@canonry/canonry 7.118.1 → 7.118.2

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 (140) hide show
  1. package/assets/assets/{AccessControls-CCvvzEec.js → AccessControls-Dw14Y8Zb.js} +1 -1
  2. package/assets/assets/{AgentSetupPage-B-vXoIII.js → AgentSetupPage-QCAFqYqz.js} +1 -1
  3. package/assets/assets/{AuditHistoryPanel-ClexSdME.js → AuditHistoryPanel-C06iViSe.js} +1 -1
  4. package/assets/assets/{BacklinksPage-QMPUVhzl.js → BacklinksPage-CJqWfjy1.js} +1 -1
  5. package/assets/assets/{ChartPrimitives-Dd9VFWrj.js → ChartPrimitives-DBTchs1y.js} +1 -1
  6. package/assets/assets/{HistoryPage-CzQLFEZG.js → HistoryPage-Dif-fQuy.js} +1 -1
  7. package/assets/assets/{MeasurementPropertyPage-BTgy_3-R.js → MeasurementPropertyPage-BJFfATTB.js} +1 -1
  8. package/assets/assets/{ProjectPage-DLgYLplH.js → ProjectPage-CFe_NEmJ.js} +3 -3
  9. package/assets/assets/{RunsPage-CnWXQk8q.js → RunsPage-DUnwiusE.js} +1 -1
  10. package/assets/assets/{ServerTrafficSection-DqVZznpe.js → ServerTrafficSection-CBCczz52.js} +3 -3
  11. package/assets/assets/{SettingsPage-D2j93m5Q.js → SettingsPage-BQRQYuJ9.js} +1 -1
  12. package/assets/assets/{ToneBadge-Dym1_0XC.js → ToneBadge-CViol5aK.js} +4 -4
  13. package/assets/assets/{TrafficPage-CzieybRn.js → TrafficPage-jtQlqa0x.js} +1 -1
  14. package/assets/assets/{TrafficSourceDetailPage-CtmGPXZc.js → TrafficSourceDetailPage-8p8kPet2.js} +1 -1
  15. package/assets/assets/{account-context-ClThq0Zv.js → account-context-B1G3xhE1.js} +1 -1
  16. package/assets/assets/{agent-trust-copy-C0WnWM9W.js → agent-trust-copy-CMgWNJn0.js} +1 -1
  17. package/assets/assets/{card-C-9Q2kJl.js → card-B8kjwkFR.js} +1 -1
  18. package/assets/assets/{index-CzPXJ0Qs.js → index-DxNmD1SS.js} +3 -3
  19. package/assets/assets/{preload-helper-DV4nEYWy.js → preload-helper-DzM601DW.js} +1 -1
  20. package/assets/assets/{query-client-plQHRUyr.js → query-client-3W7wQep0.js} +1 -1
  21. package/assets/assets/{react-query-Dz0xmEkM.js → react-query-B0EpSPOn.js} +1 -1
  22. package/assets/assets/{react-sigma_core.esm.min-B-tTeVwc.js → react-sigma_core.esm.min-DWNI6FGP.js} +1 -1
  23. package/assets/assets/{server-traffic-BNdX8qZ4.js → server-traffic-D6FWsQIv.js} +1 -1
  24. package/assets/assets/{service-CN4HIDuw.js → service-Cy2ZA98R.js} +1 -1
  25. package/assets/index.html +9 -9
  26. package/dist/{ads-GVOTYDS3.js → ads-BJCFT2N7.js} +4 -4
  27. package/dist/{agent-RFYMQYMN.js → agent-KJ5C5BUZ.js} +8 -8
  28. package/dist/{agent-ask-MZRUCCJO.js → agent-ask-RP2FZIWH.js} +4 -4
  29. package/dist/{agent-conversations-WBP5TI3X.js → agent-conversations-N6PJOOJG.js} +4 -4
  30. package/dist/{agent-journeys-6CR77XCZ.js → agent-journeys-XK3AXOZZ.js} +4 -4
  31. package/dist/{agent-memory-PH3Y7OKJ.js → agent-memory-RKHE5BVJ.js} +4 -4
  32. package/dist/{agent-providers-3CBKNXSW.js → agent-providers-G2WHCA5Y.js} +4 -4
  33. package/dist/{agent-transcript-BN3DCK33.js → agent-transcript-SSRB4KHV.js} +4 -4
  34. package/dist/{analytics-43UR5IMY.js → analytics-QAKMM34E.js} +4 -4
  35. package/dist/{apply-POV25FNG.js → apply-6IYX6MC6.js} +4 -4
  36. package/dist/{backfill-UCUWFGCR.js → backfill-PRLYAK63.js} +11 -11
  37. package/dist/{backlinks-W3SLOIHP.js → backlinks-G52LSPEQ.js} +4 -4
  38. package/dist/{bing-HGKOR5GV.js → bing-OULTQLAJ.js} +4 -4
  39. package/dist/{bootstrap-XAKQKZCC.js → bootstrap-OATKSLBT.js} +11 -11
  40. package/dist/{cdp-WAB5BPGB.js → cdp-NVM5IFD2.js} +8 -8
  41. package/dist/{chunk-QOFWKOKD.js → chunk-25KN55WQ.js} +4 -4
  42. package/dist/{chunk-7JFPGEXQ.js → chunk-2M37UZGH.js} +4 -4
  43. package/dist/{chunk-SZSZSOXP.js → chunk-3JHLIEOY.js} +2 -2
  44. package/dist/{chunk-HQ6GLLVU.js → chunk-3MGALUWM.js} +2 -2
  45. package/dist/{chunk-ZFHVEEXB.js → chunk-3QFIBU25.js} +64 -24
  46. package/dist/{chunk-7ACE6HGU.js → chunk-43QG3FYE.js} +3 -3
  47. package/dist/{chunk-EHOA2RFV.js → chunk-4INTWV22.js} +6 -6
  48. package/dist/{chunk-GSQQ6VVV.js → chunk-4O5ZWHZ4.js} +1 -1
  49. package/dist/{chunk-NZZSWCNM.js → chunk-552V4T75.js} +1 -1
  50. package/dist/{chunk-V2VWIGVT.js → chunk-6WBIJWKO.js} +1 -1
  51. package/dist/{chunk-XDOP2ANX.js → chunk-7CXUZI6H.js} +3087 -3058
  52. package/dist/{chunk-6AJ4Y3QL.js → chunk-7QFB2AI4.js} +2 -2
  53. package/dist/{chunk-ISLMLTSB.js → chunk-AABZZA7S.js} +8 -8
  54. package/dist/{chunk-U3TO2MFS.js → chunk-AR2AXWZC.js} +4 -4
  55. package/dist/{chunk-LSNAMUIJ.js → chunk-ATHSMFDP.js} +2 -2
  56. package/dist/{chunk-A5X7CSVB.js → chunk-BTM2WKQL.js} +5 -5
  57. package/dist/{chunk-WKYQRF5A.js → chunk-G2IJGOVF.js} +3 -3
  58. package/dist/{chunk-6UNZDUB6.js → chunk-G4NYHN56.js} +1 -1
  59. package/dist/{chunk-YWRXCL3J.js → chunk-H5LYOND2.js} +22 -22
  60. package/dist/{chunk-IOOJ7DQ6.js → chunk-J2JJFHAM.js} +1 -1
  61. package/dist/{chunk-G2JP3KNY.js → chunk-JMYX2YJ3.js} +4 -4
  62. package/dist/{chunk-HZTKUGQ4.js → chunk-K7BPL2BY.js} +3 -3
  63. package/dist/{chunk-4A2JURHR.js → chunk-KV5I5RJ3.js} +2 -2
  64. package/dist/{chunk-DSDNQLJO.js → chunk-KWLCI5HP.js} +4 -4
  65. package/dist/{chunk-WEZC57IK.js → chunk-MUE2JCK7.js} +5 -5
  66. package/dist/{chunk-GY7YLVMD.js → chunk-PPIXSQNM.js} +4 -4
  67. package/dist/{chunk-6ORW2OUQ.js → chunk-QM37PRXI.js} +1 -1
  68. package/dist/{chunk-VU3TF5CD.js → chunk-QP7S34UT.js} +1 -1
  69. package/dist/{chunk-Q7LU7GTH.js → chunk-R6SX4KC6.js} +1 -1
  70. package/dist/{chunk-LBNJVTGN.js → chunk-RJDIAWNE.js} +2 -2
  71. package/dist/{chunk-35DM6ZZ2.js → chunk-T6ILJ2FW.js} +2 -2
  72. package/dist/{chunk-ILDAN5TW.js → chunk-TVU3SGB3.js} +1 -1
  73. package/dist/{chunk-TO6J7C35.js → chunk-U2GFFMHS.js} +5 -5
  74. package/dist/{chunk-SBLC7FYP.js → chunk-UZBV2MFC.js} +2 -2
  75. package/dist/{chunk-OBRB7CN6.js → chunk-WHFZQMDU.js} +369 -369
  76. package/dist/{chunk-G3HBHMML.js → chunk-YB7QBOA6.js} +1 -1
  77. package/dist/{chunk-377K7XSP.js → chunk-ZTN2BG4D.js} +4 -4
  78. package/dist/{citations-IMPVSN25.js → citations-7ZI2SULG.js} +5 -5
  79. package/dist/{cli-catalog-OFMWOBCF.js → cli-catalog-RO57BEAG.js} +4 -4
  80. package/dist/cli-commands-23N5ZW76.js +18 -0
  81. package/dist/cli.js +14 -14
  82. package/dist/{competitor-2NFTABZM.js → competitor-PAILSWRL.js} +4 -4
  83. package/dist/{content-HYV3JOIS.js → content-VNVROYY3.js} +4 -4
  84. package/dist/{dashboard-OY75SNYT.js → dashboard-5WAAR33F.js} +7 -7
  85. package/dist/{demo-643NLHIX.js → demo-QD55GHC7.js} +3 -3
  86. package/dist/{demo-server-W7YKCOQJ.js → demo-server-KMJC4TWS.js} +13 -13
  87. package/dist/{discover-VIQMARSR.js → discover-Y4OYY55Y.js} +5 -5
  88. package/dist/{discover-eval-M5RRXWMX.js → discover-eval-DZGZH6ED.js} +4 -4
  89. package/dist/{doctor-HATXMESK.js → doctor-7BOKC4J6.js} +4 -4
  90. package/dist/{evidence-C3IBS7TO.js → evidence-RIJWDHZR.js} +4 -4
  91. package/dist/{export-cmd-F674KINC.js → export-cmd-J4LZ5GSD.js} +4 -4
  92. package/dist/{ga-AWBTXHSN.js → ga-IEY3C76P.js} +4 -4
  93. package/dist/{gbp-NAZYXN4S.js → gbp-OP7B6R6Z.js} +4 -4
  94. package/dist/{google-IYDAWLIV.js → google-G7MNB3XJ.js} +5 -5
  95. package/dist/{google-marketing-NHV7BCQM.js → google-marketing-7562CCEM.js} +2 -2
  96. package/dist/{health-cmd-ASZUPWDG.js → health-cmd-INJ5FWJ7.js} +5 -5
  97. package/dist/{history-TFLEYUHW.js → history-34NHNH4B.js} +4 -4
  98. package/dist/index.d.ts +43 -43
  99. package/dist/index.js +26 -26
  100. package/dist/{init-CYZUNXPV.js → init-QKAAFP7Z.js} +13 -13
  101. package/dist/{insights-VMU43BJM.js → insights-TPITCFIE.js} +4 -4
  102. package/dist/intelligence-service-3ZR7CGWF.js +15 -0
  103. package/dist/{journeys-DSPUDWGM.js → journeys-AGSHRJVG.js} +4 -4
  104. package/dist/{keys-K56VXNJX.js → keys-ZGA5ZBFE.js} +4 -4
  105. package/dist/{keyword-FCMS45PF.js → keyword-XQA6K462.js} +4 -4
  106. package/dist/{logs-75HP7UD3.js → logs-D2HPGLMI.js} +4 -4
  107. package/dist/{mcp-D7P73XVO.js → mcp-UKYWUOA6.js} +5 -5
  108. package/dist/mcp.js +10 -10
  109. package/dist/{measurement-plan-AX6G3RWU.js → measurement-plan-3S2BV34R.js} +6 -6
  110. package/dist/{notify-QUOFVHKS.js → notify-PKXIBY2X.js} +4 -4
  111. package/dist/{organic-evidence-PPHL7QGS.js → organic-evidence-6WAJC7CC.js} +4 -4
  112. package/dist/{overview-C6SSTCC6.js → overview-YIMXGGQC.js} +6 -6
  113. package/dist/{project-MMQ2H6TH.js → project-WNMIV5OV.js} +4 -4
  114. package/dist/{project-setup-6DGYQAG2.js → project-setup-OSAJFEWF.js} +4 -4
  115. package/dist/{query-EJGNRC2F.js → query-GN654GYL.js} +4 -4
  116. package/dist/{research-X43RAY3W.js → research-HR67DZJE.js} +4 -4
  117. package/dist/{results-export-FOQXK6NA.js → results-export-CNAAOWQX.js} +4 -4
  118. package/dist/{run-D4CFXIFR.js → run-M7F6BMTH.js} +6 -6
  119. package/dist/{schedule-UFOJOPKA.js → schedule-LKGWXMPF.js} +4 -4
  120. package/dist/{search-6C3ZPK24.js → search-MRWOL2M3.js} +4 -4
  121. package/dist/{serve-RBBLESEQ.js → serve-YR2A6YGF.js} +27 -27
  122. package/dist/{session-4BIHTXY3.js → session-JSZLON4Q.js} +14 -14
  123. package/dist/{settings-6AGLHMPI.js → settings-O2TJKLTN.js} +4 -4
  124. package/dist/{sitemaps-FIN5CVTH.js → sitemaps-35MYNHN6.js} +4 -4
  125. package/dist/{skills-3ZD3N6S7.js → skills-CNUBIGXM.js} +3 -3
  126. package/dist/{snapshot-EFW3B6TM.js → snapshot-G67JDGMY.js} +4 -4
  127. package/dist/{src-QSFAXHBF.js → src-T2CVI44I.js} +2 -2
  128. package/dist/{status-CLWEOZP4.js → status-EBOPJY3L.js} +6 -6
  129. package/dist/{support-P5H555LC.js → support-Q735EEZ7.js} +2 -2
  130. package/dist/{technical-aeo-IVNC26PJ.js → technical-aeo-N4WO2GSS.js} +4 -4
  131. package/dist/{telemetry-ZUFUNFST.js → telemetry-CAZH47YY.js} +5 -5
  132. package/dist/{tools-V2V7RUTA.js → tools-FCS5X36N.js} +12 -12
  133. package/dist/{traffic-CN667DLE.js → traffic-G3UAF52O.js} +25 -8
  134. package/dist/{trends-2XLTO3EN.js → trends-JEQCIQZU.js} +4 -4
  135. package/dist/{users-NXZSJ7CM.js → users-5QFNLFVU.js} +4 -4
  136. package/dist/{visibility-stats-DTJD4TEN.js → visibility-stats-MQLGIZEM.js} +5 -5
  137. package/dist/{wordpress-LE6UNQCX.js → wordpress-NMLL7F6A.js} +4 -4
  138. package/package.json +1 -1
  139. package/dist/cli-commands-TJHBC2HQ.js +0 -18
  140. package/dist/intelligence-service-NGD2KVLQ.js +0 -15
@@ -1,9 +1,9 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./react-sigma_core.esm.min-B-tTeVwc.js","./rolldown-runtime-XKyaHtl9.js","./vendor-lucide-7AWeFVeL.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,H as s,I as c,L as l,P as u,Q as d,T as f,V as p,Y as m,Z as h,a as g,at as _,b as v,c as y,et as b,g as x,h as S,i as C,lt as w,n as T,p as E,s as D,st as O,t as k,ut as A,v as j,w as M}from"./vendor-lucide-7AWeFVeL.js";import{a as N,i as P,o as ee,r as te,s as ne,t as F}from"./vendor-radix-WbUsEVSn.js";import{r as I}from"./vendor-markdown-CQdHmjWd.js";import{O as L,T as re,_ as ie,d as ae,f as R,p as z,r as B,u as V,v as oe,x as H}from"./vendor-tanstack-C613NhXZ.js";import{a as se,c as ce,d as le,f as ue,h as de,i as fe,l as pe,m as me,n as he,o as ge,p as _e,r as ve,s as ye,t as be,u as xe}from"./vendor-recharts-DCxaNd0O.js";import{$c as Se,$o as Ce,$s as U,$t as we,At as Te,B as Ee,Bc as De,Bo as Oe,Bs as ke,Cc as Ae,Co as W,Cs as je,Ct as Me,Dc as Ne,Do as Pe,Ec as Fe,Eo as Ie,Et as Le,Fc as Re,Fo as ze,Ft as Be,Gn as Ve,Go as He,Gs as Ue,Gt as We,H as Ge,Hc as Ke,Hn as qe,Ho as G,I as Je,Io as Ye,Jc as Xe,Jo as Ze,Js as Qe,Jt as $e,Kc as et,Ko as tt,Ks as nt,Kt as rt,Lc as it,Nc as at,Nt as ot,Oc as st,Oo as ct,P as lt,Pc as ut,Qc as dt,Qo as ft,Qs as pt,Qt as mt,R as ht,Rn as gt,Rt as _t,Sc as vt,Sn as yt,So as bt,Ss as xt,St,Tc as Ct,To as wt,Uc as Tt,Un as Et,Uo as Dt,Ut as Ot,V as kt,Vc as At,Vo as jt,Wo as Mt,Ws as Nt,Wt as Pt,Xa as Ft,Xo as It,Xs as Lt,Y as Rt,Ya as zt,Yc as Bt,Yo as Vt,Ys as Ht,Z as Ut,Zc as Wt,Zo as Gt,Zs as Kt,Zt as qt,_ as Jt,_s as Yt,_t as Xt,a as Zt,ac as Qt,as as $t,bn as en,bo as tn,bs as nn,c as rn,cc as an,cl as on,cs as sn,d as cn,dc as ln,dt as un,ec as dn,el as fn,en as pn,es as mn,fc as hn,fs as gn,g as _n,gs as vn,gt as yn,h as bn,hc as xn,hs as Sn,is as Cn,jn as wn,jt as K,kc as Tn,ko as En,kt as Dn,l as On,lc as kn,ls as An,lt as jn,m as Mn,mn as Nn,ms as Pn,nc as Fn,nl as In,nn as Ln,ns as Rn,o as zn,oc as Bn,ol as Vn,os as Hn,p as Un,ps as Wn,pt as Gn,q as Kn,qo as qn,qs as Jn,qt as Yn,r as q,rs as Xn,s as Zn,sl as Qn,t as J,tc as $n,tl as er,ts as tr,tt as nr,u as rr,uc as ir,uo as ar,us as or,ut as sr,vc as cr,vn as lr,vs as ur,vt as dr,w as fr,wo as pr,ws as mr,wt as hr,xc as gr,xn as _r,xo as vr,xs as yr,xt as Y,yn as br,ys as xr,zc as Sr}from"./ToneBadge-Dym1_0XC.js";import{t as Cr}from"./preload-helper-DV4nEYWy.js";import{B as wr,C as Tr,D as Er,F as Dr,I as Or,L as kr,M as Ar,N as jr,O as Mr,P as Nr,R as Pr,S as Fr,T as Ir,_ as Lr,a as Rr,b as zr,c as Br,d as Vr,f as Hr,g as Ur,h as Wr,i as Gr,j as Kr,k as qr,l as Jr,m as Yr,n as Xr,o as Zr,p as Qr,r as $r,s as ei,t as ti,u as ni,x as ri,y as ii,z as ai}from"./ChartPrimitives-Dd9VFWrj.js";import{r as oi}from"./account-context-ClThq0Zv.js";import{t as si}from"./async-handler-Bj3TnIRw.js";import{d as ci,l as li,n as ui,o as di,s as fi,t as pi,u as mi}from"./query-client-plQHRUyr.js";import{$ as hi,$t as gi,A as _i,An as vi,At as yi,B as bi,Bn as xi,Bt as Si,C as Ci,Ct as wi,D as Ti,Dt as Ei,E as Di,F as Oi,Fn as ki,Ft as Ai,G as ji,Gn as Mi,Gt as Ni,H as Pi,Hn as Fi,Ht as Ii,I as Li,In as Ri,It as zi,J as Bi,Jn as Vi,Jt as Hi,K as Ui,Kn as Wi,Kt as Gi,L as Ki,Ln as qi,M as Ji,Mn as Yi,N as Xi,Nn as Zi,Nt as Qi,O as $i,P as ea,Pn as ta,Pt as na,Q as ra,Qt as ia,R as aa,Rn as oa,Rt as sa,S as ca,St as la,T as ua,Tn as da,U as fa,V as pa,Vn as ma,Vt as ha,W as ga,Wn as _a,X as va,Xt as ya,Y as ba,Yt as xa,Z as Sa,Zt as Ca,_ as wa,_t as Ta,an as Ea,at as Da,b as Oa,bn as ka,c as Aa,ct as ja,d as Ma,dn as Na,dt as Pa,en as Fa,et as Ia,f as La,fn as Ra,ft as za,g as Ba,gt as Va,h as Ha,ht as Ua,in as Wa,it as Ga,j as Ka,jn as qa,jt as Ja,k as Ya,kn as Xa,lt as Za,m as Qa,mt as $a,n as eo,nn as to,nt as no,on as ro,ot as io,p as ao,pn as oo,pt as so,q as co,qn as lo,qt as uo,r as fo,rn as po,rt as mo,sn as ho,st as go,t as _o,tn as vo,tt as yo,un as bo,ut as xo,v as So,vn as Co,vt as wo,w as To,wn as Eo,wt as Do,x as Oo,xt as ko,y as Ao,yn as jo,yt as Mo,z as No,zn as Po,zt as Fo}from"./react-query-Dz0xmEkM.js";import{A as Io,B as Lo,C as Ro,D as zo,E as Bo,F as Vo,I as Ho,L as Uo,M as Wo,N as Go,O as Ko,P as qo,R as Jo,S as Yo,T as Xo,V as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,u as gs,v as _s,w as vs,x as ys,y as bs,z as xs}from"./AccessControls-CCvvzEec.js";import{n as Ss,t as Cs}from"./extract-error-message-C1RkZ7dQ.js";import{t as X}from"./InfoTooltip-laRfQjZw.js";import{t as ws}from"./card-C-9Q2kJl.js";import{$ as Ts,A as Es,At as Ds,B as Os,C as ks,Ct as As,D as js,Dt as Ms,E as Ns,Et as Ps,F as Fs,G as Is,H as Ls,I as Rs,J as zs,K as Bs,L as Vs,Mt as Hs,N as Us,Nt as Ws,O as Gs,Ot as Ks,P as qs,Q as Js,R as Ys,S 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,yt as Bc,z as Vc}from"./index-CzPXJ0Qs.js";import{t as Hc}from"./Hint-DiyoPGOX.js";import{t as Uc}from"./AuditHistoryPanel-ClexSdME.js";import{a as Wc,i as Gc,l as Kc,n as qc,o as Jc,r as Yc,t as Xc,u as Zc}from"./service-CN4HIDuw.js";import{a as Qc,c as $c,s as el,t as tl}from"./server-traffic-BNdX8qZ4.js";import{i as nl,n as rl,r as il}from"./agent-trust-copy-C0WnWM9W.js";import{t as al}from"./ServerTrafficSection-DqVZznpe.js";function ol(e){return e.split(/[?#]/)[0]||`/`}var sl=1e6;function cl(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/sl);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(A(),1),ll={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 ul(e,t){return e!==`viewer`||t!==null}function dl(e,t){return e===`research`&&!t?`tracked`:e}function fl(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 pl(e,t){return e.find(e=>e.kind===t.measurementScope&&(e.kind===`project`||e.id===t.measurementScopeKey))}function ml(e){return e.measurementScope!==`project`||e.marketKey!==void 0}function hl(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=I();function gl({state:e,label:t,className:n}){return(0,Q.jsx)(J,{tone:Bc(e),className:n,children:t??(e===`not-measured`?kr.label:Or(e))})}function _l({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 vl=[{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],yl={"non-brand":`Non-brand`,branded:`Branded`,pooled:`All queries`},bl={"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.`},xl=`Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.`;function Sl(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:U(e.score,et.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 Cl({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:xl})]}),(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:U(e.share)})]},e.label))})]})}function wl({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=Sl(u,{hasCompetitors:n.length>0,unavailable:e.unavailable===!0,noRun:e.breakdown.snapshotsTotal===0&&e.branded.snapshotsTotal===0,otherClassHasData:d.snapshotsTotal>0}),p=Nr(f.headline),m=l===`non-brand`?oc[e.tone]:`text-secondary`;function h(e){let t=vl.findIndex(e=>e.value===c),n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%vl.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+vl.length)%vl.length:e.key===`Home`?n=0:e.key===`End`&&(n=vl.length-1),n!==null&&(e.preventDefault(),i(vl[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:bl[l]})]}),s?(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":a,className:`segmented flex-wrap`,onKeyDown:h,children:vl.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:yl[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:yl[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)(Cl,{breakdown:u,projectLabel:t})]})}function Tl({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 El=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],Dl={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,all:`all checks`},Ol={"non-brand":`Non-brand`,branded:`Branded`,all:`All queries`},kl={"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.`},Al={"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`},jl=`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.`,Ml=100;function Nl(e){return e?e.evidence.answeredResults>0||e.evidence.sourceResults>0?`measured`:`not-measured`:`unavailable`}function Pl(e){return e===`unavailable`?`Unavailable`:`Not measured`}function Fl(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 Il(e,t,n){return e===1?t:n}function Ll(e){let t=e.label.trim(),n=Xe(e.domain);return t&&t.toLowerCase()!==e.domain.toLowerCase()&&t.toLowerCase()!==n.toLowerCase()?t:null}function Rl({row:e,aliases:t=[],autoAliases:n=[]}){let r=Ll(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 zl(e){let t=Ll(e);return t?`${t} (${e.domain})`:e.domain}function Bl(e,t){return t&&e>=Ml?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:e})}function Vl({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 Hl({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 Ul({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:Pl(n)})}function Wl({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`:Pl(t)});let{figure:r,sign:i}=Nr(U(e,et.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 Gl({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)(Rl,{row:e})}),(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:Fl(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{count:e.mentionCount,of:n,state:t,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{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)(Hl,{urls:e.sampleUrls}):null,i?(0,Q.jsx)(Vl,{action:`pin`,domain:e.domain,mutation:i}):null]})})]},e.domain))})]})})}function Kl({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 ql({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=Nl(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)(Vl,{action:`unpin`,domain:e.domain,mutation:l}):null:c?(0,Q.jsx)(Vl,{action:`pin`,domain:e.domain,mutation:c}):null:null,N=w.some(e=>M(e)!==null),P=[m,E?Ol[E]:null,Dl[e],t?.basis?C?`observed competitors only`:`tracked competitors only`:null].filter(Boolean).join(` · `),ee=[];if(t&&!C&&w.length===0&&ee.push({key:`no-pins`,text:`No pinned competitors.`}),t?.reason&&ee.push({key:`reason`,text:`Mention share: ${Al[t.reason]}`}),t&&T.length>0){let e=T.length;ee.push({key:`others`,text:O&&e>=Ml?`${Ml} or more other competitors seen`:`${e} other ${Il(e,`competitor`,`competitors`)} seen`})}D>0&&ee.push({key:`pending`,text:`${t?.scope.kind===`all-markets`?`Pending publication across markets`:`Pending publication`}: ${D} ${Il(D,`competitor`,`competitors`)}`});let te=[x&&x.missingAnswerTextResults>0?`Answer data incomplete`:null,x&&x.incompleteSourceResults>0?`Citation data incomplete`:null].filter(Boolean);te.length>0&&ee.push({key:`incomplete`,text:te.join(` · `),className:oc.caution});let ne=[];if(t&&x){ne.push(t.runCount===void 0?(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,Il(x.answeredResults,`answer`,`answers`)]}):(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:t.runCount}),` `,Il(t.runCount,`check`,`checks`),`, `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,Il(x.answeredResults,`answer`,`answers`)]})),!t.reason&&S===`measured`&&t.project.shareOfVoice!==null&&ne.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`]})),ne.push((0,Q.jsxs)(Q.Fragment,{children:[`Answers with source links: `,(0,Q.jsx)(`strong`,{children:x.sourceResults})]})),T.length===0&&ne.push(`Other competitors seen: none`),x.missingAnswerTextResults>0&&ne.push((0,Q.jsxs)(Q.Fragment,{children:[`No answer text: `,(0,Q.jsx)(`strong`,{children:x.missingAnswerTextResults}),` `,Il(x.missingAnswerTextResults,`answer`,`answers`),`, left out of mention share`]})),x.incompleteSourceResults>0&&ne.push((0,Q.jsxs)(Q.Fragment,{children:[`Incomplete source lists: `,(0,Q.jsx)(`strong`,{children:x.incompleteSourceResults}),` `,Il(x.incompleteSourceResults,`answer`,`answers`),`, not counted as misses`]}));let e=x.excludedProbeResults+x.excludedNonCompletedResults;e>0&&ne.push((0,Q.jsxs)(Q.Fragment,{children:[`Left out: `,(0,Q.jsx)(`strong`,{children:e}),` `,Il(e,`answer`,`answers`),` from spot checks or unfinished checks`]}))}let F=[...t?[{name:`You`,row:t.project}]:[],...w.map(e=>({name:e.domain,row:e}))].filter(e=>e.row.sampleUrls.length>0);S===`measured`&&F.length>0&&ne.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:F.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&&ne.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other competitors seen: `,Bl(T.length,O)]}),(0,Q.jsx)(`div`,{className:`av-subdetails-body`,children:(0,Q.jsx)(Gl,{rows:T,state:S,named:k,cited:A,onPin:_?c:void 0})})]}));let I=t?.observedNames??[];if(I.length>0){let e=t?.observedNamesTotal??I.length;ne.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Company names in answers: `,e>I.length?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:I.length}),` of `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:I.length})]}),(0,Q.jsx)(`ul`,{className:`av-subdetails-body`,children:I.map(e=>(0,Q.jsxs)(`li`,{children:[e.name,` · `,e.answerCount,` `,Il(e.answerCount,`answer`,`answers`)]},e.name))})]}))}return b.length>0&&ne.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other sites cited: `,Bl(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:[zl(e),` · `,Fl(e.surfaceClass),` · `,e.citationCount,` `,Il(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?`${kl[E]} ${jl}`:jl})]}),(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)(As,{label:`Competitors over time window`,className:`flex-wrap`,options:El,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)(Wl,{percent:t.project.shareOfVoice,state:S,toneClass:j})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{count:t.project.mentionCount,of:k,state:S,toneClass:j})}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(Ul,{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:jr(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)(Rl,{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:Fl(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{percent:e.shareOfVoice,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{count:e.mentionCount,of:k,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{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,ee.length>0?(0,Q.jsx)(`div`,{className:`space-y-1 text-label-13 text-secondary`,children:ee.map(e=>(0,Q.jsx)(`p`,{className:e.className,children:e.text},e.key))}):null]}),(0,Q.jsx)(Tl,{items:ne}),_&&u?(0,Q.jsx)(`div`,{className:`border-t border-subtle px-5 py-3`,children:(0,Q.jsx)(Kl,{onAddCompetitor:u})}):null]})}function Jl(e){return e.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function Yl(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 Xl(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 Zl({value:e,headLength:t,tailLength:n,className:r,title:i}){let a=Xl(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 Ql({rows:e,getSearchText:t,pageSize:n=25}){let[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(1),s=(0,Z.useMemo)(()=>Jl(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 $l({value:e,onChange:t,label:n,placeholder:r=`Filter rows`,className:i}){return(0,Q.jsxs)(`div`,{className:`relative ${i??``}`,children:[(0,Q.jsx)(S,{"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=>{Ve(e.target.value),t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&Ve(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 eu({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,f=r===void 0?void 0:Math.max(1,Math.ceil(r/t)),p=i??(f!==void 0&&e<f),m=e>1||p;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?`${p?`+`:``} ${o}`:` of ${r.toLocaleString(`en-US`)} ${o}`]}),m?(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)(d,{"aria-hidden":`true`,className:`size-3.5`}),`Previous`]}),(0,Q.jsx)(`span`,{className:`tabular-nums`,children:f===void 0?`Page ${e}`:`Page ${e} of ${f}`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>a(e+1),disabled:c||!p,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)(h,{"aria-hidden":`true`,className:`size-3.5`})]})]}):null]})}function tu({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":kr.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(`/`)?Re(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(`/`)?Re(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 nu(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 ru(e){let t=e.filter(e=>e!==`pending`);if(t.length===0)return`pending`;let n=ze(t.map(iu));return n===cr.cited?t.includes(`cited`)?`cited`:`emerging`:n===cr[`not-cited`]?t.includes(`lost`)?`lost`:`not-cited`:`not-measured`}function iu(e){switch(e){case`cited`:case`emerging`:return cr.cited;case`not-cited`:case`lost`:return cr[`not-cited`];case`not-measured`:return cr[`not-measured`]}}var au=320;function ou(e){return e===`branded`?`Branded`:e===`non-brand`?`Non-brand`:`Unclassified`}function su(e){return e===`non-brand`?0:e===`branded`?1:2}function cu(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 lu(e){return e.phrase}function uu(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 du(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 kr.label;case`lost`:return`Lost`;case`emerging`:return`Emerging`;case`pending`:return`Pending`}}function fu(e,t){return e.map(e=>pu(e,t))}function pu(e,t){return t===`citations`?e:{...e,citationState:uu(e,t),runHistory:e.runHistory.map(e=>({...e,citationState:uu(e,t)}))}}function mu(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:kr.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 hu(e){let t=nu(fu(e,`mentions`)),n=nu(e);return[mu(t,`mentions`),mu(n,`citations`)]}function gu({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 _u({items:e}){return(0,Q.jsx)(`div`,{className:`query-evidence-signals`,"aria-label":`Latest run mention and citation signals`,children:hu(e).map(e=>(0,Q.jsx)(gu,{signal:e},e.key))})}function vu({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)(qs,{}),t]})}):null,e?(0,Q.jsx)(Fs,{queryClass:e,manage:!!t}):null]})}function yu({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=Ys(),[p,m]=(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(pu(r,p)),s.rawItems.push(r),n.set(o,s)}return[...n.values()].sort((e,t)=>su(e.queryClass)-su(t.queryClass))},[e,p,t,S]),E=Ql({rows:(0,Z.useMemo)(()=>T.filter(e=>v===`all`||(v===`unclassified`?e.queryClass===null:e.queryClass===v)),[T,v]),getSearchText:lu}),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(Ye)),[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`,ee=p===`mentions`?`mentioned`:`cited`;return(0,Q.jsxs)(`div`,{className:`query-evidence`,children:[(0,Q.jsx)(vu,{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:()=>m(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`;m(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)($l,{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:Bo(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`})})]})}),cu(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:[ou(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),m=`${l}-query-${d}`,_=O.has(Ye(n)),v=ru(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=nu(a),S=a.filter(e=>e.citationState===cr.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 ${ee}${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":m,"aria-expanded":s,onClick:t=>{t.stopPropagation(),M(e)},children:[(0,Q.jsx)(h,{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:m,className:`query-evidence-meta`,children:[(0,Q.jsx)(`span`,{children:ou(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)(gl,{state:v,label:du(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)(Rs,{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)(tu,{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)(_u,{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?Bo(e.provider):`Awaiting engine`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(gl,{state:e.citationState,className:`rounded-none border-0 bg-transparent p-0 text-label-14`,label:du(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)(tu,{history:e.runHistory,signal:p})}),(0,Q.jsx)(`td`,{className:`evidence-change-cell`,children:_?null:(0,Q.jsx)(_u,{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?Bo(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)(Su,{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)(eu,{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 bu(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 xu(e,t){let n=t.toLowerCase().replace(/^www\./,``);return(e.citedCompetitorDomains??[]).some(e=>e.toLowerCase().replace(/^www\./,``)===n)}function Su({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)(Cu,{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:kr.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}),xu(e,Bt(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,xu(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)(Cu,{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 Cu({item:e,onViewFull:t,contextOnly:n=!1}){let{matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}=e,s=(0,Z.useMemo)(()=>bu({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>au;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:au,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,xu(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 wu({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&&Et(`window`),n(e)},children:i?i(e):e},e))})}var Tu=[``,`sm:grid-cols-1`,`sm:grid-cols-2`,`sm:grid-cols-3`],Eu=[``,`lg:grid-cols-1`,`lg:grid-cols-2`,`lg:grid-cols-3`,`lg:grid-cols-4`,`lg:grid-cols-5`,`lg:grid-cols-6`],Du=14,Ou=Rr[1],ku={current:`current`,previous:`previous`},Au=e=>e.series?.filter(e=>e.current!==null).length??0,ju=e=>e.interactive??Au(e)>=2,Mu=e=>e!=null;function Nu(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Pu(e){if(!e)return``;if(e.kind===`note`)return Nu(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 Fu({date:e,observedAt:t}){return t?Qr(Wr(t)):ni(e)}function Iu({date:e,observedAt:t}){return t?Ur(Wr(t)):Number(e.slice(0,4))}function Lu(e){return e.label??Fu(e)}function Ru(e,t){if(!e)return;let n=`since ${Lu(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`?`${dn(r).magnitude} pts`:r.toLocaleString(),direction:e.difference>0?`up`:`down`,tone:e.tone,basis:n}}function zu(e){let t=new Set(e.map(e=>e.change?Lu(e.change.basis):null)),[n]=[...t];return t.size===1&&n?`since ${n}`:void 0}function Bu(e){return e.series.map(e=>({date:e.observedAt??e.date,current:e.value,...e.label?{label:e.label}:{}}))}function Vu(e,t){if(e.label&&t.label)return e.label===t.label?e.label:`${e.label} to ${t.label}`;let n=(e,t)=>t?`${Fu(e)}, ${Iu(e)}`:Fu(e);return`${n(e,Iu(e)!==Iu(t))} to ${n(t,!0)}`}function Hu({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`?_:w,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 Uu({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 Wu(e,t){return e.formatExact?.(t)??e.formatValue?.(t)??t.toLocaleString()}function Gu({active:e,payload:t,figure:n,previousLabel:r,rowLabel:i}){let a=t?.[0]?.payload;if(!e||!a)return null;let o=e=>Mu(e)?Wu(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?Jr(a.previousDate):r}),(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:o(a.previous)})]})]})}function Ku({name:e,groups:t,mode:n=`single`,selected:i,onSelect:a,span:o,cadence:s=`day`,instants:c=!1,currentLabel:l,previous:u,chart:d,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=>c?Hr(Wr(e)):Jr(e),E=e=>e.label??T(e.date),D=e=>Yr(Wr(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===i[0]&&ju(e)):void 0,ee=P?.series??[],te=c?ee.map(e=>({...e,at:Date.parse(e.date)})):ee,ne=new Map(ee.flatMap(e=>e.label?[[e.date,e.label]]:[])),F=!!u?.available&&ee.some(e=>Mu(e.previous)),I=ee.some(e=>e.current!==null||F&&Mu(e.previous)),L=x<=1||Au(P??{key:``,label:``,value:``})>=x,re=!F||!O.has(ku.current),ie=F&&!O.has(ku.previous),ae=Au(P??{key:``,label:``,value:``})<Du?`linear`:`monotone`,R=`per ${s}`,z=l?Nu(l):o,B=P?`${P.label} ${R}${z?`, ${z}`:``}${F?` and the previous period`:``}`:``,V=N.filter(ju).map(e=>e.key),oe=V.includes(i[0]??``)?i[0]:V[0],H=e=>{a(e),document.getElementById(`${w}-tab-${e}`)?.focus()},se=(e,t)=>{let n=V.indexOf(t),r=V.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(),H(V[i]))},le=e=>k(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),ue=(e,t,o)=>{let s=ju(e),c=s&&i.includes(e.key),l=!!t.basis,u=[`${e.label} ${e.spokenValue??e.value}${e.detail?` ${e.detail}`:``}`,Pu(e.change)].filter(Boolean).join(`, `),d=(0,Q.jsxs)(`div`,{className:`flex min-h-5 items-center gap-1.5`,children:[n===`compare`&&s&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2.5 shrink-0 rounded-full`,style:{backgroundColor:c?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 ${c?`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)(r,{"aria-hidden":`true`,className:`pointer-events-none absolute right-0 size-3.5 ${c?`text-link`:`text-muted`}`})]}):(0,Q.jsx)(`span`,{className:`${b?`text-label-12 sm:text-label-14-strong`:`text-label-14-strong`} ${c?n===`single`?`text-link`:`text-heading`:`text-secondary`}`,children:e.label}),e.help&&(0,Q.jsx)(X,{text:e.help})]});return o?(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 ${c&&n===`single`?`bg-surface-active`:s?`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 ${c?`opacity-100`:`opacity-0`}`}),d,(0,Q.jsxs)(`button`,{type:`button`,id:`${w}-tab-${e.key}`,...n===`single`?{role:`tab`,"aria-selected":c,"aria-controls":`${w}-panel`,"aria-disabled":!s||void 0,tabIndex:s&&e.key===oe?0:-1,onKeyDown:t=>se(t,e.key)}:{"aria-pressed":c},"aria-label":u,disabled:n===`compare`&&(e.disabled||!s),onClick:s?()=>a(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 ${s?``:`cursor-default`} ${e.disabled?`disabled:cursor-not-allowed disabled:opacity-50`:``}`,children:[(0,Q.jsx)(Uu,{figure:e,active:c,compact:b}),(0,Q.jsx)(Hu,{change:e.change,hideBasis:l})]})]},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:d}),(0,Q.jsxs)(`dd`,{className:`mt-auto pt-1`,children:[(0,Q.jsx)(Uu,{figure:e,active:!1,compact:b}),(0,Q.jsx)(Hu,{change:e.change,hideBasis:l}),e.change&&(0,Q.jsx)(`span`,{className:`sr-only`,children:Pu(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(ju),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`} ${Tu[Math.min(t.figures.length,3)]} ${Eu[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=>ue(e,t,!0))}):(0,Q.jsx)(`dl`,{className:o,children:t.figures.map(e=>ue(e,t,!1))})]},t.key)})}),(0,Q.jsxs)(`div`,{id:`${w}-panel`,...n===`single`&&P&&V.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`?d:!P||!I||!L?(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":B,style:{height:_},children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:[...te],margin:{top:8,right:0,bottom:0,left:4},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),c?(0,Q.jsx)(fe,{dataKey:`at`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:D,minTickGap:32,padding:{left:12,right:12}}):(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:e=>ne.get(e)??Vr(e),minTickGap:32,padding:ne.size>0?{left:40,right:40}:{left:12,right:12}}),(0,Q.jsx)(ve,{orientation:`right`,reversed:P.reverseValueAxis,domain:P.reverseValueAxis?[1,`auto`]:void 0,tick:Xr,tickLine:!1,axisLine:!1,width:52,allowDecimals:P.allowDecimals??!1,tickFormatter:e=>P.formatValue?.(e)??e.toLocaleString()}),(0,Q.jsx)(_e,{cursor:{stroke:Gr.textFaint,strokeWidth:1},wrapperStyle:{outline:`none`},content:(0,Q.jsx)(Gu,{figure:P,previousLabel:F?u?.label:void 0,rowLabel:E})}),ie&&(0,Q.jsx)(ye,{type:ae,dataKey:ku.previous,stroke:Ou,strokeOpacity:.65,strokeWidth:1.5,strokeDasharray:`4 4`,dot:!1,activeDot:{r:3,strokeWidth:0,fill:Ou},connectNulls:!1,isAnimationActive:M,animationDuration:320,animationEasing:`ease-out`}),re&&(0,Q.jsx)(ye,{type:ae,dataKey:ku.current,stroke:Ou,strokeWidth:2.25,dot:ae===`linear`&&{r:3,strokeWidth:0,fill:Ou},activeDot:{r:5,strokeWidth:2,stroke:Ou,fill:`var(--color-bg)`},connectNulls:!1,isAnimationActive:M,animationDuration:320,animationEasing:`ease-out`})]})})}),n===`single`&&P&&I&&(l||y)||f||o&&!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&&I&&(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`}),(F||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&&I&&l&&u&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(qu,{label:l,checked:re,disabled:!F||re&&!ie,onChange:()=>le(ku.current),dash:void 0}),(0,Q.jsx)(qu,{label:F?u.label:`${u.label}: no earlier data`,checked:ie,disabled:!F||ie&&!re,onChange:()=>le(ku.previous),dash:`4 3`})]}),f]}),(0,Q.jsxs)(`div`,{className:`ml-auto flex flex-wrap items-center gap-x-4 gap-y-1`,children:[o&&!S&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:o}),p]})]}):null,n===`single`&&P&&I&&(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:B}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:ee.some(e=>e.label)?`Release`:`Date`}),(0,Q.jsx)(`th`,{scope:`col`,children:P.label}),F&&(0,Q.jsx)(`th`,{scope:`col`,children:u.label})]})}),(0,Q.jsx)(`tbody`,{children:ee.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`:Wu(P,e.current)}),F&&(0,Q.jsx)(`td`,{children:Mu(e.previous)?Wu(P,e.previous):`No data`})]},e.date))})]})})]})]})}function qu({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:Ou,strokeWidth:i?1.5:2.5,strokeDasharray:i})}),e]})}var Ju=`baseline`;function Yu(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,[Ju]:i.get(e)??null};for(let e of n)a[e.dataKey]=t?.[e.key]??0;return a}),series:n}}var Xu=`text-label-12-strong normal-case text-muted`;function Zu({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 Qu({children:e}){return(0,Q.jsx)(`div`,{className:`[&>details:first-child]:border-t-0`,children:e})}function $u({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 ed={3:`lg:grid-cols-3`,4:`lg:grid-cols-4`,5:`lg:grid-cols-5`};function td({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 ${ed[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 nd({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:`${Xu} 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 rd({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:Xu,children:e}),(0,Q.jsx)(X,{text:n})]}):(0,Q.jsx)(`span`,{className:Xu,children:e})})}function id(e,t,n=`desc`){return e.key===t?{key:t,dir:e.dir===`desc`?`asc`:`desc`}:{key:t,dir:n}}function ad(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 od(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 sd({groups:e,groupLabel:t,caption:n,childColumns:i,childRowKey:a,renderChildCells:o,pinLast:s,extraColumns:c=[],defaultSort:l,referenceRow:u}){let d=(0,Z.useId)(),[f,p]=(0,Z.useState)(new Set),[m,g]=(0,Z.useState)(l??{key:`sessions`,dir:`desc`}),_=(0,Z.useMemo)(()=>{let t=c.find(e=>e.key===m.key),n=t?.sortValue?od(t.sortValue,m.dir):ad(m.key,m.dir);return[...e].sort((e,t)=>Number(s?.(e)??!1)-Number(s?.(t)??!1)||n(e,t))},[e,m,s,c]),v=e=>g(t=>id(t,e,c.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 ${c.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)(nd,{label:t,sortKey:`label`,current:m.key,dir:m.dir,onSort:v,align:`left`}),(0,Q.jsx)(nd,{label:`Sessions`,sortKey:`sessions`,current:m.key,dir:m.dir,onSort:v,align:`right`}),(0,Q.jsx)(nd,{label:`Organic`,sortKey:`organicSessions`,current:m.key,dir:m.dir,onSort:v,align:`right`}),(0,Q.jsx)(nd,{label:`Paid`,sortKey:`paidSessions`,current:m.key,dir:m.dir,onSort:v,align:`right`}),(0,Q.jsx)(rd,{label:`Share`,align:`right`}),c.map(e=>e.sortValue?(0,Q.jsx)(nd,{label:e.label,sortKey:e.key,current:m.key,dir:m.dir,onSort:v,align:`right`,help:e.help},e.key):(0,Q.jsx)(rd,{label:e.label,align:`right`,help:e.help},e.key))]})}),(0,Q.jsxs)(`tbody`,{children:[u,_.map((e,t)=>{let n=f.has(e.label),s=`${d}-group-${t}`,l=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?s: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)(r,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-secondary`}):(0,Q.jsx)(h,{"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:[l,` `,l===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:U(e.share)}),c.map(t=>(0,Q.jsx)(Z.Fragment,{children:t.render(e)},t.key))]}),n&&(0,Q.jsx)(`tr`,{id:s,children:(0,Q.jsx)(`td`,{colSpan:5+c.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:i.map(e=>(0,Q.jsx)(rd,{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:o(e)},a(e)))})]})})})})]},e.label)})]})]})})}function cd(e,t){return e===`other`?Gr.textDim:Rr[t%Rr.length]}function ld({input:e,baseline:t,baselineLabel:n,label:r,height:i=224}){let{rows:a,series:o}=(0,Z.useMemo)(()=>Yu(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)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:a,margin:{top:4,right:4,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:Vr,minTickGap:24}),(0,Q.jsx)(ve,{tick:Xr,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(_e,{...ei,labelFormatter:Jr,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=cd(e.key,o.indexOf(e));return(0,Q.jsx)(ge,{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)(ye,{type:`monotone`,dataKey:`baseline`,name:`baseline`,stroke:Gr.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:cd(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:Gr.textFaint,strokeWidth:`2`,strokeDasharray:`5 3`})}),n]})]})]})}var ud=[`sessions`,`activeUsers`,`organicSessions`,`engagementRate`,`keyEvents`],dd=`canonry.siteTraffic.slots`;function fd(e){return typeof e==`string`&&Wn.some(t=>t===e)}function pd(){try{let e=JSON.parse(window.localStorage.getItem(dd)??`null`);if(Array.isArray(e)&&e.length===ud.length&&e.every(fd))return[...e]}catch{}return[...ud]}function md(e){try{window.localStorage.setItem(dd,JSON.stringify(e))}catch{}}function hd(e,t,n){let r=yr(e,t);return r===null||t===null?{kind:`note`,text:`No earlier data`}:{kind:`delta`,amount:U(Math.abs(t),et.percent),direction:t>0?`up`:t<0?`down`:`flat`,tone:r===ur.better?`better`:r===ur.worse?`worse`:`neutral`,basis:n}}function gd({overview:e,refreshing:t=!1}){let[n,r]=(0,Z.useState)(pd),[i,a]=(0,Z.useState)(0),o=mr(e.window)?Sn[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,md(r),r}),u=n.map((t,n)=>({key:t,slot:`slot-${n}`,label:gn[t].label,value:nn(t,e.totals[t],{compact:!0}),exactValue:nn(t,e.totals[t]),change:hd(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:Wn.map(e=>({value:e,label:gn[e].label})),onChange:e=>{fd(e)&&l(n,e)}},formatValue:e=>nn(t,e,{compact:!0}),formatExact:e=>nn(t,e),allowDecimals:gn[t].unit!==xr.count})),d=n[i]??ud[0],f=e.current.startDate&&e.current.endDate&&e.previous.startDate&&e.previous.endDate?`${_d(e.current.startDate,e.current.endDate,!0)} vs ${_d(e.previous.startDate,e.previous.endDate,!1)}`:void 0;return(0,Q.jsx)(Ku,{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 ${gn[d].label.toLowerCase()} yet.`,refreshing:t})}function _d(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 vd(e){return e?Jr(e.slice(0,10)):`—`}function yd({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 bd({rows:e,expanded:t,loading:n,onToggle:i,actions:a,lastReadLabel:o,empty:s}){let c=a?6:5,l=(e,o)=>{let s=t.has(e.url),c=n?.has(e.url)??!1;return(0,Q.jsxs)(`tr`,{className:`group`,children:[(0,Q.jsx)(`td`,{className:`max-w-md ${o?`pl-9`:``}`,children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[e.isIndex&&!o&&(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-label":`${s?`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:()=>i(e.url),children:s?(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,Q.jsx)(Zl,{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:c?`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?vd(e.submittedAt):o?(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?vd(e.lastReadAt):`Not yet`}),a&&(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:a(e,o)})})]},`${o?.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:o}),a&&(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:c,className:`py-6 text-center text-secondary`,children:s})}),e.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[l(e,null),e.isIndex&&t.has(e.url)&&(e.files??[]).map(t=>l(t,e))]},e.url))]})]})})}var xd=10,Sd={ok:`positive`,pending:`neutral`,warnings:`caution`,errors:`negative`,other:`neutral`},Cd={site:`on your site`,google:`in Google`,bing:`in Bing`};function wd(e){return e.map(e=>Cd[e]).join(` and `)}function Td(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 Ed(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:Sd[t.state],detail:Td(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:wd(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=Ql({rows:[...g,..._],getSearchText:e=>`${e.url} ${e.files?.map(e=>e.url).join(` `)??``}`,pageSize:xd});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)(ws,{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 `,qr(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)($l,{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)(bd,{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)(yd,{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)(yd,{disabled:!e.canSubmit||e.submitting,onClick:()=>void y([n.url]),children:n.submittedAt?`Resubmit`:`Submit`}),e.onInspect&&(0,Q.jsx)(yd,{disabled:e.inspecting,onClick:()=>e.onInspect(n.url),children:`Inspect URLs`}),e.onSetDefault&&!n.isDefault&&(0,Q.jsx)(yd,{disabled:e.settingDefault,title:`Canonry uses this sitemap when a command names none.`,onClick:()=>e.onSetDefault(n.url),children:`Set as default`})]})}),v.totalRows>xd&&(0,Q.jsx)(eu,{page:v.page,pageSize:xd,visibleRows:v.rows.length,totalRows:v.totalRows,onPageChange:v.setPage,itemLabel:`sitemaps`})]})]})}function Dd({label:e,items:t,disabled:n=!1,menuLabel:i,triggerRef:a}){let[o,s]=(0,Z.useState)(!1),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=a??l,d=(0,Z.useId)();return(0,Z.useEffect)(()=>{if(!o)return;c.current?.querySelector(`[role="menuitem"]:not([disabled])`)?.focus();let e=e=>{c.current&&!c.current.contains(e.target)&&s(!1)},t=e=>{e.key===`Escape`&&(s(!1),u.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[o,u]),(0,Q.jsxs)(`div`,{className:`relative inline-flex`,ref:c,children:[(0,Q.jsxs)(q,{ref:u,type:`button`,variant:`outline`,size:`sm`,disabled:n,"aria-haspopup":`menu`,"aria-expanded":o,"aria-controls":o?d:void 0,onClick:()=>s(e=>!e),children:[e,(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),o&&(0,Q.jsx)(`div`,{id:d,role:`menu`,"aria-label":i,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=>{c.current?.contains(e.relatedTarget)||s(!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:()=>{s(!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 Od(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 kd=`Unexpected OAuth redirect URL. Please try again.`;async function Ad(e,t,n){let{authUrl:r,redirectUri:i}=await Xt(e,t);if(!r.startsWith(`https://accounts.google.com/`))throw Error(kd);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 jd=`Search Console is not connected yet. Your Canonry team can set this up.`,Md=[`7d`,`30d`,`90d`,`all`],Nd=500,Pd=[{key:`clicks`,label:`Clicks`,color:Rr[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:Rr[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Zr.caution,format:e=>U(e)},{key:`position`,label:`Avg position`,color:Rr[2],inverted:!0,format:e=>e.toFixed(1)}],Fd=25;function Id(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`?`${dn(Math.abs(o)).magnitude} pts`:$n(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:U(Math.abs(s)),direction:s>0?`up`:`down`,tone:a(s>0),basis:i}}var Ld=[{key:`google-indexed`,engine:`google`,color:Rr[0]},{key:`bing-indexed`,engine:`bing`,color:Rr[6]}];function Rd(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 zd(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 Bd({projectName:e,refreshNonce:t}){let n=L(),{isAdmin:r}=oi(),i=ot(),[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=H({...Co({client:Y,path:{name:e},query:j?{surface:`index-coverage`,...j}:{surface:`index-coverage`,window:k}}),staleTime:ui,placeholderData:re}),[P,ee]=(0,Z.useState)([`clicks`,`impressions`]),[te,ne]=(0,Z.useState)(!0),[F,I]=(0,Z.useState)(null),[ie,ae]=(0,Z.useState)(0),[R,z]=(0,Z.useState)({startDate:``,endDate:``,query:``,page:``}),[B,oe]=(0,Z.useState)(0),[se,ce]=(0,Z.useState)(!1),[le,ue]=(0,Z.useState)(0),[de,fe]=(0,Z.useState)(!1),[pe,me]=(0,Z.useState)(``),[he,ge]=(0,Z.useState)(!0),[_e,ve]=(0,Z.useState)(!1),[ye,be]=(0,Z.useState)(!1),[xe,Ce]=(0,Z.useState)(!1),[Te,Ee]=(0,Z.useState)(!1),[De,Oe]=(0,Z.useState)(!1),[ke,Ae]=(0,Z.useState)(!1),[W,je]=(0,Z.useState)(null),[Me,Ne]=(0,Z.useState)(!1),[Pe,Fe]=(0,Z.useState)(null),[Ie,Le]=(0,Z.useState)(!1),[Re,ze]=(0,Z.useState)(!1),[Be,Ve]=(0,Z.useState)(!1),[He,We]=(0,Z.useState)(!1),[Ge,Ke]=(0,Z.useState)(`indexed`),qe=(0,Z.useId)(),[G,Je]=(0,Z.useState)(null),Ye=!!(R.query.trim()||R.page.trim()||G),Xe=G!==null,Ze=(0,Z.useMemo)(()=>{if(!G)return d;let{key:e,dir:t}=G;return[...d].sort((n,r)=>{let i=e===zr.CTR?Number.isFinite(n.ctr)?n.ctr:0:n[e],a=e===zr.CTR?Number.isFinite(r.ctr)?r.ctr:0:r[e];return t===`asc`?i-a:a-i})},[d,G]),Qe=Ql({rows:Ze,pageSize:25}),et=de?Qe.rows:Ze,[tt,nt]=(0,Z.useState)([]),[rt,it]=(0,Z.useState)(null),[at,st]=(0,Z.useState)(1),ct=(0,Z.useMemo)(()=>{if(tt.length<2)return null;let e=tt[tt.length-1],t=tt[tt.length-2];return{indexed:e.indexed-t.indexed,notIndexed:e.notIndexed-t.notIndexed}},[tt]);(0,Z.useEffect)(()=>{st(1)},[W,Ge,rt]);let lt=(0,Z.useMemo)(()=>rt?(W?.reasonGroups??[]).find(e=>e.reason===rt):void 0,[W,rt]),ut=(0,Z.useMemo)(()=>W?Ge===`indexed`?W.indexed:Ge===`deindexed`?W.deindexed:Ge===`notIndexed`?rt?lt?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,Ge,rt,lt]),dt=Math.max(1,Math.ceil(ut.length/Fd)),ft=Math.min(Math.max(1,at),dt),pt=(ft-1)*Fd,mt=(0,Z.useMemo)(()=>W?.indexed.slice(pt,pt+Fd)??[],[W,pt]),ht=(0,Z.useMemo)(()=>W?.notIndexed.slice(pt,pt+Fd)??[],[W,pt]),gt=(0,Z.useMemo)(()=>W?.deindexed.slice(pt,pt+Fd)??[],[W,pt]),_t=(0,Z.useMemo)(()=>(lt?.urls??[]).slice(pt,pt+Fd),[lt,pt]),[yt,bt]=(0,Z.useState)(!1),[xt,St]=(0,Z.useState)(null),[wt,Tt]=(0,Z.useState)(null),[Et,Dt]=(0,Z.useState)(null),[Ot,kt]=(0,Z.useState)(null);function At(e,t){let n=Cs(e),r=Od(n);r?(Tt(r),St(null)):(Tt(null),St(n.message||t))}let jt=s.find(e=>e.connectionType===`gsc`),Mt=(jt?.scopes??[]).includes(`https://www.googleapis.com/auth/webmasters`),Nt=H({...bo({client:Y,path:{name:e}}),staleTime:ui,enabled:!!jt?.propertyId&&!i}),Pt=Nt.data?.google?.sitemaps??[],Ft=Pt.filter(e=>e.parentUrl===null),It=Ft.filter(e=>e.isIndex).map(e=>e.url),Lt=It.length>0?It:Ft.map(e=>e.url),Rt=It.length,zt=Rt===1?`Resubmit sitemap index`:Rt>1?`Resubmit sitemap indexes`:`Resubmit all sitemaps`,Bt=d.length>0||h.length>0||_.length>0,Vt=Ac(),Ht=vc();async function Ut(t,r=!1){if(i)u([]);else if(!t)u([]),S(``);else{be(!0);try{let{sites:i}=await n.fetchQuery({...so({client:Y,path:{name:e}}),staleTime:r?0:ui});u(i),S(t.propertyId??i[0]?.siteUrl??``),Tt(null)}catch(e){u([]),At(e,`Failed to load Search Console properties`)}finally{be(!1)}}}async function Wt(t){Ee(!0);let r=t??B;try{let t=Ye?Nd:25,i=Ye?0:r,a={limit:String(t)};R.startDate&&(a.startDate=R.startDate),R.endDate&&(a.endDate=R.endDate),R.query&&(a.query=R.query),R.page&&(a.page=R.page),i>0&&(a.offset=String(i)),k&&k!==`all`&&!R.startDate&&(a.window=k);let o=await n.fetchQuery({...za({client:Y,path:{name:e},query:a}),staleTime:ui}),s=o.rows;Ye?(ce(!1),f(s),ue(s.length),fe(!0)):(ce(i+s.length<o.totalMatching),f(s),ue(0),fe(!1))}catch(e){f([]),ce(!1),ue(0),St(e instanceof Error?e.message:`Failed to load GSC performance data`)}finally{Ee(!1)}}async function Gt(){try{let t={};R.startDate&&(t.startDate=R.startDate),R.endDate&&(t.endDate=R.endDate),k&&k!==`all`&&!R.startDate&&(t.window=k);let r=await n.fetchQuery({...Pa({client:Y,path:{name:e},query:t}),staleTime:ui});m(r),M(t.startDate||t.endDate?{...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{}}:null)}catch{m(null)}}async function Kt(t=!1){Oe(!0);try{let r=pe.trim()||void 0,i={limit:`20`};r&&(i.url=r);let[a,o]=await Promise.all([n.fetchQuery({...xo({client:Y,path:{name:e},query:i}),staleTime:t?0:ui}),n.fetchQuery({...Za({client:Y,path:{name:e}}),staleTime:t?0:ui})]);g(a),v(o)}catch(e){g([]),v([]),St(e instanceof Error?e.message:`Failed to load GSC inspection history`)}finally{Oe(!1)}}async function Jt(t=!1){Ne(!0);try{let[r,i]=await Promise.all([n.fetchQuery({...ja({client:Y,path:{name:e}}),staleTime:t?0:ui}),n.fetchQuery({...go({client:Y,path:{name:e}}),staleTime:t?0:ui}).catch(()=>[])]);je(r),nt(i)}catch(e){je(null),nt([]),St(e instanceof Error?e.message:`Failed to load coverage data`)}finally{Ne(!1)}}async function Yt(t){bt(!0),St(null);try{let{succeeded:n,failed:r,total:i}=(await $e(e,{urls:t})).summary;ci({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){St(e instanceof Error?e.message:`Failed to request indexing`)}finally{bt(!1)}}async function Xt(){bt(!0),St(null);try{let{succeeded:t,failed:n,total:r}=(await $e(e,{urls:[],allUnindexed:!0})).summary;ci({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){St(e instanceof Error?e.message:`Failed to request indexing`)}finally{bt(!1)}}async function Zt(t){let n=[];if(!Mt||t.length===0)return n;let r=[...new Set(t)];ze(!0),St(null),Fe({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 Nn(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,Fe({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}`,St(s),ci({title:`Sitemap resubmission partially completed`,detail:f,tone:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`}),n}}let t=r.length;ci({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){St(e instanceof Error?e.message:`Failed to submit sitemap to Google`)}finally{ze(!1),Fe(null),s&&St(s)}return n}async function Qt(){let e=Pt.filter(e=>!e.isIndex).map(e=>e.url),t=It.filter(e=>!Pt.some(t=>t.parentUrl===e));await Zt([...e,...t])}async function $t(t){Le(!0),St(null);try{await we(e,`gsc`,t),await li(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,sitemapUrl:t}:e)),ci({title:`Default sitemap updated`,detail:t,tone:`positive`,dedupeKey:`gsc:sitemap-default:${e}`,dedupeMode:`replace`})}catch(e){St(e instanceof Error?e.message:`Failed to set the default sitemap`)}finally{Le(!1)}}async function en(t){try{await Ht.mutateAsync({projectName:e,projectLabel:e,opts:t?{sitemapUrl:t}:void 0})}catch{}}async function tn(){try{let t=(await n.fetchQuery({...Ni({client:Y,path:{name:e},query:{kind:gr[`gsc-sync`],limit:1}}),staleTime:ui}))[0];kt(t?.status===vt.failed&&t.error?`Last saved Search Console sync failed: ${Ct(t.error)}`:null)}catch{kt(`Saved Search Console sync status is unavailable.`)}}async function nn(){ge(!0),St(null);try{let[t,a]=await Promise.all([i||!r?Promise.resolve(null):jn().catch(()=>null),n.fetchQuery({...io({client:Y,path:{name:e}}),staleTime:ui}).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?Ut(s):Promise.resolve(),!i&&s?tn():Promise.resolve(),Wt(),Gt(),Kt(),Jt()])}finally{ge(!1)}}(0,Z.useEffect)(()=>{u([]),Ve(!1),kt(null),Tt(null),Dt(null)},[e]);let rn=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{nn(),rn.current!==t&&(rn.current=t,N.refetch())},[e,t,r]),(0,Z.useEffect)(()=>{oe(0),I(null),z(e=>e.startDate||e.endDate?{...e,startDate:``,endDate:``}:e),ae(e=>e+1),Gt()},[k]);let an=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{an.current?(oe(0),Qe.setPage(1),Wt(0)):an.current=!0},[ie]);function on(e){let t=F===e?null:e;I(t),z(e=>({...e,startDate:t??``,endDate:t??``})),ae(e=>e+1)}let sn=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{sn.current?(oe(0),Wt(0)):sn.current=!0},[Xe]);async function cn(){if(!a)St(`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`);else{ve(!0),St(null),Dt(null);try{await Ad(e,`gsc`,e=>{(async()=>{Dt(e?`Google connected. Refreshing access…`:`Refreshing Google connection…`);try{await li(n,`google`),await nn()}finally{Dt(null)}})()})===`popup`&&Dt(`Finish the Google consent flow in the popup. This page will refresh automatically.`)}catch(e){St(e instanceof Error?e.message:`Failed to start OAuth flow`)}finally{ve(!1)}}}async function ln(){St(null),Dt(null);try{await dr(e,`gsc`),await li(n,`google`),c(e=>e.filter(e=>e.connectionType!==`gsc`)),u([]),S(``)}catch(e){St(e instanceof Error?e.message:`Failed to disconnect`)}}async function un(){if(x){Ce(!0),St(null);try{await qt(e,`gsc`,x),await li(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,propertyId:x}:e)),ci({title:`GSC property updated`,detail:`${e} is now linked to ${x}.`,tone:`positive`,dedupeKey:`gsc:property:${e}`,dedupeMode:`drop`})}catch(e){St(e instanceof Error?e.message:`Failed to save GSC property`)}finally{Ce(!1)}}}async function dn(){St(null),Dt(null);try{await Vt.mutateAsync({projectName:e,projectLabel:e,opts:{days:parseInt(T,10)||void 0,full:D||void 0}}),await li(n,`gsc`)}catch{}}async function fn(){if(C.trim()){Ae(!0),St(null),Dt(null);try{let t=await hr(e,C.trim());await li(n,`gsc`),b(t),w(``),await Kt()}catch(e){St(e instanceof Error?e.message:`Failed to inspect URL`)}finally{Ae(!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`})})}),Ot&&(0,Q.jsx)(`p`,{role:`status`,className:`mb-3 text-copy-14 text-caution`,children:Ot}),wt&&(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:wt.title}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-caution-200/90`,children:wt.message}),(mc(wt.enableUrl)||mc(wt.indexingApiUrl))&&(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3`,children:[mc(wt.enableUrl)&&(0,Q.jsx)(`a`,{href:mc(wt.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(wt.indexingApiUrl)&&(0,Q.jsx)(`a`,{href:mc(wt.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:()=>Tt(null),children:`×`})]})}),xt&&(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:[xt,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>St(null),children:`×`})]}),Et&&(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:[Et,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-positive-400 hover:text-positive-200`,onClick:()=>Dt(null),children:`×`})]}),he?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading…`}):(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[jt?(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:jt.domain}),(0,Q.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Coverage measured`,` `,W?.lastInspectedAt?qr(W.lastInspectedAt):`never`]}),!i&&(0,Q.jsx)(`button`,{type:`button`,className:`ml-auto text-muted transition-colors hover:text-negative-400`,onClick:si(ln),children:`Disconnect`})]}):r?(0,Q.jsxs)(ws,{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:_e,onClick:si(cn),children:_e?`Opening…`:`Connect Google Search Console`}):(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,asChild:!0,children:(0,Q.jsx)(V,{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)(ws,{className:`surface-card`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jd})}),(jt||Bt)&&(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(ws,{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:`${Rd(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 ${Nd.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)(wu,{windows:Md,value:k,onChange:e=>{A(e),oe(0),Qe.setPage(1)},label:`Search Console time period`,formatOption:e=>e===`all`?`All`:e}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Te,onClick:()=>{oe(0),Qe.setPage(1),Wt(0),Gt()},children:Te?`Loading…`:`Apply filters`})]})]}),p&&p.daily.length>0&&(()=>{let{totals:e,daily:t,trends:n,periodComparison:r}=p,i=t=>e[t]??null,a=Ld.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=Ue(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=[...Pd.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:te?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:Pd.map(e=>{let t=i(e.key);return{key:e.key,label:e.label,color:e.color,value:t===null?`—`:e.format(t),change:Id(r,e.key,e.inverted),interactive:!0,disabled:t===null}})},h=a.length===0?null:{key:`indexed`,label:`Indexed pages`,basis:zu(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:Ru(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)(Ku,{name:`Search performance figures`,frame:`none`,mode:`compare`,groups:h?[m,h]:[m],selected:P,onSelect:e=>ee(t=>t.includes(e)?t.length===1?t:t.filter(t=>t!==e):[...t,e]),chart:(0,Q.jsx)(Br,{data:d,xKey:`date`,series:f,xTickFormatter:Vr,labelFormatter:Jr,onSelectX:on,selectedX:F}),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:te,onChange:e=>ne(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":F===e.date,onClick:()=>on(e.date),children:[Jr(e.date),`: `,e.clicks,` clicks, `,e.impressions,` impressions`]},e.date))}),F&&(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 `,Jr(F)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`text-link hover:underline`,onClick:()=>on(F),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:R.startDate,onChange:e=>z(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:R.endDate,onChange:e=>z(t=>({...t,endDate:e.target.value}))}),(0,Q.jsx)($l,{value:R.query,onChange:e=>z(t=>({...t,query:e})),label:`Filter search queries`,placeholder:`Contains query…`}),(0,Q.jsx)($l,{value:R.page,onChange:e=>z(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(zr).map(e=>(0,Q.jsx)(`th`,{className:`text-right`,"aria-sort":G?.key===e?G.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:()=>{Qe.setPage(1),Je(t=>t?.key===e?t.dir===`desc`?{key:e,dir:`asc`}:null:{key:e,dir:`desc`})},children:[ii[e],G?.key===e?G.dir===`desc`?` ↓`:` ↑`:``]})},e))]})}),(0,Q.jsx)(`tbody`,{children:et.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)(Zl,{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:U(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)(eu,{page:de?Qe.page:Math.floor(B/25)+1,pageSize:25,visibleRows:et.length,totalRows:de?le:void 0,hasNextPage:de?void 0:se,disabled:Te,itemLabel:de?`matches`:`rows`,onPageChange:e=>{if(de){Qe.setPage(e);return}let t=(e-1)*25;oe(t),Wt(t)}}),de&&le>=Nd?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Results are capped at `,Nd.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)(ws,{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:[W&&W.notIndexed.length>0&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:yt,onClick:()=>void Xt(),children:yt?`Requesting…`:`Request indexing (${W.notIndexed.length})`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Me,onClick:()=>void Jt(!0),children:Me?`Loading…`:`Reload saved coverage`})]})]}),W&&W.summary.total>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mt-6 flex flex-col items-center`,children:(()=>{let e=W.summary.indexedShare??0,t=W.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:Gr.trackSubtle,strokeWidth:`14`}),(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Zr.positiveDeep,strokeWidth:`14`,strokeDasharray:n,strokeDashoffset:r,strokeLinecap:`round`,transform:`rotate(-90 64 64)`,style:{transition:`stroke-dashoffset 0.6s ease`}}),W.summary.notIndexed>0&&(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Gr.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:U(W.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:W.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:W.summary.notIndexed.toLocaleString()}),(0,Q.jsxs)(`p`,{className:`text-label-12 normal-case text-muted`,children:[`Not indexed`,(W.reasonGroups??[]).length>0&&(0,Q.jsxs)(`span`,{className:`ml-1 text-faint`,children:[`· `,(W.reasonGroups??[]).length,` `,(W.reasonGroups??[]).length===1?`reason`:`reasons`]})]})]})]}),W.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:W.summary.deindexed.toLocaleString()}),(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Deindexed`})]})]})]})]})]})})()}),(0,Q.jsx)(_l,{id:qe,label:`Coverage status`,value:Ge,onChange:e=>{Ke(e),it(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 (${W.indexed.length})`],[`notIndexed`,`Not Indexed (${W.notIndexed.length})`],[`deindexed`,`Deindexed (${W.deindexed.length})`]]}),(0,Q.jsxs)(`div`,{id:`${qe}-panel`,role:`tabpanel`,"aria-labelledby":`${qe}-${Ge}`,tabIndex:0,className:`mt-3 overflow-x-auto`,children:[Ge===`indexed`&&W.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:mt.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))})]}),Ge===`notIndexed`&&!rt&&(W.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:(W.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:()=>it(e.reason),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),it(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))})]}),Ge===`notIndexed`&&!rt&&(W.reasonGroups??[]).length===0&&W.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: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.indexingState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`})]},e.id))})]}),Ge===`notIndexed`&&rt&&(()=>{let e=(W.reasonGroups??[]).find(e=>e.reason===rt);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:()=>it(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:yt,onClick:()=>void Yt(e.urls.map(e=>e.url)),children:yt?`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:_t.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:yt,onClick:()=>void Yt([e.url]),title:`Request indexing`,children:`Index`})})]},e.id))})]})]}):null})(),Ge===`deindexed`&&W.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:gt.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}`))})]}),(Ge===`indexed`&&W.indexed.length===0||Ge===`notIndexed`&&!rt&&W.notIndexed.length===0||Ge===`deindexed`&&W.deindexed.length===0)&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No URLs in this category.`}),(0,Q.jsx)(eu,{page:ft,pageSize:Fd,visibleRows:Math.min(Fd,ut.length-pt),totalRows:ut.length,onPageChange:st,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":He,onClick:()=>We(e=>!e),children:[(0,Q.jsx)(`span`,{children:`Coverage history`}),(0,Q.jsx)(`span`,{children:He?`Hide snapshots`:tt.length>0?`View ${tt.length} snapshots`:`View history`})]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Current: `,W.summary.indexed.toLocaleString(),` indexed, `,W.summary.notIndexed.toLocaleString(),` not indexed.`,ct&&(0,Q.jsxs)(Q.Fragment,{children:[` Since the last snapshot: `,ct.indexed>=0?`+`:``,ct.indexed.toLocaleString(),` indexed, `,ct.notIndexed>=0?`+`:``,ct.notIndexed.toLocaleString(),` not indexed.`]})]}),He&&(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:tt.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:tt.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:Me?`Loading coverage data…`:`No coverage data yet. Inspect your sitemap to populate this view.`})]}),!i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ed,{engine:`Google`,data:Nt.isError?null:Nt.isPending&&Nt.fetchStatus!==`idle`?void 0:Nt.data?.google??null,loadError:Nt.isError?Se(Nt.error):null,label:e=>zd(e,jt?.propertyId),canSubmit:Mt,submitBlocked:jt?(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:si(cn),children:`Reconnect`})]}):void 0,onSubmit:Zt,submitting:Re,defaultUrl:jt?.sitemapUrl??null,onSetDefault:e=>void $t(e),settingDefault:Ie,onInspect:e=>void en(e),inspecting:Ht.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:Ft.length>0?(0,Q.jsx)(Dd,{label:Pe?`Submitting ${Pe.completed} of ${Pe.total}`:`Resubmit all`,menuLabel:`Resubmit sitemaps to Google`,disabled:!Mt||Re,items:[{key:`primary`,label:zt,description:Rt>0?`Google rereads every sitemap the index lists.`:`Each sitemap in the list, once.`,disabled:Lt.length===0,onSelect:()=>void Zt(Lt)},{key:`files`,label:`Resubmit all files`,description:`Every file inside each index, one by one.`,onSelect:()=>void Qt()}]}):void 0}),(0,Q.jsxs)(ws,{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 fn()}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:ke||!jt?.propertyId||!C.trim(),onClick:si(fn),children:ke?`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:Tr(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:qr(y.crawlTime)})]})]})]})]}),(0,Q.jsxs)(ws,{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:De,onClick:()=>void Kt(!0),children:De?`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:pe,onChange:e=>me(e.target.value)})]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`self-end`,disabled:De,onClick:()=>void Kt(!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:Tr(e.isMobileFriendly??null)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:qr(e.inspectedAt)})]},e.id))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No inspection history yet.`})]}),(0,Q.jsxs)(ws,{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:qr(e.transitionDate)})]},`${e.url}:${e.transitionDate}`))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No deindexed transitions recorded.`})]})]}),jt&&!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:()=>{Be||Ut(jt),Ve(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 ${Be?`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`})]})}),Be&&(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)(ws,{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:ye||l.length===0,onChange:e=>S(e.target.value),children:l.length===0?(0,Q.jsx)(`option`,{value:``,children:ye?`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:ye,onClick:()=>void Ut(jt,!0),children:ye?`Refreshing…`:`Refresh properties`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:!x||xe,onClick:si(un),children:xe?`Saving…`:`Save property`})]})]})]}),(0,Q.jsxs)(ws,{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:Vt.isPending||!jt.propertyId,onClick:si(dn),children:Vt.isPending?`Queueing…`:`Queue sync`}),!jt.propertyId&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-caution-400`,children:`Select a Search Console property before queueing a sync.`})]})]})]})})]})]})]})}var Vd=[`7d`,`30d`,`90d`,`all`],Hd=10,Ud=[{key:`clicks`,label:`Clicks`,color:Rr[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:Rr[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Zr.caution,format:e=>U(e)},{key:`position`,label:`Avg position`,color:Rr[2],inverted:!0,format:e=>e.toFixed(1)}],Wd=`bing-indexed`,Gd=`Impression-weighted across the queries Bing names. Bing reports these per week, so the line moves weekly.`,Kd=`Asks Bing directly. Counts against the shared Bing request limit for this key.`;function qd(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:$n(t),direction:t>0?`up`:`down`,tone:t>0?`worse`:`better`,basis:n}}function Jd(e){return e==null?`—`:e.toFixed(1)}function Yd(e){return e==null?`—`:Math.round(e).toLocaleString()}function Xd(e){return e.replace(/^https?:\/\//,``).replace(/\/+$/,``)}function Zd(e,t){let n=t.replace(/\/+$/,``);return e.startsWith(n)?e.slice(n.length)||`/`:e}function Qd(e,t){return e?.find(e=>e.kind===t)}function $d(e){let t=e?.payload;return t&&typeof t.dailyQuota==`number`&&typeof t.monthlyQuota==`number`?{dailyQuota:t.dailyQuota,monthlyQuota:t.monthlyQuota}:null}function ef(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 tf(e){return Array.isArray(e?.payload)?e.payload.filter(e=>typeof e==`object`&&!!e):null}var nf=new Set([`entityType`,`requestType`,`type`,`role`]);function rf(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)?Jr(e.slice(0,10)):nf.has(t)&&/^[a-z]+(?:-[a-z]+)*$/.test(e)?e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`-`,` `):e:JSON.stringify(e)}function af({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 of({projectName:e,refreshNonce:t}){let n=L(),{canWrite:r,isAdmin:i}=oi(),a=r&&!K()&&!ot(),[o,s]=(0,Z.useState)(),c=!i&&a&&o?.project===e?o.sites:void 0,l=H({...Li({client:Y,path:{name:e}}),staleTime:ui}),u=l.data??null,d=H({...Oi({client:Y,path:{name:e}}),staleTime:ui,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 Un(e,f.trim()||void 0);if(!i){let n=Wt(t.domain),r=t.availableSites.filter(e=>e.verified&&n!==null&&Wt(e.url)===n);s({project:e,sites:r})}p(``),await li(n,`bing`)}catch(e){_(Ss(e))}}}async function y(){_(null);try{await Mn(e),s(void 0),h(``),await li(n,`bing`)}catch(e){_(Ss(e))}}async function b(){if(a&&m.trim()){_(null);try{await _n(e,m.trim()),await li(n,`bing`)}catch(e){_(Ss(e))}}}if(l.isPending)return(0,Q.jsx)(af,{children:(0,Q.jsx)(ws,{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)(af,{children:(0,Q.jsxs)(ws,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load the Bing connection: `,Ss(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)(af,{children:(0,Q.jsxs)(ws,{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)(ds,{size:`sm`,disabled:!i&&!f.trim(),onClick:si(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)(af,{children:(0,Q.jsxs)(ws,{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)(ds,{size:`sm`,variant:`ghost`,onClick:si(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?qr(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:si(async e=>{e.preventDefault(),await b()}),children:[(0,Q.jsx)(`input`,{type:`url`,required:!0,"aria-label":`Verified Bing site URL`,placeholder:Wt(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:Ss(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:si(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)(sf,{projectName:e,connection:u,siteUrl:u.siteUrl,onDisconnect:y,error:g})}function sf({projectName:e,connection:t,siteUrl:n,onDisconnect:i,error:a}){let[o,s]=(0,Z.useState)(`30d`),c=ot(),l={name:e},u=H({...Ki({client:Y,path:l,query:{window:o}}),staleTime:ui,placeholderData:re,enabled:!c}),d=H({...Xi({client:Y,path:l}),staleTime:ui,enabled:!c}),f=H({...ea({client:Y,path:l}),staleTime:ui,enabled:!c}),p=!c&&!!(u.data?.latestAvailableDate||d.data?.syncedAt||f.data?.syncedAt),m=!u.isPending&&!d.isPending&&!f.isPending,h=[u,d,f].find(e=>e.isError)?.error??null,g=tf(Qd(d.data?.snapshots,`blocked-urls`))?.length??0;return(0,Q.jsx)(af,{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:Xd(n)}),u.data?.latestAvailableDate&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Data through `,Jr(u.data.latestAvailableDate)]})]}),d.data?.syncedAt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Synced `,qr(d.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)(r,{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?qr(t.updatedAt):`—`})]}),!K()&&!c&&(0,Q.jsx)(ds,{size:`sm`,variant:`ghost`,onClick:si(i),children:`Disconnect`})]})]}),children:(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[a&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-negative`,children:a}),!c&&(m&&!p&&h?(0,Q.jsxs)(ws,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load Bing data: `,Ss(h)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{u.refetch(),d.refetch(),f.refetch()},children:`Retry`})]}):m&&!p?(0,Q.jsx)(uf,{projectName:e,loadedAt:d.dataUpdatedAt}):(0,Q.jsx)(df,{projectName:e,siteUrl:n,range:o,onRangeChange:s})),(0,Q.jsx)(gf,{projectName:e,siteUrl:n,snapshots:d.data?.snapshots}),p&&(0,Q.jsx)(_f,{projectName:e,siteUrl:n}),p&&(0,Q.jsx)(mf,{projectName:e}),p&&(0,Q.jsx)(yf,{siteUrl:n,snapshots:d.data?.snapshots??[]})]})})}var cf=5e3;function lf(e){return e?.status===vt.queued||e?.status===vt.running}function uf({projectName:e,loadedAt:t}){let n=L(),r=H({...Ni({client:Y,path:{name:e},query:{kind:gr[`bing-sync`],limit:1}}),refetchInterval:e=>lf(e.state.data?.[0])?cf:!1,enabled:!K()}),i=r.data?.[0],a=lf(i),[o,s]=(0,Z.useState)(!1),c=i&&!a&&i.finishedAt?Date.parse(i.finishedAt):0;(0,Z.useEffect)(()=>{c>t&&Ls(n,gr[`bing-sync`],e)},[c,t,n,e]);async function l(){s(!0);try{let t=await br(e);Ks({id:t.id,projectId:t.projectId,kind:gr[`bing-sync`],projectLabel:e,sourceAction:`bing-sync`}),await r.refetch(),ci({title:`Bing sync started`,detail:`Search data appears here when it finishes.`,tone:`neutral`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}catch(t){ci({title:`Bing sync could not start`,detail:Ss(t),tone:`negative`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}finally{s(!1)}}let u=!a&&i?.status===vt.failed;return(0,Q.jsxs)(ws,{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===vt.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?`: ${Ct(i.error)}`:`.`]}),!K()&&(0,Q.jsx)(ds,{className:`mt-3`,size:`sm`,disabled:a||o,onClick:si(l),children:a||o?`Sync running…`:u?`Try the sync again`:`Sync Bing data now`})]})}function df({projectName:e,siteUrl:t,range:n,onRangeChange:r}){let i={name:e},a=H({...Ki({client:Y,path:i,query:{window:n}}),staleTime:ui,placeholderData:re}),o=H({...Ka({client:Y,path:i,query:{window:n,groupBy:`week`}}),staleTime:ui,placeholderData:re}),s=H({...Co({client:Y,path:i,query:{surface:`index-coverage`,window:n}}),staleTime:ui,placeholderData:re}),[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: `,Ss(a.error)]});else{let r=o.data?.totals?.avgImpressionPosition??null,i=qd(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:Ud.map(e=>{if(e.key===`position`)return{key:e.key,label:e.label,help:Gd,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:Id(m,e.key,!1),interactive:!0,disabled:f.rows.length===0}})},_=p?{key:`indexed`,label:`Indexed pages`,basis:zu([p]),figures:[{key:Wd,label:`Bing`,color:Rr[6],value:p.value===null?`—`:p.value.toLocaleString(),change:Ru(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?Ue(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,[Wd]:T.get(e)??null}}):[],D=[...Ud.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(Wd)&&p?[{dataKey:Wd,label:`Bing indexed pages`,color:Rr[6],axisId:Wd,formatValue:e=>e.toLocaleString(),connectNulls:!0}]:[]];h=(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(Ku,{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)(Br,{data:E,xKey:`date`,series:D,xTickFormatter:Vr,labelFormatter:Jr,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)(ff,{projectName:e,siteUrl:t,range:n})]})}return(0,Q.jsxs)(ws,{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:`${Rd(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:[Jr(f.window.startDate),` to `,Jr(f.window.endDate)]})]}),(0,Q.jsx)(wu,{windows:Vd,value:n,onChange:r,label:`Bing time period`,formatOption:e=>e===`all`?`All`:e})]}),h]})}function ff({projectName:e,siteUrl:t,range:n}){let[i,a]=(0,Z.useState)(`queries`),o=(0,Z.useId)(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(void 0),[d,f]=(0,Z.useState)(1),[p,m]=(0,Z.useState)(null),g={name:e},_=(d-1)*Hd;(0,Z.useEffect)(()=>{let e=s.trim()||void 0;if(e===void 0){u(void 0);return}let t=setTimeout(()=>u(e),300);return()=>clearTimeout(t)},[s]);let v=H({...Ka({client:Y,path:g,query:{window:n,query:l,limit:Hd,offset:_}}),staleTime:ui,placeholderData:re,enabled:i===`queries`}),y=H({..._i({client:Y,path:g,query:{window:n,page:l,limit:Hd,offset:_}}),staleTime:ui,placeholderData:re,enabled:i===`pages`}),b=i===`queries`?v:y,x=i===`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=i===`queries`?`Query`:`Page`;return(0,Z.useEffect)(()=>{f(1),m(null)},[i,n,l]),(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)(_l,{id:o,label:`Bing search rows`,value:i,onChange:a,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)($l,{className:`mb-1.5 w-full sm:w-64`,value:s,onChange:c,label:i===`queries`?`Filter Bing queries`:`Filter Bing pages`,placeholder:i===`queries`?`Contains query…`:`Contains page URL…`})]}),(0,Q.jsxs)(`div`,{id:`${o}-panel`,role:`tabpanel`,"aria-labelledby":`${o}-${i}`,tabIndex:0,children:[b.isError?(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing `,i,`: `,Ss(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…`:l?`No ${i} match "${l}" in this window.`:`Bing named no ${i} in this window.`})}),x.map(a=>{let o=p===a.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":o,"aria-label":`${o?`Hide`:`Show`} details for ${a.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:()=>m(o?null:a.key),children:o?(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,Q.jsx)(`td`,{className:`max-w-md text-strong`,children:i===`pages`?(0,Q.jsx)(Zl,{value:Zd(a.key,t),title:a.key,className:`font-mono text-label-13`}):(0,Q.jsx)(`span`,{className:`block truncate`,title:a.key,children:a.key})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:a.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:a.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:U(a.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Jd(a.avgImpressionPosition)})]}),o&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:5,className:`pb-4`,children:(0,Q.jsx)(pf,{projectName:e,siteUrl:t,range:n,tab:i,rowKey:a.key})})]})]},a.key)})]})]})}),(0,Q.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Q.jsx)(eu,{page:d,pageSize:Hd,visibleRows:x.length,totalRows:S,disabled:b.isFetching,itemLabel:i,onPageChange:f})})]})]})}function pf({projectName:e,siteUrl:t,range:n,tab:r,rowKey:i}){let a={name:e},[o,s]=(0,Z.useState)(!1),c=H({...Ka({client:Y,path:a,query:{window:n,query:i,match:`exact`,groupBy:`week`}}),staleTime:ui,enabled:r===`queries`}),l=H({..._i({client:Y,path:a,query:{window:n,page:i,match:`exact`,groupBy:`week`}}),staleTime:ui,enabled:r===`pages`}),u=H({...Ji({client:Y,path:a,query:{query:i}}),staleTime:ui,retry:!1,enabled:o&&r===`queries`}),d=H({...Ya({client:Y,path:a,query:{page:i}}),staleTime:ui,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:Jr(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:Jd(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:Kd})]})),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:`${Ss(p.error)} Nothing was stored.`}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void p.refetch(),children:[(0,Q.jsx)(v,{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?Jr(e.date):`—`}),(0,Q.jsx)(`td`,{className:`max-w-xs`,children:r===`queries`?(0,Q.jsx)(Zl,{value:Zd(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:Jd(e.avgImpressionPosition)})]},`${e.date}:${e.key}:${n}`))})]}))]})]})}function mf({projectName:e}){let t=H({...$i({client:Y,path:{name:e}}),staleTime:ui}),[n,i]=(0,Z.useState)(null),a=t.data?.market,o=t.data?.rows??[];return(0,Q.jsxs)(ws,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`h3`,{children:`Search demand`}),a&&(0,Q.jsx)(X,{label:`${a.country.toUpperCase()} · ${a.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: `,Ss(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:[o.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.`})}),o.map(t=>{let a=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":a,"aria-label":`${a?`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:()=>i(a?null:t.query),children:a?(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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:Yd(t.avgWeeklyImpressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Yd(t.latestImpressions)})]}),a&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:3,className:`pb-4`,children:(0,Q.jsx)(hf,{projectName:e,query:t.query})})]})]},t.query)})]})]})})]})}function hf({projectName:e,query:t}){let n=H({...$i({client:Y,path:{name:e},query:{query:t}}),staleTime:ui}),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:Jr(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 gf({projectName:e,siteUrl:t,snapshots:n}){let r=L(),i=ot(),a={name:e},o=H({...ua({client:Y,path:a}),staleTime:ui}),s=H({...Ti({client:Y,path:a}),staleTime:ui}),c=H({...Di({client:Y,path:a,query:{days:`30`}}),staleTime:ui,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=$d(Qd(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 bn(e,t)).summary;ci({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 li(r,`bing`)}catch(t){let r=Ss(t);y(r),ci({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 Me(e,m.trim());_(t),await li(r,`bing`)}catch(e){y(Ss(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:U(x.percentage,et.percent)}]:[],A=Ql({rows:l===`not-indexed`?C:l===`unknown`?w:l===`indexed`?T:[],pageSize:Hd}),j=Ql({rows:E,pageSize:Hd}),M=Ql({rows:c.data?.rows??[],pageSize:Hd}),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)(ws,{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 ${Jr(S.date)}. Crawl by day has the codes.`})]}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:o.data?.lastInspectedAt?`Last inspected ${qr(o.data.lastInspectedAt)}`:`No inspection history yet`})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:k.length>0?(0,Q.jsx)(td,{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)(_l,{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)(ds,{size:`sm`,variant:`outline`,disabled:f,onClick:si(()=>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)(Zl,{value:Zd(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?qr(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)(ds,{size:`sm`,variant:`ghost`,disabled:f,onClick:si(()=>D({urls:[n.url]},n.url)),children:`Submit`})})})]},n.id))]})]})})(),(l===`not-indexed`||l===`unknown`||l===`indexed`)&&(0,Q.jsx)(eu,{page:A.page,pageSize:Hd,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)(ds,{size:`sm`,disabled:!m.trim(),onClick:si(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)(Zl,{value:Zd(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:qr(e.inspectedAt)})]},e.id))]})]}),(0,Q.jsx)(eu,{page:j.page,pageSize:Hd,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:Jr(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)(eu,{page:M.page,pageSize:Hd,visibleRows:M.rows.length,totalRows:M.totalRows,onPageChange:M.setPage,itemLabel:`days`})]})]})]})}function _f({projectName:e,siteUrl:t}){let{canWrite:n}=oi(),r=H({...bo({client:Y,path:{name:e}}),staleTime:ui}),[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 Jt(e,r),n.push(r);let r=n.length;ci({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){ci({title:n.length>0?`Bing took ${n.length} of ${t.length}`:`Bing did not take the sitemap`,detail:Ss(r),tone:`negative`,dedupeKey:`bing:submit-sitemap:${e}`,dedupeMode:`replace`})}finally{a(!1)}return n}async function l(t){s(!0);try{await St(e,{sitemapUrl:t}),ci({title:`Checking sitemap URLs in Bing`,detail:`Coverage updates when the check finishes.`,tone:`neutral`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}catch(t){ci({title:`Sitemap check could not start`,detail:Ss(t),tone:`negative`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}finally{s(!1)}}return(0,Q.jsx)(Ed,{engine:`Bing`,data:r.isError?null:r.isPending?void 0:r.data.bing,loadError:r.isError?Ss(r.error):null,label:e=>Zd(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 vf=`Bing shows this only to the site owner key. Not a failure.`;function yf({siteUrl:e,snapshots:t}){let n=$d(Qd(t,`url-submission-quota`)),r=$d(Qd(t,`content-submission-quota`)),i=ef(Qd(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:vf};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=Qd(t,n),s=tf(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)(bf,{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)(Zl,{value:Zd(r,e),title:r,className:`font-mono text-neutral`}):rf(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)(ws,{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)(bf,{label:`URL submissions left`,value:l(n),help:`URL submissions Bing will still accept, as of the last sync.`}),(0,Q.jsx)(bf,{label:`Content submissions left`,value:l(r)}),(0,Q.jsx)(bf,{label:`Crawl boost`,value:i?i.crawlBoostEnabled?`On`:i.crawlBoostAvailable?`Off`:`Not offered`:`—`}),i&&i.crawlRate.length===24&&(0,Q.jsx)(bf,{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 bf({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)(h,{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 xf=Rr[0],Sf=Rr[1],Cf=Rr[2],wf=Rr[3],Tf=Rr[4],Ef=[`both`,`server`,`ga4`],Df=[`days`,`months`],Of={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.`},kf=e=>new Date(`${e}-01T00:00:00.000Z`),Af=e=>kf(e).toLocaleDateString(void 0,{month:`short`,timeZone:`UTC`}),jf=e=>kf(String(e)).toLocaleDateString(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),Mf=e=>Number(e.slice(0,4))*12+Number(e.slice(5,7)),Nf={fontSize:12,paddingTop:6},Pf={top:4,right:8,left:0,bottom:0},Ff=44,If=.4,Lf=`ai-visits`,Rf=e=>typeof e==`number`?pt(Math.round(e)):String(e),zf=`Page fetches`,Bf={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 ${Jr(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:zf,olderPageFetchesSeries:`${zf} (older count)`,visitors:`AI visitors`,visitorsDetail:`arrived from an AI answer`,visitorsOlderDetail:`older days may read high`},Vf=`Visits, server`,Hf=`Visits, GA4`,Uf=`${Vf} (older count)`,Wf=`${Vf} (part month)`,Gf=`${Vf} (part month, older count)`,Kf=`Visits, GA4 (part month)`,qf=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function Jf(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 Yf(e,t){if(!e||t<e.startMonth||t>e.endMonth)return null;let n=Mf(e.endMonth)-Mf(e.startMonth);return n<=0?null:e.start+(e.end-e.start)*((Mf(t)-Mf(e.startMonth))/n)}function Xf(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 Zf(e){let t=e=>e.measured!==!1;if(e.length===0||t(e[0]))return null;let n=e.findIndex(t)-1;return n<0?{from:e[0].bucket,to:e[e.length-1].bucket}:{from:e[0].bucket,to:e[n].bucket}}function Qf(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 $f(e){let t=e===null?NaN:Date.parse(e);return Number.isFinite(t)?new Date(t-1).toISOString().slice(0,10):void 0}function ep(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 tp({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 np({source:e,rows:t,monthly:n,height:r,showXAxis:i,showTrend:a,unmeasured:o,older:s}){let c=e===`server`,l=c?Cf:wf,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?Vf:Hf,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)(tp,{color:l}),c?Vf:Hf]}),d&&(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(tp,{color:l,opacity:If}),`Older count, may read high`]})]}),(0,Q.jsx)(de,{width:`100%`,height:r,children:(0,Q.jsxs)(be,{data:t,syncId:Lf,margin:i?Pf:{...Pf,bottom:10},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`bucket`,hide:!i,tick:Xr,stroke:ti,tickFormatter:n?Af:Vr,minTickGap:n?8:28}),(0,Q.jsx)(ve,{tick:Xr,stroke:ti,width:Ff,allowDecimals:!1,tickFormatter:nt,tickCount:r<150?3:5}),(0,Q.jsx)(_e,{contentStyle:ei.contentStyle,labelStyle:ei.labelStyle,itemStyle:ei.itemStyle,labelFormatter:n?jf:Jr,formatter:Rf}),o&&o.from!==o.to&&(0,Q.jsx)(pe,{x1:o.from,x2:o.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)`}}),s&&(0,Q.jsx)(pe,{x1:s.from,x2:s.to,fill:`var(--color-overlay-hover)`,fillOpacity:.3,stroke:`none`}),s&&(0,Q.jsx)(xe,{x:s.to,stroke:Tf,strokeDasharray:`4 4`,strokeWidth:1.5}),c&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`aiReferralLandedHits`,name:Vf,stroke:l,strokeWidth:2,connectNulls:!1,dot:ep(u(`aiReferralLandedHits`),l)}),d&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`serverOlder`,name:Uf,stroke:l,strokeOpacity:If,strokeWidth:2,connectNulls:!1,dot:ep(u(`serverOlder`),l,!1,If)}),c&&n&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`serverPartial`,name:Wf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:ep(u(`serverPartial`),l,!0)}),d&&n&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`serverOlderPartial`,name:Gf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:ep(u(`serverOlderPartial`),l,!0,If)}),c&&a&&(0,Q.jsx)(ye,{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)(ye,{type:`monotone`,dataKey:`ga4Visits`,name:Hf,connectNulls:!1,stroke:l,strokeWidth:2,dot:ep(u(`ga4Visits`),l)}),!c&&n&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`ga4Partial`,name:Kf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:ep(u(`ga4Partial`),l,!0)}),!c&&a&&(0,Q.jsx)(ye,{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 rp({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=Qc(e,{range:d,granularity:`month`,limit:1},{enabled:u}),p=Qc(e,{sinceMinutes:t,granularity:`day`,limit:1}),m=el(e),h=H({...co({client:Y,path:{name:e}}),enabled:!!e,staleTime:fi}),g=h.data?.connected===!0,_=H({...fa({client:Y,path:{name:e},query:{window:t>=259200?`180d`:t>=129600?`90d`:t>=43200?`30d`:`7d`}}),enabled:!!e&&g,staleTime:fi}),v=H({...fa({client:Y,path:{name:e},query:{startDate:d.since.slice(0,10)}}),enabled:!!e&&g&&u,staleTime:fi}),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)(()=>Zf(y),[y]),C=p.data?.series?.coverageStart??null,w=p.data?.series?.aiReferralCountingChangedAt??null,T=(0,Z.useMemo)(()=>Qf(y,w?.slice(0,10)),[w,y]),E=p.data?.series?.aiUserFetchCountingChangedAt??null,D=(0,Z.useMemo)(()=>Qf(y,$f(E)),[E,y]),O=(e,t,n)=>{let r=n.payload?.bucket;return D&&t===zf&&r!==void 0&&r<=D.to?[Rf(e),Bf.olderPageFetchesSeries]:Rf(e)},k=p.data?.series?.trends,A=(0,Z.useMemo)(()=>{let e=Jf(k?.crawlerContentHits,y.length),t=Jf(k?.aiUserFetchHits,y.length),n=Jf(k?.aiReferralLandedHits,y.length);return y.map((r,i)=>({...r,crawlerContentHits:r.measured===!1?null:qf(r.crawlerContentHits),aiUserFetchHits:r.measured===!1?null:qf(r.aiUserFetchHits),aiReferralLandedHits:r.measured===!1?null:qf(r.aiReferralLandedHits),ga4Visits:b.get(r.bucket)??null,ga4Trend:Xf(x,r.bucket),crawlTrend:e[i],fetchTrend:t[i],visitTrend:n[i]}))},[y,b,x,k]),j=f.data?.series,M=v.data,N=(0,Z.useMemo)(()=>j?.points??[],[j]),P=(0,Z.useMemo)(()=>{let e=new Set(j?.partialBuckets??[]),t=new Map((M?.months??[]).map(e=>[e.month,e])),n=Jf(j?.trends?.aiReferralLandedHits,N.length),r=new Map(N.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?qf(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:Yf(M?.monthlyTrend,n),recorded:o!==null||(s?.sessions??null)!==null}}),a=i.findIndex(e=>e.recorded);return a>0?i.slice(a):i},[N,j,M]),ee=(0,Z.useMemo)(()=>{if(o===`ga4`)return null;if(!u)return S;let e=new Set(P.map(e=>e.bucket));return Zf(N.filter(t=>e.has(t.bucket)))},[o,u,N,P,S]),te=(0,Z.useMemo)(()=>u?Qf(N,j?.aiReferralCountingChangedAt?.slice(0,7)):T,[u,N,j,T]),ne=te!==null&&o!==`ga4`,F=(0,Z.useMemo)(()=>(u?P:A).map(e=>{let t=e.aiReferralLandedHits??null,n=`serverPartial`in e?e.serverPartial:null,r=te!==null&&e.bucket<=te.to;return{...e,aiReferralLandedHits:r?null:t,serverOlder:r?t:null,serverPartial:r?null:n,serverOlderPartial:r?n:null}}),[u,P,A,te]),I=[`server`,`ga4`].filter(e=>F.some(t=>e===`server`?t.aiReferralLandedHits!=null||t.serverOlder!=null||t.serverPartial!=null||t.serverOlderPartial!=null:t.ga4Visits!=null||t.ga4Partial!=null)),L=o===`both`?I.length>0?I:[`server`,`ga4`]:[o],re=(M?.months??[]).filter(e=>e.complete&&e.sessions!==null).at(-1)??null,ie=P.filter(e=>e.aiReferralLandedHits!==null).at(-1)??null,ae=o===`server`?ie?.bucket??null:o===`ga4`?re?.month??null:re?.month??ie?.bucket??null,R=ae?P.find(e=>e.bucket===ae)?.aiReferralLandedHits??null:null,z=M?.monthlyTrend??null,B=u&&o!==`ga4`,V=u&&o!==`server`,oe=V&&g,se=B&&f.isSuccess||oe&&v.isSuccess,le=(!B||f.isSuccess)&&(!V||h.isSuccess&&(!g||v.isSuccess)),ue=P.some(e=>B&&(e.aiReferralLandedHits!==null||e.serverPartial!==null)||oe&&(e.ga4Visits!==null||e.ga4Partial!==null)),he=P.find(e=>e.bucket===d.until.slice(0,7)),Se=oe?he?.ga4Partial??null:null,Ce=B?he?.serverPartial??null:null,we=Se!==null||Ce!==null,Te=p.data?.totals,Ee=Te&&{crawlers:qf(Te.crawlerContentHits),fetches:qf(Te.aiUserFetchHits),visits:qf(Te.aiReferralLandedHits)},De=(0,Z.useMemo)(()=>y.reduce((e,t)=>({crawlers:e.crawlers+qf(t.crawlerContentHits),fetches:e.fetches+qf(t.aiUserFetchHits),visits:e.visits+qf(t.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[y]),Oe=Ee??De,ke=Oe.crawlers>0||Oe.fetches>0||Oe.visits>0,Ae=null;if(p.isLoading)Ae=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading AI traffic history…`});else if(p.isError)Ae=(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(!ke){let e=m.data?.sources,t=e!==void 0&&e.length===0,n=!t&&C===null;Ae=(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.`:`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.`:`The window was measured and nothing was recorded. Try a longer range.`})]})}return(0,Q.jsxs)(`div`,{children:[Ae??(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mb-5`,children:(0,Q.jsx)(td,{label:`AI traffic totals`,items:[{label:`AI crawlers`,value:pt(Oe.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:Bf.pageFetches,value:pt(Oe.fetches),detail:D?Bf.pageFetchesOlderDetail:Bf.pageFetchesDetail,tooltip:Bf.pageFetchesTooltip(D?.to??null)},{label:Bf.visitors,value:pt(Oe.visits),detail:T?Bf.visitorsOlderDetail:Bf.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.`+(T?` Days through ${Jr(T.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&&(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:qf(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:qf(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:qf(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`}),Bf.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)(de,{width:`100%`,height:206,children:(0,Q.jsxs)(be,{data:A,margin:Pf,children:[(0,Q.jsx)(ce,{stroke:`var(--chart-grid, #2e2e2e)`,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`bucket`,tick:Xr,stroke:`var(--chart-axis, #2e2e2e)`,tickFormatter:Vr,minTickGap:28}),(0,Q.jsx)(ve,{tick:Xr,stroke:`var(--chart-axis, #2e2e2e)`,width:Ff,allowDecimals:!1,tickFormatter:nt}),(0,Q.jsx)(_e,{contentStyle:ei.contentStyle,labelStyle:ei.labelStyle,itemStyle:ei.itemStyle,labelFormatter:Jr,formatter:O}),S&&(0,Q.jsx)(pe,{x1:S.from,x2:S.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)`}}),n&&D&&(0,Q.jsx)(xe,{x:D.to,stroke:Tf,strokeDasharray:`4 4`,strokeWidth:1.5}),(0,Q.jsx)(me,{wrapperStyle:Nf,iconType:`plainline`,iconSize:14}),(0,Q.jsx)(ge,{type:`monotone`,dataKey:`crawlerContentHits`,name:`Pages crawled`,stroke:xf,fill:xf,fillOpacity:.22,strokeWidth:1.8}),n&&(0,Q.jsx)(ge,{type:`monotone`,dataKey:`aiUserFetchHits`,name:zf,stroke:Sf,fill:Sf,fillOpacity:.18,strokeWidth:1.6}),i&&(0,Q.jsx)(ye,{type:`linear`,dataKey:`crawlTrend`,legendType:`none`,name:`Pages crawled trend`,dot:!1,tooltipType:`none`,stroke:xf,strokeWidth:1.4,strokeDasharray:`5 4`,connectNulls:!0}),i&&n&&(0,Q.jsx)(ye,{type:`linear`,dataKey:`fetchTrend`,legendType:`none`,name:`Page fetches trend`,dot:!1,tooltipType:`none`,stroke:Sf,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)(wu,{windows:Df,value:c,onChange:l,label:`Visits by day or month`,formatOption:e=>e===`months`?`Months`:`Days`}),(0,Q.jsx)(wu,{windows:Ef,value:o,onChange:s,label:`Visit measurement source`,formatOption:e=>e===`ga4`?`GA4`:e===`both`?`Both`:`Server`})]})]}),B&&f.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:Of.serverLoading}),oe&&v.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:Of.gaLoading}),V&&h.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:Of.gaStatusLoading}),V&&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:Of.gaStatusError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":Of.retryGaStatus,disabled:h.isFetching,onClick:()=>{h.refetch()},children:`Retry`})]}),B&&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:Of.serverError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":Of.retryServer,disabled:f.isFetching,onClick:()=>{f.refetch()},children:`Retry`})]}),oe&&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:Of.gaError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":Of.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:Of.connectGa}),se&&le&&!ue&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Of.emptyMonths}),u&&ae&&(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:jf(ae)}),o!==`server`&&re?.month===ae&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:pt(re.sessions??0)}),`visits, GA4`]}),o!==`ga4`&&R!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:pt(R)}),`visits, server`]}),o!==`server`&&z?.changePct!=null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:[z.changePct>0?`▲`:z.changePct<0?`▼`:``,U(Math.abs(z.changePct),et.percent)]}),`trend since `,Af(z.startMonth)]}),o!==`server`&&re?.month===ae&&re.engines[0]&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:pt(re.engines[0].sessions)}),`from `,re.engines[0].label]})]}),we&&he&&(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:[jf(he.bucket),` so far`]}),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, GA4`]}),Ce!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong tabular-nums mr-1`,children:pt(Ce)}),`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?se&&ue:!Ae)&&(0,Q.jsx)(`div`,{className:`flex flex-col gap-3`,children:L.map((e,t)=>{let n=t===L.length-1;return(0,Q.jsx)(np,{source:e,rows:F,monthly:u,height:L.length===1?176:n?134:104,showXAxis:n,showTrend:i,unmeasured:e===`server`?ee:null,older:e===`server`&&ne?te:null},e)})})]})}function ip(e){return e.replace(/\+/g,` `)}var ap=Pn,op={"7d":10080,"30d":43200,"90d":129600,"180d":259200};function sp(e){return Yl(e.landingPage)}var cp=25,lp=10,up={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0,byEngine:{series:[],otherCount:0,days:[]}},dp={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 fp(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 pp(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function mp(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 hp({projectName:e}){let{data:t,isLoading:n,isError:r}=$c(e),i=t?.sources??[];return(0,Q.jsxs)(`section`,{"aria-labelledby":`server-activity-heading`,children:[(0,Q.jsx)(Zu,{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)(V,{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)(V,{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)(rd,{label:`Source`,align:`left`}),(0,Q.jsx)(rd,{label:`Status`,align:`left`}),(0,Q.jsx)(rd,{label:`Crawler hits`,align:`right`}),(0,Q.jsx)(rd,{label:`AI hits`,align:`right`}),(0,Q.jsx)(rd,{label:`AI sessions`,align:`right`}),(0,Q.jsx)(rd,{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:tl(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:il(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?fp(t.lastSyncedAt):`never`}),(0,Q.jsx)(`td`,{className:`py-2 pl-3 text-right`,children:!K()&&(0,Q.jsx)(V,{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 gp({projectName:e}){let[t,n]=(0,Z.useState)(`30d`);return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(hp,{projectName:e}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsx)(jp,{projectName:e,window:t,periodControl:(0,Q.jsx)(wu,{windows:ap,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)(Zu,{id:`ai-traffic-history-heading`,title:`AI traffic history`,tooltip:dp.aiHistoryTooltip}),(0,Q.jsx)(rp,{projectName:e,sinceMinutes:op[t]})]})]})})]})}var _p={session:`Session`,first_user:`First visit`,manual_utm:`UTM`},vp={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)`},yp=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Attribution`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}],bp=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}];function xp(e){return e.engine===null}function Sp({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:vp[e.sourceDimension]??``,children:_p[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:U(e.share)})]})}function Cp({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:ip(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:ip(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:U(e.share)})]})}var wp=[{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`}],Tp=`—`;function Ep({label:e}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,title:e,children:Tp}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})}function Dp({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:ip(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:ip(e.medium)}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:e.trafficClass===`paid`?dp.paidClassTitle:dp.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:U(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)(Ep,{label:dp.notMeasured}):e.conversions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.conversionsPerThousandSessionsDisplay})]})}function Op({performance:e}){let t=(0,Z.useMemo)(()=>[{key:`conversions`,label:`Conversions`,help:dp.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)(Ep,{label:dp.notMeasured}):e.conversions.toLocaleString()})},{key:`perThousand`,label:`Per 1,000 sessions`,help:dp.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:dp.tooFewSessions(e.minSessions),children:t.conversionsPerThousandSessionsDisplay})},{key:`rank`,label:`Rank`,help:dp.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:dp.tooFewSessions(e.minSessions),children:dp.notRanked}):(0,Q.jsx)(Ep,{label:dp.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)(sd,{groups:e.platforms,groupLabel:`Platform`,caption:`Social and creator platforms by sessions and conversions`,childColumns:wp,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(Dp,{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:[dp.siteLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:dp.siteScope})]}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:n.sessions===null?(0,Q.jsx)(Ep,{label:dp.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)(Ep,{label:dp.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:dp.rateReasons[r]})]})}function kp({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)(td,{label:`Social sessions`,items:[{label:`Social sessions`,value:e.sessions.toLocaleString(),detail:`${e.sharePctDisplay} of all sessions`},{label:`Platforms`,value:String(t.length),detail:Pp(i,`source`),tooltip:dp.platformsTooltip},{label:`Paid social`,value:e.paidSessions.toLocaleString(),detail:`${U(e.paidShare)} of social`,tooltip:dp.platformPaidTooltip},{label:`Top platform`,value:n?.label??`None`,detail:n?Pp(n.sessions,`session`):void 0},{label:`Best converting`,value:r?.label??(e.conversionRateAvailable?dp.noneRanked:dp.notMeasured),detail:r?`${r.conversionsPerThousandSessionsDisplay} per 1,000 sessions`:void 0,tooltip:dp.bestConvertingTooltip}]}),(0,Q.jsxs)(Qu,{children:[(0,Q.jsx)($u,{label:dp.socialChartLabel,meta:t.length>0?Pp(e.sessions,`session`):dp.noneInPeriod,children:t.length>0?(0,Q.jsx)(ld,{input:e.daily,label:dp.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noSocial})}),(0,Q.jsx)($u,{label:`Social platforms`,meta:t.length>0?`${Pp(t.length,`platform`)} · ${Pp(i,`source`)}`:dp.noneInPeriod,children:t.length>0?(0,Q.jsx)(Op,{performance:e}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noSocial})})]})]})}function Ap(e,t){let n=L(),[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)(up),[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({...co({client:Y,path:{name:e}}),staleTime:fi});if(r.current)return;if(i(a),!a.connected){o(null),v(up),b([]),S(null),c(!1);return}let s=t===`all`?void 0:t,[l,u,d,f]=await Promise.all([n.fetchQuery({...Bi({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:fi}),n.fetchQuery({...fa({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:fi}).catch(()=>up),n.fetchQuery({...Ui({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:fi}).catch(()=>[]),n.fetchQuery({...ga({client:Y,path:{name:e},query:{window:mr(t)?t:`30d`}}),staleTime:fi}).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 _r(e,mr(t)?Sn[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 li(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 Je(e),await li(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 li(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 jp({projectName:e,window:t,periodControl:n,between:r}){let i=Ap(e,t??`30d`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Mp,{ga:i,projectName:e,periodControl:n}),r,(0,Q.jsx)(Np,{ga:i,projectName:e})]})}function Mp({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()&&!ot(),d=i?mp(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)(gd,{overview:e.overview,refreshing:e.loading}):i?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(td,{label:`Site traffic`,items:[{label:`Total sessions`,value:pp(i.totalSessions),detail:i.totalSessions.toLocaleString()},{label:`Organic sessions`,value:pp(i.totalOrganicSessions),detail:`${i.organicSharePctDisplay} of total`},{label:`Total users`,value:i.totalUsers===null?`n/a`:pp(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()&&!ot()&&(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,disabled:a,onClick:si(s),children:[(0,Q.jsx)(v,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),`Sync from GA4`]})]}):K()||ot()?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Google Analytics 4 property connected.`}):(0,Q.jsx)(Hp,{projectName:t,onConnected:()=>{e.handleConnected()}}),(0,Q.jsxs)(`section`,{"aria-labelledby":`site-traffic-heading`,children:[(0,Q.jsx)(Zu,{id:`site-traffic-heading`,title:`Site traffic`,tooltip:e.overview?dp.siteTrafficTooltip:d?`${dp.siteTrafficFallbackTooltip} Data covers ${d}.`:dp.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:si(s),children:[(0,Q.jsx)(v,{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:si(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 Np({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=Ql({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=>Yl(e.landingPage),pageSize:lp}),u=Ql({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:sp,pageSize:cp}),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?mp(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)(Zu,{id:`traffic-by-channel-heading`,title:`Traffic by channel`,tooltip:dp.channelTooltip,meta:m}),(0,Q.jsx)(td,{label:`Sessions by channel`,items:[{label:`Organic search`,value:h.organic.sharePctDisplay,detail:`${h.organic.sessions.toLocaleString()} sessions`,tooltip:dp.organicTooltip},{label:`Social`,value:h.social.sharePctDisplay,detail:`${h.social.sessions.toLocaleString()} sessions`,tooltip:dp.socialTooltip},{label:`Direct`,value:h.direct.sharePctDisplay,detail:`${h.direct.sessions.toLocaleString()} sessions`,tooltip:dp.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:dp.aiTooltip},{label:`Other channels`,value:h.other.sharePctDisplay,detail:`${h.other.sessions.toLocaleString()} sessions`,tooltip:dp.otherTooltip}]}),(0,Q.jsxs)(Qu,{children:[(0,Q.jsx)($u,{label:dp.aiChartLabel,meta:r.days.length>0?Pp(r.totalSessions,`session`):dp.noneInPeriod,children:r.days.length>0?(0,Q.jsx)(ld,{input:r.byEngine,baseline:d,baselineLabel:`Total sessions`,label:dp.aiChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noAiReferrals})}),(0,Q.jsx)($u,{label:`Where AI visitors came from`,meta:_.length>0?`${Pp(_.filter(e=>e.engine!==null).length,`engine`)} · ${Pp(n.aiReferrals.length,`source`)}`:dp.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)(sd,{groups:_,groupLabel:`Engine`,caption:`AI referral sessions by engine`,childColumns:yp,childRowKey:e=>`${e.source}:${e.medium}:${e.sourceDimension}:${e.trafficClass}`,renderChildCells:e=>(0,Q.jsx)(Sp,{row:e}),pinLast:xp})}),(0,Q.jsx)(X,{text:dp.aiEnginesTooltip})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noAiReferrals})}),(0,Q.jsx)($u,{label:`Pages AI visitors landed on`,meta:x??dp.noneInPeriod,children:n.aiReferralLandingPages.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($l,{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)(nd,{label:`Landing page`,sortKey:`landingPage`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(nd,{label:`Source`,sortKey:`source`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(rd,{label:`Attribution`,align:`left`}),(0,Q.jsx)(nd,{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)(Wp,{row:e},`${e.landingPage}:${e.source}:${e.medium}:${e.sourceDimension}`))})]})}),(0,Q.jsx)(eu,{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:dp.noAiLandingPages})})]})]}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`social-heading`,children:[(0,Q.jsx)(Zu,{id:`social-heading`,title:`Social`,tooltip:b?dp.socialPlatformTooltip:dp.socialTooltip2,meta:m}),b?(0,Q.jsx)(kp,{performance:b}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(td,{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:dp.platformsTooltip},{label:`Paid social`,value:(n.paidSocialSessions??0).toLocaleString(),detail:`${U(n.paidSocialShare??0)} of social`,tooltip:dp.paidSocialTooltip},{label:`Top platform`,value:y?.label??`None`,detail:y?`${y.sessions.toLocaleString()} sessions`:void 0}]}),(0,Q.jsxs)(Qu,{children:[(0,Q.jsx)($u,{label:dp.socialChartLabel,meta:v.length>0?Pp(n.socialSessions,`session`):dp.noneInPeriod,children:v.length>0?(0,Q.jsx)(ld,{input:n.socialPlatformDaily,label:dp.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noSocial})}),(0,Q.jsx)($u,{label:`Social platforms`,meta:v.length>0?`${Pp(v.length,`platform`)} · ${Pp(n.socialReferrals.length,`source`)}`:dp.noneInPeriod,children:v.length>0?(0,Q.jsx)(sd,{groups:v,groupLabel:`Platform`,caption:`Social sessions by platform`,childColumns:bp,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(Cp,{row:e})}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.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)(Zu,{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)($l,{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)(nd,{label:`Landing page`,sortKey:`landingPage`,current:a.key,dir:a.dir,onSort:f,align:`left`}),(0,Q.jsx)(nd,{label:`Sessions`,sortKey:`sessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(nd,{label:`Organic`,sortKey:`organicSessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(rd,{label:`Organic share`,align:`right`})]})}),(0,Q.jsx)(`tbody`,{children:l.rows.map(e=>(0,Q.jsx)(Up,{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)(eu,{page:l.page,pageSize:l.pageSize,visibleRows:l.rows.length,totalRows:l.totalRows,onPageChange:l.setPage,itemLabel:l.hasQuery?`matches`:`pages`})]})]}),(0,Q.jsx)(Vp,{projectName:t}),(0,Q.jsx)(`p`,{className:`mt-6 text-copy-13 text-secondary`,children:n?.lastSyncedAt?`Last synced ${fp(n.lastSyncedAt)}`:`Never synced`})]})}function Pp(e,t){return`${e.toLocaleString()} ${e===1?t:`${t}s`}`}var Fp=25,Ip=`n/a`,Lp={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 Rp(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 zp(e){return e===null?Ip:e.toFixed(1)}function Bp(e){return e===null?Ip:U(e)}function Vp({projectName:e}){let[t,n]=(0,Z.useState)(`28d`),[r,i]=(0,Z.useState)(`clicks`),[a,o]=(0,Z.useState)(`desc`),s=H({...ji({client:Y,path:{name:e},query:{window:t,limit:vn}}),staleTime:fi}),c=s.data,l=Ql({rows:(0,Z.useMemo)(()=>[...c?.rows??[]].sort((e,t)=>{let n=Rp(e,r),i=Rp(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=>Yl(je(e.landingPage)),pageSize:Fp});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()&&!ot();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:Lp.heading}),(0,Q.jsx)(X,{text:Lp.tooltip})]}),c?.windowStart&&c.windowEnd&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[Qe(c.windowStart),` to `,Qe(c.windowEnd),c.timeZone?` (${c.timeZone})`:``]})]}),(0,Q.jsx)(wu,{windows:Yt,value:t,onChange:e=>{l.setPage(1),n(e)},label:Lp.windowLabel})]}),s.isPending?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary py-6 text-center`,children:Lp.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:Lp.loadError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>{s.refetch()},children:Lp.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:Lp.notLinkedBadge}),(0,Q.jsx)(X,{text:Lp.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:Lp.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:Lp.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:Lp.thresholdedBadge}),(0,Q.jsx)(X,{text:Lp.thresholded})]}),c.status!==`ready`&&d&&c.syncedAt&&(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[Lp.previousSnapshot,` `,fp(c.syncedAt),`.`]}),c.status===`unavailable`&&d&&(0,Q.jsx)(`p`,{className:`w-full text-copy-14 text-secondary`,children:Lp.unavailableAction})]}),d?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($l,{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)(nd,{label:`Landing page`,sortKey:`landingPage`,current:r,dir:a,onSort:u,align:`left`}),(0,Q.jsx)(nd,{label:`Clicks`,sortKey:`clicks`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{label:`Impressions`,sortKey:`impressions`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{label:`CTR`,sortKey:`ctr`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{label:`Avg. position`,sortKey:`position`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{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:[Lp.totalLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:Lp.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:Bp(d.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:zp(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:je(e.landingPage),children:je(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:Bp(e.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:zp(e.organicGoogleSearchAveragePosition)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.activeUsers.toLocaleString()})]},e.landingPage))]})]})}),!xt(d)&&!f&&(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary mt-3 space-y-1`,children:[(0,Q.jsx)(`p`,{children:Lp.noSearchTraffic}),(0,Q.jsx)(`p`,{children:c.searchConsoleLink?.state===`no-search-data`?Lp.noSearchTrafficConfirmed:Lp.noSearchTrafficAction})]}),l.totalRows===0&&l.hasQuery&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-3`,children:c.totalRows>c.rows.length?Lp.noFilterMatchInLoaded(c.rows.length):Lp.noFilterMatch}),(0,Q.jsx)(eu,{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 `,fp(c.syncedAt)]})]}):(0,Q.jsx)(ws,{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:Lp.unavailable}),(0,Q.jsx)(`p`,{children:Lp.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:Lp.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:Lp.neverSynced}),p&&(0,Q.jsx)(`p`,{children:Lp.neverSyncedAction})]})})]})]})]})}function Hp({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 fr(e,{propertyId:n.trim(),keyJson:o});try{await _r(e)}catch{}t()}catch(e){d(e instanceof Error?e.message:`Failed to connect GA4`)}finally{l(!1)}}}return(0,Q.jsxs)(ws,{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)(C,{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:si(m),children:c?`Connecting & syncing…`:`Connect GA4`})]})}function Up({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:U(e.organicShare)})]})}function Wp({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)(Zl,{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:vp[e.sourceDimension]??``,children:_p[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 Gp=new Set([`gbp-listing-discrepancy`,`gbp-lodging-gap`,`gbp-cta-gap`,`gbp-metric-drop`,`gbp-keyword-drop`]),Kp={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.`},qp=`Google Business Profile is not connected yet. Your Canonry team can set this up.`,Jp={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.`},Yp={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 Xp({projectName:e,projectId:t}){let n=L(),[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}=oi(),y=!K()&&!ot(),b=y&&v,x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(!1),T=H(io({client:Y,path:{name:e}})),E=T.data?.find(e=>e.connectionType===`gbp`),D=!!E,O=r?{locationName:r}:void 0,k=H({...Sa({client:Y,path:{name:e}}),enabled:D}),A=H({...yo({client:Y,path:{name:e},query:O}),enabled:D}),j=H({...va({client:Y,path:{name:e},query:O}),enabled:D}),M=H({...ra({client:Y,path:{name:e},query:O}),enabled:D}),N=H({...hi({client:Y,path:{name:e},query:O}),enabled:D}),P=H({...Ia({client:Y,path:{name:e},query:O}),enabled:D}),ee=H({queryKey:[`gbp-section-insights`,e],queryFn:()=>Kn(e),enabled:D});function te(){li(n,`gbp`)}let ne=oe({...qa(),onSuccess:n=>{Ks({id:n.runId,projectId:t,kind:gr[`gbp-sync`],projectLabel:e,sourceAction:`gbp-sync`}),ci({title:`Business Profile sync started`,detail:`${e} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`gbp-sync:${e}`,dedupeMode:`replace`})}}),F=(0,Z.useSyncExternalStore)(Ms,Qs,Qs),I=Object.values(F.runs).some(e=>e.kind===gr[`gbp-sync`]&&e.projectId===t),re=ne.isPending||I,ie=oe({..._a(),onSuccess:()=>te()}),ae=H({...da({client:Y}),enabled:!T.isLoading&&!D&&b}),R=!!ae.data?.google?.configured,z=D&&k.data!==void 0&&k.data.locations.length===0,B=z&&b,V=H({...ba({client:Y,path:{name:e}}),enabled:B,retry:!1}),se=oe({...vi(),onSuccess:t=>{c(!0),ci({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`})}}),ce=oe({..._o(),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&&ae.isLoading)return;let t=e&&!e.disabled?e:C.current;t&&(w.current=!1,t.focus())});function le(){ce.reset(),g(!1),x.current?.focus()}(0,Z.useEffect)(()=>{z&&c(!0)},[z]);async function ue(){if(!R)m(Kp.credentialsMissing);else{u(!0),m(null),f(null);try{await Ad(e,`gbp`,()=>{f(Kp.refreshing),Promise.all([li(n,`google`),li(n,`gbp`)]).finally(()=>f(null))})===`popup`&&f(Kp.waiting)}catch(e){m(Se(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)(ws,{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)(ds,{ref:S,type:`button`,disabled:l||ae.isLoading,onClick:()=>void ue(),children:l?Kp.connecting:Kp.connect}),!ae.isLoading&&!R?(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:qp}):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 de=A.data,fe=k.data?.locations??[],pe=fe.filter(e=>e.selected),me=j.data?.keywords??[],he=M.data?.lodging??[],ge=N.data?.placeActions??[],_e=P.data?.places??[],ve=fe.length>0?fe[0].accountName:E.domain,ye=r?fe.find(e=>e.locationName===r)?.displayName??null:null,be=r?fe.filter(e=>e.locationName===r):pe,xe=new Set(be.map(e=>e.locationName)),Ce=he.filter(e=>xe.has(e.locationName)),we=ge.filter(e=>xe.has(e.locationName)),Te=_e.filter(e=>xe.has(e.locationName)),Ee=new Set(pe.map(e=>e.locationName)),De=r?me:me.filter(e=>Ee.has(e.locationName)),Oe=!r&&pe.length>1,ke=(ee.data??[]).filter(e=>!e.dismissed&&Gp.has(e.type)&&(!ye||e.query===ye||e.query===r||e.title.startsWith(ye)));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)(ds,{type:`button`,variant:`outline`,size:`sm`,disabled:re,onClick:()=>ne.mutate({client:Y,path:{name:e},body:{}}),children:re?`Syncing…`:`Sync`}),y&&(0,Q.jsx)(ds,{ref:x,type:`button`,variant:`ghost`,size:`sm`,"aria-expanded":h,"aria-controls":`gbp-disconnect-confirm`,disabled:ce.isPending,onClick:()=>{h?le():g(!0)},children:Yp.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:Yp.confirmTitle}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:Yp.confirmBody}),ce.isError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative break-words`,children:Ss(ce.error)}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Q.jsx)(ds,{type:`button`,variant:`destructive`,size:`sm`,disabled:ce.isPending,onClick:()=>ce.mutate({client:Y,path:{name:e}}),children:ce.isPending?Yp.disconnecting:Yp.confirm}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:ce.isPending,onClick:le,children:Yp.cancel})]})]}),(0,Q.jsxs)(`p`,{className:`mb-4 text-copy-13 text-muted`,children:[ve?(0,Q.jsxs)(Q.Fragment,{children:[`Account `,(0,Q.jsx)(`span`,{className:`font-mono text-secondary`,children:ve}),` · `]}):null,k.data?`${k.data.totalSelected} of ${k.data.totalDiscovered} locations tracked`:`Loading locations…`]}),pe.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`}),pe.map(e=>(0,Q.jsx)(`option`,{value:e.locationName,children:e.displayName},e.id))]})]}),pe.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:z?B?Jp.noneDiscovered:y&&_?Jp.noneDiscoveredDefaultAccount:Jp.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:[ke.length>0&&(0,Q.jsxs)(`div`,{className:`mb-6 grid gap-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Needs attention`}),ke.map(e=>(0,Q.jsx)(`div`,{className:[`surface-card insight-card`,hm(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))]}),de&&(0,Q.jsx)(Cm,{performance:de.performance,freshness:de.freshness,timeseries:de.timeseries}),de?.profileCompleteness&&(0,Q.jsx)($p,{summary:de.profileCompleteness}),be.length>0&&(0,Q.jsx)(em,{locations:be,lodging:Ce,places:Te,placeActions:we,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:[U(j.data.thresholdedPct,et.percent),` privacy-thresholded`]})]}),De.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`}),Oe&&(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:De.slice(0,25).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.keyword}),Oe&&(0,Q.jsx)(`td`,{className:`text-muted`,children:fe.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 (`,fe.length,`)`]}),s&&(0,Q.jsxs)(`div`,{className:`mt-3`,children:[y&&(0,Q.jsx)(Qp,{firstDiscovery:z,chooseAccount:B,accounts:V.data?.accounts??null,accountsLoading:V.isLoading,accountsError:V.error?Se(V.error):null,pending:se.isPending,onDiscover:t=>se.mutate({client:Y,path:{name:e},body:t})}),fe.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:fe.map(t=>(0,Q.jsx)(Zp,{location:t,showAction:!K(),columnCount:K()?3:4,disabled:ie.isPending,onSetSelected:async n=>{await ie.mutateAsync({client:Y,path:{name:e,locationName:t.locationName},body:{selected:n}})}},t.id))})]})]})]})]})})}function Zp({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(Se(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)(ds,{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)(ds,{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 Qp({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:Jp.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:Jp.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:Jp.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)}),Jp.trackNew]}),(0,Q.jsx)(ds,{type:`button`,variant:e?`default`:`outline`,size:`sm`,disabled:a||f,onClick:()=>o(t?{accountName:d,selectAllNew:l}:{selectAllNew:l}),children:a?Jp.discovering:e?Jp.discover:Jp.refresh})]})}function $p({summary:e}){if(e.locationCount===0)return null;let t=e.locationCount,n=[{label:`Description`,value:`${e.withDescription}/${t}`,tone:pm(e.withDescription,t,`caution`)},{label:`Hours`,value:`${e.withHours}/${t}`,tone:pm(e.withHours,t,`caution`)},{label:`Phone`,value:`${e.withPrimaryPhone}/${t}`,tone:pm(e.withPrimaryPhone,t,`caution`)},{label:`Service area`,value:`${e.withServiceArea}/${t}`,tone:pm(e.withServiceArea,t,`neutral`)},{label:`Secondary categories`,value:`${e.withSecondaryCategories}/${t}`,detail:`${e.secondaryCategoryTotal} total`,tone:pm(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 ${mm(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 em({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:_m(e.openStatus)})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(nm,{location:e})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(rm,{lodging:t})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(am,{place:n,mapsUri:e.mapsUri})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(sm,{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)(um,{location:e,lodging:t,place:n,placeActions:r})})})]},e.id)})})]})})]})}function tm(e){return[{label:`Description`,tone:gm(e.description)?`positive`:`neutral`,value:gm(e.description)?`set`:`not returned`},{label:`Hours`,tone:e.regularHours?`positive`:`neutral`,value:e.regularHours?`set`:`not returned`},{label:`Phone`,tone:gm(e.primaryPhone)?`positive`:`neutral`,value:gm(e.primaryPhone)?`set`:`not returned`},{label:`Website`,tone:gm(e.websiteUri)?`positive`:`neutral`,value:gm(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 nm({location:e}){let t=tm(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 rm({lodging:e}){return(0,Q.jsx)(lm,{...im(e)})}function im(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 am({place:e,mapsUri:t}){return(0,Q.jsx)(lm,{...om(e,t)})}function om(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 sm({actions:e}){return(0,Q.jsx)(lm,{...cm(e)})}function cm(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 lm({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 um({location:e,lodging:t,place:n,placeActions:r}){let i=t?xm(t.attributes):[];return(0,Q.jsxs)(`div`,{className:`grid gap-5 text-label-12 lg:grid-cols-3`,children:[(0,Q.jsxs)(dm,{title:`Owner profile · Business Information`,children:[(0,Q.jsx)(fm,{label:`Primary category`,value:e.primaryCategoryDisplayName??`Not returned`}),(0,Q.jsx)(fm,{label:`Secondary categories`,value:e.additionalCategories.length>0?e.additionalCategories.join(`, `):`Not returned`}),(0,Q.jsx)(fm,{label:`Description`,value:gm(e.description)?e.description:`Not returned`}),(0,Q.jsx)(fm,{label:`Hours`,value:e.regularHours?`Returned by Google`:`Not returned`}),(0,Q.jsx)(fm,{label:`Service area`,value:e.serviceArea?`Returned by Google`:`Not returned`}),(0,Q.jsx)(fm,{label:`Phone`,value:e.primaryPhone??`Not returned`}),(0,Q.jsx)(fm,{label:`Website`,value:e.websiteUri??`Not returned`}),(0,Q.jsx)(fm,{label:`Open status`,value:_m(e.openStatus)}),(0,Q.jsx)(fm,{label:`Opening date`,value:e.openingDate??`Not returned`})]}),(0,Q.jsx)(dm,{title:`Hotel data · Lodging API`,children:t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(fm,{label:`Last checked`,value:bm(t.syncedAt)}),(0,Q.jsx)(fm,{label:`Groups returned`,value:String(t.populatedGroupCount)}),(0,Q.jsx)(fm,{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)(dm,{title:`Public listing + CTAs`,children:[n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(fm,{label:`Places tier`,value:n.tier}),(0,Q.jsx)(fm,{label:`Last checked`,value:bm(n.syncedAt)}),(0,Q.jsx)(fm,{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:[vm(e.placeActionType),e.isPreferred?` · preferred`:``]}),(0,Q.jsxs)(`span`,{className:`text-faint`,children:[vm(e.providerType),e.uri?` · ${ym(e.uri)}`:``]})]},e.placeActionLinkName))})})]})]})}function dm({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 fm({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 pm(e,t,n){return e===t?`positive`:e===0?n:`caution`}function mm(e){switch(e){case`positive`:return`text-positive`;case`caution`:return`text-caution`;case`negative`:return`text-negative`;case`neutral`:return`text-neutral`}}function hm(e){return e===`critical`||e===`high`?`insight-card-negative`:e===`medium`?`insight-card-caution`:``}function gm(e){return typeof e==`string`&&e.trim().length>0}function _m(e){return e?vm(e):`Not returned`}function vm(e){return e?e.toLowerCase().split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `):`Unknown`}function ym(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function bm(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}function xm(e){return Object.entries(e).filter(([e,t])=>e!==`name`&&e!==`metadata`&&Sm(t)).map(([e])=>vm(e.replace(/([a-z])([A-Z])/g,`$1_$2`)))}function Sm(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e!=`object`||Object.keys(e).length>0}function Cm({performance:e,freshness:t,timeseries:n}){let r=e.totals,i=De.filter(e=>(r[e]??0)>0),a=At.filter(e=>(r[e]??0)>0),o=Object.keys(r).filter(e=>(r[e]??0)>0&&Ke(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 ${Jr(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)(wm,{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:[Tt(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)(wm,{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=>Tt(e)).join(`, `)]})]})}function wm({data:e,metrics:t,kind:n,firstPending:r,lastDate:i}){return(0,Q.jsx)(`div`,{className:`h-48 w-full`,children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:e,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:Vr,minTickGap:24}),(0,Q.jsx)(ve,{tick:Xr,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(_e,{...ei,labelFormatter:Jr,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),Tt(String(t??``))]}),(0,Q.jsx)(me,{wrapperStyle:{fontSize:12,color:Gr.text},formatter:e=>Tt(e)}),r&&i&&(0,Q.jsx)(pe,{x1:r,x2:i,fill:Gr.surface,fillOpacity:.55,stroke:`none`,label:{value:`pending`,position:`insideTopRight`,fill:Gr.textDim,fontSize:12}}),t.map((e,t)=>n===`line`?(0,Q.jsx)(ye,{type:`monotone`,dataKey:e,stroke:Rr[t%Rr.length],strokeWidth:2,dot:!1,isAnimationActive:!1},e):(0,Q.jsx)(ge,{type:`monotone`,dataKey:e,stackId:`reach`,stroke:Rr[t%Rr.length],fill:Rr[t%Rr.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},e))]})})})}var Tm=25;function Em(e){return typeof window>`u`?e:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,``)??``}${e}`}function Dm(e){return e.toLocaleString()}function Om(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 km(e){let t=e.filter(e=>e.kind===gr[`backlink-extract`]&&!Ps(e.status));return t.length===0?null:t.reduce((e,t)=>e.createdAt>t.createdAt?e:t)}function Am(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 jm({projectName:e}){let t=ot(),[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(null),[o,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,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([Rt().catch(()=>null),Ge(e,{excludeCrawlers:!0}).catch(()=>null),kt(e,{limit:Tm,offset:b,excludeCrawlers:!0}).catch(e=>{if(e instanceof zn&&e.code===`NOT_FOUND`)return null;throw e}),un(e,{surface:An.backlinks}).catch(()=>null),Ut(e).catch(()=>[])]);f(t),r(n),a(i),u(o);let c=km(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(!p)return;let e=p.id,t=!1,n=async()=>{try{let n=await nr(e);if(t)return;Ps(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)}},[p,O]),(0,Z.useEffect)(()=>{if(!p)return;let e=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(e)},[p]),(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 lr(e);h(t)}catch(e){e instanceof zn&&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??[],j=i?.total??0,N=n?.excludedLinkingDomains??0,P=Math.floor(b/Tm)+1;return(0,Z.useEffect)(()=>{b>0&&b>=j&&x(0)},[b,j]),(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)(ws,{className:`surface-card p-4 mb-4 bg-negative-soft`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:E})}),p&&(0,Q.jsx)(ws,{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)(c,{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:p.status}),(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:[Am(p.startedAt??null,p.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&&!p&&(0,Q.jsx)(ws,{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)(m,{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:Dr(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.`})]})]})}),ee()]});function ee(){return S?(0,Q.jsx)(ws,{className:`surface-card p-6`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading backlinks…`})}):te()}function te(){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`,c=d&&(d.status===`downloading`||d.status===`querying`||d.status===`queued`);return e?ne((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||p!==null,onClick:si(k),children:[(0,Q.jsx)(s,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsx)(Hc,{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:Em(`/backlinks`),children:`Open admin`})})]})):(0,Q.jsx)(ws,{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)(l,{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:Em(`/backlinks`),children:`Set up backlinks`})})})]}),c&&(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:Em(`/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:Em(`/backlinks`),children:`Go to Backlinks admin`})})})]}),a&&!c&&!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||p!==null,onClick:si(k),children:[(0,Q.jsx)(M,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:w?`Queuing…`:`Run extract`]}),(0,Q.jsx)(Hc,{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:Em(`/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:Em(`/backlinks`),children:`Go to Backlinks admin`})}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:w||p!==null,onClick:si(k),children:[(0,Q.jsx)(M,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsxs)(Hc,{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 ne(e){if(!n)return null;let t=`release`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Mm,{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 `,Om(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)(ws,{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:Dm(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&&j===0?`Every referring domain in this ${t} was a crawler/proxy host (${N} hidden).`:`No referring domains in this ${t}.`})})]})]})}),(0,Q.jsx)(eu,{page:P,pageSize:Tm,visibleRows:A.length,totalRows:j,onPageChange:e=>x((e-1)*Tm)})]}),(0,Q.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:e})]})}}function Mm({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?Ru(o.change,o.unit):void 0,series:o?Bu(o):void 0,formatValue:i,allowDecimals:o?.unit===`fraction`}},s=[o(`referring-domains`,`Referring domains`,`Unique domains linking to ${e.targetDomain}.`,e.totalLinkingDomains,Dm),o(`hosts`,`Total linking hosts`,`Aggregate linking hosts across referring domains.`,e.totalHosts,Dm),o(`top-10-concentration`,`Top-10 concentration`,`Share of linking hosts from the 10 largest linking domains.`,Number(e.top10HostsShare),e=>U(e))],c=s.some(ju),l=a.get(`referring-domains`)?.series??[],u=l[0],d=l.at(-1);return(0,Q.jsx)(Ku,{name:`Backlinks figures`,groups:[{key:`backlinks`,label:`Every release`,basis:i?zu(i.figures):void 0,figures:s}],selected:c?[n]:[],onSelect:r,cadence:`release`,span:c&&u&&d?Vu(u,d):void 0,emptyChartMessage:t?`One release so far. The trend starts with the next one.`:`Release history could not be loaded.`})}var Nm={[G[`keyword-metrics`]]:`Search demand`,[G[`domain-intelligence`]]:`Domain comparison`,[G[`ranked-keywords`]]:`Searches you rank for`,[G[`market-rankings`]]:`Market rankings`,[G[`competitor-discovery`]]:`Organic competitors`,[G[`keyword-gaps`]]:`Search gaps`},Pm={[Mt.shared]:`Shared`,[Mt.missing]:`Missing`,[Mt.outranked]:`Competitor ahead`},Fm=`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.`,Im={[Gt.queued]:`Queued`,[Gt.running]:`Refreshing`,[Gt.completed]:`Completed`,[Gt.partial]:`Partial results`,[Gt.failed]:`Failed`,[Gt.cancelled]:`Cancelled`,[Gt[`reconciliation-required`]]:`Needs review`},Lm=25,Rm=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:1}),zm=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}),Bm=Intl.DateTimeFormat().resolvedOptions().timeZone,Vm=new Intl.DisplayNames([`en`],{type:`language`,fallback:`none`}),Hm=`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`,Um=`px-4 py-3 text-right align-top tabular-nums whitespace-nowrap`,Wm=`min-w-56 px-4 py-3 text-left align-top text-label-14`,Gm=`Position on the page, counting maps and other blocks`,Km={overview:`Overview`,"latest-rankings":`Latest rankings`,...Nm},qm=[G[`market-rankings`],G[`ranked-keywords`],G[`keyword-metrics`],G[`domain-intelligence`],G[`competitor-discovery`],G[`keyword-gaps`]];function Jm(e){return e?.status===Gt.queued||e?.status===Gt.running}function Ym(e){return e.status===Gt.completed||e.status===Gt.partial}function Xm({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?zm.format(e):Rm.format(e)})}function Zm({status:e}){let t=e===Gt.completed?`positive`:e===Gt.failed?`negative`:e===Gt.partial||e===Gt[`reconciliation-required`]?`caution`:`neutral`;return(0,Q.jsx)(J,{tone:t,children:Im[e]})}function Qm(e){let t=Rn(e).split(`/`).at(-1)??e,n=tr.safeParse(t.replaceAll(`_`,`-`));return n.success?Nm[n.data]:t.replaceAll(/[-_]/g,` `)}function $m(e){return e===`mobile`?`phone results`:e===`desktop`?`computer results`:`device not specified by source`}function eh(e){return e.capabilities.includes(G[`market-rankings`])?`Market locations`:`Location ${e.locationCode}`}function th(e){try{return Vm.of(e)??e}catch{return e}}function nh(e){return e.capabilities.includes(G[`market-rankings`])?`searches`:`tasks`}function rh(e){return e.capability!==G[`market-rankings`]||![Gt.queued,Gt.running,Gt.completed].includes(e.status)}function ih(e,t){let n=e.capabilities.includes(G[`market-rankings`]);return`${t} ${t===1?n?`search`:`task`:nh(e)}`}function ah(e,t){return Number.isFinite(Date.parse(e))?Jn(Lt(e,t)):null}var oh={[Gt.failed]:`Latest refresh failed`,[Gt.cancelled]:`Latest refresh cancelled`,[Gt[`reconciliation-required`]]:`Latest refresh needs review`};function sh(e,t){let n=e&&e.id!==t?.id?oh[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=`${ih(t,t.failedTasks)} failed`,n=t.capabilities.includes(G[`market-rankings`])?`Their queries show as Failed.`:`Open Refresh history for details.`;return{label:e,text:`${e}: ${t.failedTasks} of ${ih(t,t.taskCount)} in this refresh returned no results. ${n}`}}return t.status===Gt.partial?{label:`Partial results`,text:`Partial results: ${t.error??`some ${nh(t)} returned only part of their results or did not run. Open Refresh history for details.`}`}:null}function ch({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:Qm(e.dataset)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Search engine`}),(0,Q.jsxs)(`dd`,{children:[`Google · `,$m(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:Fn(e.collectedAt,Bm)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Source updated`}),(0,Q.jsx)(`dd`,{children:e.sourceUpdatedAt?Qe(e.sourceUpdatedAt):`Not supplied`})]})]})}function lh({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)(h,{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)(ch,{source:t})]})]})}function uh({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:Ss(e)}),(0,Q.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:t,children:`Retry`})]})}function dh({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 fh(e,t){return!e||!t?.supported?[]:qm.filter(n=>e.capabilities.includes(n)&&(t.capabilities?.includes(n)??!0))}function ph({projectName:e}){let{isAdmin:t}=oi(),n=R({strict:!1}),r=ae(),i=H(ya({client:Y,path:{name:e}})),a=H(po({client:Y,path:{name:e}})),s=H({...Ea({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()&&!ot(),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)(uh,{error:i.error,retry:()=>{i.refetch()}});if(a.error)return(0,Q.jsx)(uh,{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=>fh(t,e)))),S=G[`market-rankings`],C=b&&[...x].some(e=>e!==S),w=b&&x.has(S),T=g&&(C||g.rankings&&w),E=t&&!K()&&!ot()?(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:`${Hm} 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)(Dd,{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!==ft.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)(dg,{projectName:e,context:i.data,profile:c.profile,id:c.id,onClose:y,onSaved:e=>_(e,!0)},c.id),!ot()&&!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)(uh,{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)(dh,{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)(mh,{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)(dh,{title:`No SEO profiles yet`,children:`Set up market rankings with the CLI or API.`}):(0,Q.jsx)(dh,{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)(dh,{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)(dh,{title:`Profile unavailable`,children:`This saved profile is no longer available. Select another profile to view its data.`}):!c&&(0,Q.jsx)(dh,{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 mh({projectName:e,profile:t,context:n,selectedRunId:r,onLatest:i}){let a=L(),o=R({strict:!1}),s=ae(),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),g=(0,Z.useRef)(null),_=(0,Z.useRef)(null),y={name:e},b=to({client:Y,path:y,query:{profileId:t.id,runId:r}}),x=H({...b,refetchInterval:e=>Jm(e.state.data?.latestRun)?2e3:!1}),S=oe({...xi({client:Y}),meta:{skipGlobalErrorToast:!0}}),C=oe({...Fi({client:Y}),meta:{skipGlobalErrorToast:!0}}),w=x.data?.latestRun,T=x.data?.evidenceRun,E=x.data?.evidenceRun?.capabilities??t.capabilities,D=[`overview`,...qm.filter(e=>E.includes(e))],O=o.seoRegion||o.seoMarket||o.seoShow||o.seoSort||o.seoQ,k=!r&&O&&E.includes(G[`market-rankings`])?G[`market-rankings`]:`overview`,A=o.seoView===`latest-rankings`?o.seoView:D.find(e=>e===o.seoView),M=A??k,N=o.seoView===`activity`||!(!r||A),P=d||N,ee=()=>{f(!1),N&&r?i():N&&s({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoView:void 0}),replace:!0})},te=t=>{f(!1),s({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})})},ne=(t,n=!1)=>{n&&l.current?.querySelector(`[data-seo-view="${t}"]`)?.focus();let i=t===G[`market-rankings`]?{}:{seoRegion:void 0,seoMarket:void 0,seoShow:void 0,seoSort:void 0,seoQ:void 0};s({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...i,seoView:t===`overview`&&!r?void 0:t})})},F=Jm(w),I=S.isPending||C.isPending,re=n.access.canRun&&!K()&&!ot(),ie=n.connections.find(e=>e.id===t.connectionId),z=n.scopes.find(e=>e.kind===t.scope.kind&&e.key===(t.scope.key??null)),B=H({...Gi({client:Y,path:y,query:{kind:In[`seo-sync`]}}),retry:!1}),V=!B.isError&&B.data?.enabled&&B.data.nextRunAt?B.data.nextRunAt:null,se=V?ah(V,B.data?.timezone??`UTC`):null,ce=T?.finishedAt&&Ym(T)?ah(T.finishedAt,Bm):null,le=re&&ie&&(t.capabilities.includes(G[`market-rankings`])?`Refresh now runs new Google searches through ${ie.label} for this profile’s tracked queries and markets.`:`Refresh now requests the latest data available from ${ie.label}. The source may return the same readings until its dataset updates.`),ue=[ce&&`Last refresh shows when Canonry saved these results.`,se&&`Next scheduled refresh ${se}.`,le].filter(Boolean).join(` `),de=F?null:sh(w,T);return(0,Z.useEffect)(()=>{w&&(Jm(w)?_.current=w.id:_.current===w.id&&(_.current=null,li(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:ce&&T?.finishedAt?(0,Q.jsxs)(Q.Fragment,{children:[r?`Viewing saved results from`:`Last refresh`,` `,(0,Q.jsx)(`time`,{dateTime:T.finishedAt,title:Fn(T.finishedAt,Bm)??void 0,children:ce})]}):`No saved results`}),!r&&ue&&(0,Q.jsx)(X,{placement:`bottom`,text:`About refreshes. ${ue}`}),F&&w&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),w.cancelRequested?`Cancellation requested`:Im[w.status],` · `,w.completedTasks,` of `,w.taskCount,` `,nh(w),` completed`]}),de&&(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:de.label,text:de.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)(j,{className:`size-4`,"aria-hidden":`true`}),`Refresh history`]}),r?(0,Q.jsx)(q,{variant:`secondary`,onClick:i,children:`View latest data`}):re&&(0,Q.jsxs)(q,{disabled:I||F||!x.data||!n.available||!ie,onClick:si(async()=>{if(!(!re||r||F||I)){m(null);try{if(!g.current){let e=await S.mutateAsync({path:y,body:{profileId:t.id}});if(e.availability!==jt.ready){m(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,Jm(n)&&(_.current=n.id,Ks({id:n.id,projectId:n.projectId,projectName:e,projectLabel:e,kind:gr[`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){Cs(e).code===`VALIDATION_ERROR`&&(g.current=null),m(Ss(e))}}}),children:[(0,Q.jsx)(v,{"aria-hidden":`true`,className:`size-4 ${I?`motion-safe:animate-spin`:``}`}),I?`Starting refresh…`:F?`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.`,re&&n.available&&ie&&` Refresh to use the current settings.`]}),!ot()&&z&&!z.supported&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:z.reason??`This scope is not supported for domain data.`}),x.isRefetchError&&(0,Q.jsx)(uh,{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:()=>ne(e),children:Km[e]},e)})}),x.isLoadingError?(0,Q.jsx)(`div`,{className:`pt-4`,children:(0,Q.jsx)(uh,{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)(Sh,{projectName:e,profileId:t.id,data:x.data,active:F,canRun:re,nextRefresh:se,snapshot:!!r||M===`latest-rankings`,historical:!!r,onOpen:e=>ne(e,!0)}):(0,Q.jsx)(kh,{projectName:e,profileId:t.id,runId:x.data.evidenceRunId,view:M,active:F,nextRefresh:se},`${t.id}:${M}:${x.data.evidenceRunId??`empty`}`)]}),(0,Q.jsx)(_c,{title:`Refresh history`,subtitle:t.name,open:P,onClose:ee,onCloseAutoFocus:e=>{let t=u.current;t?.isConnected&&!(N&&r)&&(e.preventDefault(),t.focus())},children:P&&(0,Q.jsx)(ug,{projectName:e,profileId:t.id,canRun:re,selectedRunId:r,exactRefresh:N&&!!r,onViewSaved:te,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)(h,{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: `,ot()?`Fictional demo data`:ie?.label??`Source unavailable`,`. Google · `,$m(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}`,`. `,eh(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)(ch,{source:x.data.summary.provenance})]})]})]})}var hh=6,gh=new Intl.DateTimeFormat(`en-US`,{month:`short`,year:`numeric`,timeZone:`UTC`}),_h=new Intl.DateTimeFormat(`en-US`,{month:`short`,year:`2-digit`,timeZone:`UTC`}),vh=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),yh=[{days:180,label:`180 days`},{days:90,label:`90 days`},{days:30,label:`30 days`}],bh={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 xh({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===mn.market,p=t.kind===mn.ranked,m=Oe[t.kind],h=m.map(e=>{let n=t.points.filter(t=>t[e]!=null).at(-1)?.[e]??null;return{...bh[e],key:e,value:n===null?`—`:Rm.format(n),stateValue:n===null,interactive:!0,change:Ru(t.changes[e]??null,or.count),series:t.points.map(t=>({date:t.observedAt,current:t[e]??null})),formatValue:e=>p?Rm.format(e):vh.format(e),formatExact:e=>Rm.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&&Th(t.target),`Google`,f?`Market locations`:null,t.languageCode&&th(t.languageCode)].filter(Boolean).join(` · `),b=(a?i??t.keyword:t.keyword)??``,x=t.rankedKeywords??[],S=b!==``&&!x.includes(b);Ws(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?Vu({date:C,observedAt:C},{date:w,observedAt:w}):void 0,E=t.points.filter(e=>e[_]!=null),D=E.length,k=E.at(-1),A=k?ah(k.observedAt,Bm):null,j=k&&k!==t.points.at(-1),M=m.length>1?zu(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,ee=[A&&j&&`Data through ${A}.`,T&&`Chart dates ${T}.`,D>=2&&`${Rm.format(D)} comparable refreshes.`,D===1&&A&&!j&&`Reading from ${A}.`,M&&`Change ${M}.`,t.marketQueryCount!==null&&`${Rm.format(t.marketQueryCount)} non-brand queries across markets.`,!f&&t.locationCode!==null&&`Search location code ${t.locationCode}.`].filter(Boolean).join(` `),te=D===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.`,ne=e=>{let t=Hn.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}),ee&&(0,Q.jsx)(X,{placement:`bottom`,text:`About this chart. ${ee}`})]}),(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:`${Hm} 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)(Ku,{name:v,groups:[{key:`seo`,figures:h,basis:M}],selected:[_],onSelect:e=>{let t=sn.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:te,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:`${Hm} min-w-28 sm:min-h-9`,"aria-label":`SEO trend range`,"aria-busy":u,value:n,onChange:e=>ne(e.target.value),children:yh.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)(O,{className:`size-4`,"aria-hidden":`true`})]})]})})})]})}function Sh({snapshot:e=!1,historical:t=!1,...n}){let r=R({strict:!1}),i=ae(),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===G[`domain-intelligence`]||e===G[`market-rankings`]||e===G[`ranked-keywords`])===!0,m=ho({client:Y,path:{name:u},query:{profileId:d,days:a,keyword:o}}),h=(0,Z.useRef)(void 0),g=H({...m,enabled:!e&&p,placeholderData:re});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)(Dh,{...n},l.evidenceRunId??`empty`)]});if(!p)return(0,Q.jsx)(Dh,{...n},l.evidenceRunId??`empty`);let _=g.data??h.current;if(g.error&&!_)return(0,Q.jsx)(`div`,{className:`pt-4`,children:(0,Q.jsx)(uh,{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??Oe[v].some(e=>_.points.some(t=>t[e]!=null)))&&v!==mn.market&&!(v===mn.ranked&&o)&&(l.keywordMetricsCount>0||l.rankedKeywordCount>0))return(0,Q.jsx)(Dh,{...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)(xh,{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}),Et(`window`)},onMetricChange:e=>{y({seoTrendMetric:e}),Et(`other`)},onKeywordChange:e=>{y({seoTrendKeyword:e||void 0}),Et(`other`)}}),g.error&&(0,Q.jsx)(uh,{error:g.error,retry:()=>{g.refetch()}})]})}function Ch({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?`—`:Rm.format(e.value)})),g=new Map(i.map(e=>[e.label,e.tick??e.label])),_=e=>vh.format(e),v=e=>g.get(e)??e,y=(0,Q.jsx)(_e,{...ei,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`?Rm.format(e):`—`),r]}}),b=Rr[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)(de,{width:`100%`,height:c?220:i.length*38+34,children:c?(0,Q.jsxs)(he,{data:h,accessibilityLayer:!1,margin:{top:12,right:12,bottom:2,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`label`,tick:Xr,tickFormatter:v,tickLine:!1,axisLine:!1,minTickGap:16}),(0,Q.jsx)(ve,{tick:Xr,tickFormatter:_,tickLine:!1,axisLine:!1,allowDecimals:!1,width:46}),y,(0,Q.jsx)(se,{dataKey:`plotted`,fill:b,maxBarSize:46,minPointSize:1,radius:[3,3,0,0],isAnimationActive:!1})]}):(0,Q.jsxs)(be,{data:h,layout:`vertical`,accessibilityLayer:!1,margin:{top:3,right:58,bottom:2,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,horizontal:!1}),(0,Q.jsx)(ve,{type:`category`,dataKey:`label`,tick:Xr,tickFormatter:v,tickLine:!1,axisLine:!1,width:a===G[`domain-intelligence`]?48:112,interval:0}),(0,Q.jsx)(fe,{type:`number`,tick:Xr,tickFormatter:e=>l&&e<1?``:_(e),tickLine:!1,axisLine:!1,allowDecimals:!1,domain:l?[1,`auto`]:[0,`auto`]}),y,l?(0,Q.jsx)(ye,{dataKey:`plotted`,stroke:`none`,dot:{r:5,fill:b,stroke:b},activeDot:!1,isAnimationActive:!1,children:(0,Q.jsx)(le,{dataKey:`display`,position:`right`,fill:Xr.fill,fontSize:12})}):(0,Q.jsxs)(se,{dataKey:`plotted`,fill:b,barSize:18,minPointSize:1,radius:[0,3,3,0],isAnimationActive:!1,children:[h.map((e,t)=>(0,Q.jsx)(ue,{fill:e.value===null?`transparent`:b},`${e.label}:${t}`)),(0,Q.jsx)(le,{dataKey:`display`,position:`right`,fill:Xr.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 ${Nm[a]}`,onClick:()=>o(a),children:[Nm[a],(0,Q.jsx)(O,{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)(Xm,{value:e.value})})]},`${e.label}:${t}`))})]})})]})}function wh(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 Th(e){return`${e.value} · ${e.includeSubdomains?`includes subdomains`:`exact host`}`}function Eh({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)(Xm,{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)(Xm,{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)(Xm,{value:e.estimatedOrganicTraffic})})]})]})}function Dh({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=H({...vo(d),enabled:p}),g=H({...Ca({...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?wh(v):[],b=y.some(e=>e.value!==null),x=f&&!p&&!b&&(!m||g.isSuccess)&&n.rankedKeywordCount>0,S=H({...Wa({...d,query:{...d.query,limit:hh}}),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,E=H({...gi({...d,query:{...d.query,limit:Lm,offset:(s-1)*Lm}}),enabled:T}),D=p?h:m&&!g.isSuccess?g:x&&!S.isSuccess?S:T?E:null,k;if(D?.error)k=(0,Q.jsx)(uh,{error:D.error,retry:()=>{D.refetch()}});else if(D?.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)(Ch,{title:`Google rank across markets`,caption:`Non-brand queries · ${eg(e)}`,category:`Outcome`,unit:`Queries`,points:ar(t,e).map(t=>({label:t.label,value:e[t.count]})),view:G[`market-rankings`],onOpen:o})}else if(v&&b)k=(0,Q.jsx)(Ch,{title:`Organic positions in the top 20`,caption:`${Th(v.target)} · Google · Location ${v.provenance.locationCode} · ${v.provenance.languageCode}`,category:`Position`,unit:`Ranking searches`,points:y,view:G[`domain-intelligence`],onOpen:o});else if(x&&w)k=(0,Q.jsx)(Ch,{title:`Organic positions for saved searches`,caption:`First ${C.length} of ${Rm.format(n.rankedKeywordCount)} saved results · Google`,category:`Search and target`,unit:`Organic position`,rankAxis:!0,view:G[`ranked-keywords`],onOpen:o,points:C.map(e=>({label:`${e.keyword} · ${Th(e.target)}`,tick:Oh(e.keyword),value:e.rankOrganic}))});else if(T&&E.data?.items.length){let e=E.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:gh.format(t),tick:_h.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:`${Hm} min-w-0 sm:max-w-96`,value:e.indexOf(t),onChange:e=>{u(Number(e.target.value)),Et(`other`)},children:e.map((e,t)=>(0,Q.jsx)(`option`,{value:t,children:e.keyword},`${e.keyword}:${t}`))})]}),E.data.total>Lm&&(0,Q.jsx)(eu,{page:s,pageSize:Lm,visibleRows:e.length,totalRows:E.data.total,disabled:E.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)(Ch,{title:`Monthly search demand`,caption:a,category:`Month`,unit:`Estimated searches`,points:n,monthAxis:!0,view:G[`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)(Ch,{title:`Search demand estimate`,caption:a,category:`Search`,unit:`Estimated monthly searches`,points:[{label:t.keyword,tick:Oh(t.keyword),value:t.searchVolume}],view:G[`keyword-metrics`],onOpen:o,controls:i})}else{let e=qm.find(e=>n.evidenceRun?.capabilities.includes(e));k=(0,Q.jsxs)(`div`,{className:`material-base`,children:[(0,Q.jsx)(dh,{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 ${Km[e]}`,onClick:()=>o(e),children:[Km[e],(0,Q.jsx)(O,{className:`size-4`,"aria-hidden":`true`})]})})]})}return(0,Q.jsxs)(`div`,{className:`space-y-4 pt-4`,children:[k,n.summary&&(0,Q.jsx)(Eh,{summary:n.summary})]})}function Oh(e){return e.length>16?`${e.slice(0,15)}…`:e}function kh({projectName:e,profileId:t,runId:n,view:r,active:i,nextRefresh:a}){return r===G[`market-rankings`]?n?(0,Q.jsx)($h,{projectName:e,profileId:t,runId:n,active:i}):(0,Q.jsx)(dh,{title:`No market rankings yet`,children:a?`First refresh ${a}`:`Refresh this profile to rank its tracked queries in each market.`}):(0,Q.jsx)(Ah,{projectName:e,profileId:t,runId:n,view:r,active:i})}function Ah({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:Lm,offset:(a-1)*Lm}},m=H({...Wa(p),enabled:!!n&&r===G[`ranked-keywords`]}),h=H({...gi(p),enabled:!!n&&r===G[`keyword-metrics`]}),g=H({...Ca(p),enabled:!!n&&r===G[`domain-intelligence`]}),_=H({...xa({...p,query:{...p.query,sort:l}}),placeholderData:re,enabled:!!n&&r===G[`competitor-discovery`]}),v=H({...ia({...p,query:{...p.query,kind:s||void 0,sort:d}}),placeholderData:re,enabled:!!n&&r===G[`keyword-gaps`]}),y=r===G[`ranked-keywords`]?m:r===G[`keyword-metrics`]?h:r===G[`competitor-discovery`]?_:r===G[`keyword-gaps`]?v:g;return n?(0,Q.jsxs)(`div`,{className:`space-y-3 pt-4`,children:[r===G[`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:`${Hm} 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:Mt.missing,children:`Missing`}),(0,Q.jsx)(`option`,{value:Mt.shared,children:`Shared`}),(0,Q.jsx)(`option`,{value:Mt.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===G[`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)(uh,{error:y.error,retry:()=>{y.refetch()}}):y.data?y.data.items.length===0?(0,Q.jsx)(dh,{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":`${Nm[r]} table`,"aria-busy":y.isFetching,tabIndex:0,children:[r===G[`ranked-keywords`]&&m.data&&(0,Q.jsx)(Fh,{rows:m.data.items}),r===G[`keyword-metrics`]&&h.data&&(0,Q.jsx)(Ih,{rows:h.data.items}),r===G[`domain-intelligence`]&&g.data&&(0,Q.jsx)(Lh,{rows:g.data.items}),r===G[`competitor-discovery`]&&_.data&&(0,Q.jsx)(Nh,{rows:_.data.items,sort:l,onSort:e=>{u(e),o(1)}}),r===G[`keyword-gaps`]&&v.data&&(0,Q.jsx)(Ph,{rows:v.data.items,sort:d,onSort:e=>{f(e),o(1)}})]}),(0,Q.jsx)(eu,{page:a,pageSize:Lm,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 `,Nm[r].toLowerCase(),`…`]})]}):(0,Q.jsxs)(dh,{title:`No saved data yet`,children:[`Refresh this profile to collect `,Nm[r].toLowerCase(),` for its saved scope.`]})}function jh({value:e}){return e===null?(0,Q.jsx)(Xm,{value:null}):(0,Q.jsxs)(Q.Fragment,{children:[e>0?`+`:``,Rm.format(e)]})}function Mh({label:e,sort:t,ascending:n,descending:r,align:i=`right`,onSort:a,help:o}){return(0,Q.jsx)(Qh,{label:e,align:i,sorted:t===n?`ascending`:t===r?`descending`:null,onSort:()=>a(t===n?r:n),help:o,showUnsorted:!0})}function Nh({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)(Mh,{label:`Competitor`,align:`left`,sort:t,ascending:Dt.domain,descending:Dt[`-domain`],onSort:n}),(0,Q.jsx)(Mh,{label:`Shared searches`,sort:t,ascending:Dt.shared,descending:Dt[`-shared`],onSort:n}),(0,Q.jsx)(Mh,{label:`Avg. position`,sort:t,ascending:Dt.position,descending:Dt[`-position`],onSort:n}),(0,Q.jsx)(Mh,{label:`Est. organic traffic`,sort:t,ascending:Dt.traffic,descending:Dt[`-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:Wm,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:Um,children:(0,Q.jsx)(Xm,{value:e.sharedKeywords})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.averagePosition})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(lh,{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)(Xm,{value:e.organicKeywords})]}),(0,Q.jsxs)(`p`,{children:[`Target: `,e.target.value,` · includes subdomains`]})]})})]},`${e.target.value}:${e.domain}:${t}`))})]})}function Ph({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)(Mh,{label:`Search`,align:`left`,sort:t,ascending:He.keyword,descending:He[`-keyword`],onSort:n}),(0,Q.jsx)(Mh,{label:`Comparison`,align:`left`,sort:t,ascending:He.kind,descending:He[`-kind`],onSort:n}),(0,Q.jsx)(Mh,{label:`Your rank`,sort:t,ascending:He[`target-rank`],descending:He[`-target-rank`],onSort:n}),(0,Q.jsx)(Mh,{label:`Competitor rank`,sort:t,ascending:He[`competitor-rank`],descending:He[`-competitor-rank`],onSort:n}),(0,Q.jsx)(Mh,{label:`Rank gap`,sort:t,ascending:He[`rank-gap`],descending:He[`-rank-gap`],onSort:n,help:Fm}),(0,Q.jsx)(Mh,{label:`Monthly searches`,sort:t,ascending:He.volume,descending:He[`-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:Wm,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===Mt.shared?`neutral`:`caution`,children:Pm[e.kind]})}),(0,Q.jsx)(`td`,{className:Um,children:e.kind===Mt.missing?(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Not found`}):(0,Q.jsx)(Xm,{value:e.targetRankOrganic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.competitorRankOrganic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(jh,{value:e.rankGap})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(lh,{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)(Xm,{value:e.keywordDifficulty})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(Xm,{value:e.cpcUsd,currency:!0})]})]})})]},`${e.target.value}:${e.competitor.value}:${e.keyword}:${t}`))})]})}function Fh({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:`${Um} text-label-13-strong`,children:`Position`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:`Est. traffic`}),(0,Q.jsx)(`th`,{className:`${Um} 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:Wm,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)(Zl,{value:e.url??e.target.value})})]}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.rankOrganic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.estimatedTraffic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.keywordDifficulty})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(lh,{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:[Gm,`: `,(0,Q.jsx)(Xm,{value:e.rankAbsolute})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(Xm,{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 Ih({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:`${Um} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:`CPC`}),(0,Q.jsx)(`th`,{className:`${Um} 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:`${Wm} text-primary`,children:e.keyword}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.cpcUsd,currency:!0})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{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)(lh,{label:e.keyword,source:e.provenance,children:[(0,Q.jsxs)(`p`,{children:[`Ad competition: `,e.adCompetition===null?`Not supplied`:U(e.adCompetition,et.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)(Xm,{value:e.searchVolume})})]},`${e.year}-${e.month}`))})]})})]},`${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:`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:`${Um} text-label-13-strong`,children:`Searches ranked for`}),(0,Q.jsx)(`th`,{className:`${Um} 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:Wm,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:Um,children:(0,Q.jsx)(Xm,{value:e.organicKeywords})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsx)(lh,{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)(Xm,{value:e.top1})}),(0,Q.jsx)(`dt`,{children:`Positions 2–3`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.top2To3})}),(0,Q.jsx)(`dt`,{children:`Positions 4–10`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.top4To10})}),(0,Q.jsx)(`dt`,{children:`Positions 11–20`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.top11To20})}),(0,Q.jsx)(`dt`,{children:`Est. traffic value`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.estimatedOrganicTrafficValueUsd,currency:!0})})]})})})]},`${e.target.value}:${t}`))})]})}var Rh=5,zh=10,Bh=`all`;function Vh(e){return e===Bh?Bh:Xn.safeParse(e).data??null}var Hh={column:`ranks11To20`,descending:!0},Uh={3:`sm:grid-cols-3`,4:`sm:grid-cols-4`,5:`sm:grid-cols-5`},Wh=`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`,Gh=`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 Kh(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 qh(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 Jh(e){let t=e.filter(e=>e.kind===qn.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 Yh(e,t){return e.counts[t]}function Xh(e){let t=e.descending?-1:1,n=e.column;return n===`label`?(e,n)=>t*(dt(e.label,n.label)||dt(e.key,n.key)):(e,r)=>t*(Yh(e,n)-Yh(r,n))||dt(e.label,r.label)||dt(e.key,r.key)}function Zh(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 Qh({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:`${Wh} ${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 $h({projectName:e,profileId:t,runId:n,active:r}){let i=R({strict:!1}),a=ae(),o=i.seoRegion,s=i.seoMarket,c=Vh(i.seoShow),l=Cn.safeParse(i.seoSort).data??It.rank,u=t=>{a({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...t}),replace:!0})},d=(0,Z.useId)(),f=H(vo({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)(uh,{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)(ng,{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)(dh,{title:`No rankings here`,children:[`This refresh has no rankings for this `,s===void 0?`region`:`market`,`.`]}):(0,Q.jsx)(dh,{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=ar(m,p),b=c??(p.needsWork>0?tt[`needs-work`]:Bh),x=h.length>1||h.some(e=>e.kind===qn.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:eg(p)})]}),(0,Q.jsxs)(`dl`,{className:`grid grid-cols-2 gap-5 border-b border-subtle pb-5 ${Uh[y.length+1]??`sm:grid-cols-5`}`,children:[y.map(e=>(0,Q.jsx)(tg,{label:e.label,help:Kh(e,m),value:p[e.count]},e.count)),(0,Q.jsx)(tg,{label:`Rival ahead`,help:qh(m),value:p.rivalAhead,className:`sm:border-l sm:border-subtle sm:pl-5`})]})]}),x&&(0,Q.jsx)(rg,{projectName:e,groups:h,bands:y},`groups\u0000${g}`),(0,Q.jsx)(ig,{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===It.rank?void 0:e}),urlQ:i.seoQ??``,onQ:e=>u({seoQ:e||void 0}),onClear:()=>u({seoShow:Bh,seoQ:void 0})},`queries\u0000${g}`)]})}function eg(e){return[`${Rm.format(e.queries)} ${e.queries===1?`query`:`queries`}`,...e.partlyChecked>0?[`${Rm.format(e.partlyChecked)} partly checked`]:[],...e.failed>0?[`${Rm.format(e.failed)} failed`]:[],...e.cancelled>0?[`${Rm.format(e.cancelled)} not searched`]:[]].join(` · `)}function tg({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:Rm.format(n)})]})}function ng({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)(V,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoView:G[`market-rankings`],seoRegion:void 0,seoMarket:void 0}),className:Gh,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)(V,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoMarket:void 0}),className:Gh,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 rg({projectName:e,groups:t,bands:n}){let r=ae(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(1),c=Jh(t),l=(i===null?t:[...t].sort(Xh(i))).slice((o-1)*Rh,o*Rh),u=i??(n.some(e=>e.count===Hh.column)?Hh: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??Hh;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,m=e=>e.kind===qn.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)(Qh,{label:c.label,align:`left`,sorted:p(`label`),onSort:()=>f(`label`)}),d.map(e=>(0,Q.jsx)(Qh,{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:m(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)(V,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:m(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:Um,children:Rm.format(t.counts[e.column])},e.column)),(0,Q.jsx)(`td`,{className:`px-4 py-3 text-right align-top`,children:(0,Q.jsx)(h,{"aria-hidden":`true`,className:`ml-auto size-4 text-muted`})})]},`${t.kind}:${t.key}`))})]})}),(0,Q.jsx)(eu,{page:o,pageSize:Rh,visibleRows:l.length,totalRows:t.length,onPageChange:s,itemLabel:c.plural,className:`text-label-13 [&_button]:min-h-11`})]})}function ig({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=Zh(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=H({...Fa({client:Y,path:{name:e},query:{profileId:t,runId:n,regionKey:r,marketKey:i,outcome:c===Bh?void 0:c,q:v||void 0,sort:u,limit:zh,offset:(C-1)*zh}}),placeholderData:re}),T=[{value:tt[`needs-work`],label:`Needs work`,count:a.needsWork},...o.map(e=>({value:e.filter,label:e.label,count:a[e.count]})),{value:tt[`rival-ahead`],label:`Rival ahead`,count:a.rivalAhead},{value:tt[`partly-checked`],label:`Partly checked`,count:a.partlyChecked},{value:tt.failed,label:`Failed`,count:a.failed},{value:tt.cancelled,label:`Not searched`,count:a.cancelled},{value:Bh,label:`All`,count:a.queries}],E=[tt[`partly-checked`],tt.failed,tt.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===It.rank?`ascending`:u===It[`-rank`]?`descending`:null,A=u===It.query?`ascending`:u===It[`-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`:`${Rm.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:`${Hm} min-w-0 sm:w-56`,children:D.map(e=>(0,Q.jsxs)(`option`,{value:e.value,children:[e.label,` (`,Rm.format(e.count),`)`]},e.value))})]}),(0,Q.jsx)($l,{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)(uh,{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)(Qh,{label:`Query`,align:`left`,sorted:A,onSort:()=>d(u===It.query?It[`-query`]:It.query)}),(0,Q.jsx)(Qh,{label:`Google rank`,align:`right`,sorted:k,onSort:()=>d(u===It.rank?It[`-rank`]:It.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:`${Um} text-label-13-strong`,children:`Rival rank`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Rank gap`,(0,Q.jsx)(X,{text:Fm,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)(ag,{row:e,requested:s},`${e.marketKey}\u0000${e.queryId??e.queryText}\u0000${t}`))})]})}),(0,Q.jsx)(eu,{page:C,pageSize:zh,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 ag({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:Wm,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:Um,children:(0,Q.jsx)(sg,{row:e,requested:t})}),(0,Q.jsx)(`td`,{className:`px-4 py-3 align-top text-label-13`,children:(0,Q.jsx)(cg,{row:e})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.topCompetitor?.rankOrganic??null})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(jh,{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)(lg,{row:e,requested:t})})})]})}function og(e){return e.outcome===Ze.failed||e.outcome===Ze.cancelled}function sg({row:e,requested:t}){return e.outcome===Ze.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===Ze.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===Ze[`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 cg({row:e}){if(og(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 lg({row:e,requested:t}){let n=`text-muted`,r=`mt-0.5 text-primary`,i=e.outcome===Ze.failed?`No result: the search failed`:e.outcome===Ze.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:Gm}),(0,Q.jsx)(`p`,{className:`${r} tabular-nums`,children:(0,Q.jsx)(Xm,{value:e.rankAbsolute})})]}),e.searchStatus===Vt.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}`]})]}),!og(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)(ch,{source:e.provenance})})]})}function ug({projectName:e,profileId:t,canRun:n,selectedRunId:r,exactRefresh:i,onViewSaved:a,onLatest:o}){let s=L(),[c,l]=(0,Z.useState)(r??null),[u,d]=(0,Z.useState)(null),f={name:e},p=H({...ro({client:Y,path:f,query:{profileId:t}}),enabled:!i,refetchInterval:e=>e.state.data?.runs.some(Jm)?2e3:!1}),m=H({...Ea({client:Y,path:{...f,id:c??``}}),enabled:!!c,refetchInterval:e=>Jm(e.state.data)?2e3:!1}),h=oe({...ma({client:Y}),meta:{skipGlobalErrorToast:!0}}),g=async t=>{if(n&&!h.isPending){d(null);try{await h.mutateAsync({path:{...f,id:t}}),await li(s,`seo`,{projectName:e})}catch(e){d(Ss(e))}}},_=i?m:p;if(_.error)return(0,Q.jsx)(uh,{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)(dh,{title:`No refreshes yet`,children:`Refresh this profile to collect its first saved results.`});let y=m.data?.tasks.filter(rh)??[];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:Fn(e.createdAt,Bm)}),(0,Q.jsx)(Zm,{status:e.status})]}),(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[e.completedTasks,` of `,e.taskCount,` `,nh(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&&Jm(e)&&(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,disabled:h.isPending||e.cancelRequested,onClick:si(()=>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,` · `,eh(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)(uh,{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:[Nm[e.capability],e.searchText===null?e.target?` · ${e.target.value}`:``:` · “${e.searchText}” from ${e.locationLabel??`its market`}`,e.comparison?` · ${e.comparison.competitor.value} · ${Pm[e.comparison.mode]} searches`:``,e.retried?` · retried once`:``]}),(0,Q.jsx)(Zm,{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…`}),Ym(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 dg({projectName:e,context:t,profile:n,id:r,onClose:i,onSaved:a}){let o=L(),s=G[`market-rankings`],c=(e,t)=>fh(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===ft.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??``}`:`${ft.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=G[`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:Ce.domain,value:``,includeSubdomains:!0}]),[E,D]=(0,Z.useState)(n?.competitors?.map(e=>e.value).join(`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./react-sigma_core.esm.min-DWNI6FGP.js","./rolldown-runtime-XKyaHtl9.js","./vendor-lucide-7AWeFVeL.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,H as s,I as c,L as l,P as u,Q as d,T as f,V as p,Y as m,Z as h,a as g,at as _,b as v,c as y,et as b,g as x,h as S,i as C,lt as w,n as T,p as E,s as D,st as O,t as k,ut as A,v as j,w as M}from"./vendor-lucide-7AWeFVeL.js";import{a as N,i as P,o as ee,r as te,s as ne,t as F}from"./vendor-radix-WbUsEVSn.js";import{r as I}from"./vendor-markdown-CQdHmjWd.js";import{O as L,T as re,_ as ie,d as ae,f as R,p as z,r as B,u as V,v as oe,x as H}from"./vendor-tanstack-C613NhXZ.js";import{a as se,c as ce,d as le,f as ue,h as de,i as fe,l as pe,m as me,n as he,o as ge,p as _e,r as ve,s as ye,t as be,u as xe}from"./vendor-recharts-DCxaNd0O.js";import{$c as Se,$o as Ce,$s as U,$t as we,At as Te,B as Ee,Bc as De,Bo as Oe,Bs as ke,Cc as Ae,Co as W,Cs as je,Ct as Me,Dc as Ne,Do as Pe,Ec as Fe,Eo as Ie,Et as Le,Fc as Re,Fo as ze,Ft as Be,Gn as Ve,Go as He,Gs as Ue,Gt as We,H as Ge,Hc as Ke,Hn as qe,Ho as G,I as Je,Io as Ye,Jc as Xe,Jo as Ze,Js as Qe,Jt as $e,Kc as et,Ko as tt,Ks as nt,Kt as rt,Lc as it,Nc as at,Nt as ot,Oc as st,Oo as ct,P as lt,Pc as ut,Qc as dt,Qo as ft,Qs as pt,Qt as mt,R as ht,Rn as gt,Rt as _t,Sc as vt,Sn as yt,So as bt,Ss as xt,St,Tc as Ct,To as wt,Uc as Tt,Un as Et,Uo as Dt,Ut as Ot,V as kt,Vc as At,Vo as jt,Wo as Mt,Ws as Nt,Wt as Pt,Xa as Ft,Xo as It,Xs as Lt,Y as Rt,Ya as zt,Yc as Bt,Yo as Vt,Ys as Ht,Z as Ut,Zc as Wt,Zo as Gt,Zs as Kt,Zt as qt,_ as Jt,_s as Yt,_t as Xt,a as Zt,ac as Qt,as as $t,bn as en,bo as tn,bs as nn,c as rn,cc as an,cl as on,cs as sn,d as cn,dc as ln,dt as un,ec as dn,el as fn,en as pn,es as mn,fc as hn,fs as gn,g as _n,gs as vn,gt as yn,h as bn,hc as xn,hs as Sn,is as Cn,jn as wn,jt as K,kc as Tn,ko as En,kt as Dn,l as On,lc as kn,ls as An,lt as jn,m as Mn,mn as Nn,ms as Pn,nc as Fn,nl as In,nn as Ln,ns as Rn,o as zn,oc as Bn,ol as Vn,os as Hn,p as Un,ps as Wn,pt as Gn,q as Kn,qo as qn,qs as Jn,qt as Yn,r as q,rs as Xn,s as Zn,sl as Qn,t as J,tc as $n,tl as er,ts as tr,tt as nr,u as rr,uc as ir,uo as ar,us as or,ut as sr,vc as cr,vn as lr,vs as ur,vt as dr,w as fr,wo as pr,ws as mr,wt as hr,xc as gr,xn as _r,xo as vr,xs as yr,xt as Y,yn as br,ys as xr,zc as Sr}from"./ToneBadge-CViol5aK.js";import{t as Cr}from"./preload-helper-DzM601DW.js";import{B as wr,C as Tr,D as Er,F as Dr,I as Or,L as kr,M as Ar,N as jr,O as Mr,P as Nr,R as Pr,S as Fr,T as Ir,_ as Lr,a as Rr,b as zr,c as Br,d as Vr,f as Hr,g as Ur,h as Wr,i as Gr,j as Kr,k as qr,l as Jr,m as Yr,n as Xr,o as Zr,p as Qr,r as $r,s as ei,t as ti,u as ni,x as ri,y as ii,z as ai}from"./ChartPrimitives-DBTchs1y.js";import{r as oi}from"./account-context-B1G3xhE1.js";import{t as si}from"./async-handler-Bj3TnIRw.js";import{d as ci,l as li,n as ui,o as di,s as fi,t as pi,u as mi}from"./query-client-3W7wQep0.js";import{$ as hi,$t as gi,A as _i,An as vi,At as yi,B as bi,Bn as xi,Bt as Si,C as Ci,Ct as wi,D as Ti,Dt as Ei,E as Di,F as Oi,Fn as ki,Ft as Ai,G as ji,Gn as Mi,Gt as Ni,H as Pi,Hn as Fi,Ht as Ii,I as Li,In as Ri,It as zi,J as Bi,Jn as Vi,Jt as Hi,K as Ui,Kn as Wi,Kt as Gi,L as Ki,Ln as qi,M as Ji,Mn as Yi,N as Xi,Nn as Zi,Nt as Qi,O as $i,P as ea,Pn as ta,Pt as na,Q as ra,Qt as ia,R as aa,Rn as oa,Rt as sa,S as ca,St as la,T as ua,Tn as da,U as fa,V as pa,Vn as ma,Vt as ha,W as ga,Wn as _a,X as va,Xt as ya,Y as ba,Yt as xa,Z as Sa,Zt as Ca,_ as wa,_t as Ta,an as Ea,at as Da,b as Oa,bn as ka,c as Aa,ct as ja,d as Ma,dn as Na,dt as Pa,en as Fa,et as Ia,f as La,fn as Ra,ft as za,g as Ba,gt as Va,h as Ha,ht as Ua,in as Wa,it as Ga,j as Ka,jn as qa,jt as Ja,k as Ya,kn as Xa,lt as Za,m as Qa,mt as $a,n as eo,nn as to,nt as no,on as ro,ot as io,p as ao,pn as oo,pt as so,q as co,qn as lo,qt as uo,r as fo,rn as po,rt as mo,sn as ho,st as go,t as _o,tn as vo,tt as yo,un as bo,ut as xo,v as So,vn as Co,vt as wo,w as To,wn as Eo,wt as Do,x as Oo,xt as ko,y as Ao,yn as jo,yt as Mo,z as No,zn as Po,zt as Fo}from"./react-query-B0EpSPOn.js";import{A as Io,B as Lo,C as Ro,D as zo,E as Bo,F as Vo,I as Ho,L as Uo,M as Wo,N as Go,O as Ko,P as qo,R as Jo,S as Yo,T as Xo,V as Zo,_ as Qo,a as $o,b as es,c as ts,d as ns,f as rs,g as is,h as as,i as os,j as ss,k as cs,l as ls,m as us,n as ds,o as fs,p as ps,r as ms,s as hs,u as gs,v as _s,w as vs,x as ys,y as bs,z as xs}from"./AccessControls-Dw14Y8Zb.js";import{n as Ss,t as Cs}from"./extract-error-message-C1RkZ7dQ.js";import{t as X}from"./InfoTooltip-laRfQjZw.js";import{t as ws}from"./card-B8kjwkFR.js";import{$ as Ts,A as Es,At as Ds,B as Os,C as ks,Ct as As,D as js,Dt as Ms,E as Ns,Et as Ps,F as Fs,G as Is,H as Ls,I as Rs,J as zs,K as Bs,L as Vs,Mt as Hs,N as Us,Nt as Ws,O as Gs,Ot as Ks,P as qs,Q as Js,R as Ys,S 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,yt as Bc,z as Vc}from"./index-DxNmD1SS.js";import{t as Hc}from"./Hint-DiyoPGOX.js";import{t as Uc}from"./AuditHistoryPanel-C06iViSe.js";import{a as Wc,i as Gc,l as Kc,n as qc,o as Jc,r as Yc,t as Xc,u as Zc}from"./service-Cy2ZA98R.js";import{a as Qc,c as $c,s as el,t as tl}from"./server-traffic-D6FWsQIv.js";import{i as nl,n as rl,r as il}from"./agent-trust-copy-CMgWNJn0.js";import{t as al}from"./ServerTrafficSection-CBCczz52.js";function ol(e){return e.split(/[?#]/)[0]||`/`}var sl=1e6;function cl(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/sl);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(A(),1),ll={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 ul(e,t){return e!==`viewer`||t!==null}function dl(e,t){return e===`research`&&!t?`tracked`:e}function fl(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 pl(e,t){return e.find(e=>e.kind===t.measurementScope&&(e.kind===`project`||e.id===t.measurementScopeKey))}function ml(e){return e.measurementScope!==`project`||e.marketKey!==void 0}function hl(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=I();function gl({state:e,label:t,className:n}){return(0,Q.jsx)(J,{tone:Bc(e),className:n,children:t??(e===`not-measured`?kr.label:Or(e))})}function _l({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 vl=[{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],yl={"non-brand":`Non-brand`,branded:`Branded`,pooled:`All queries`},bl={"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.`},xl=`Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.`;function Sl(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:U(e.score,et.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 Cl({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:xl})]}),(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:U(e.share)})]},e.label))})]})}function wl({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=Sl(u,{hasCompetitors:n.length>0,unavailable:e.unavailable===!0,noRun:e.breakdown.snapshotsTotal===0&&e.branded.snapshotsTotal===0,otherClassHasData:d.snapshotsTotal>0}),p=Nr(f.headline),m=l===`non-brand`?oc[e.tone]:`text-secondary`;function h(e){let t=vl.findIndex(e=>e.value===c),n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%vl.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+vl.length)%vl.length:e.key===`Home`?n=0:e.key===`End`&&(n=vl.length-1),n!==null&&(e.preventDefault(),i(vl[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:bl[l]})]}),s?(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":a,className:`segmented flex-wrap`,onKeyDown:h,children:vl.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:yl[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:yl[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)(Cl,{breakdown:u,projectLabel:t})]})}function Tl({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 El=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],Dl={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,all:`all checks`},Ol={"non-brand":`Non-brand`,branded:`Branded`,all:`All queries`},kl={"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.`},Al={"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`},jl=`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.`,Ml=100;function Nl(e){return e?e.evidence.answeredResults>0||e.evidence.sourceResults>0?`measured`:`not-measured`:`unavailable`}function Pl(e){return e===`unavailable`?`Unavailable`:`Not measured`}function Fl(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 Il(e,t,n){return e===1?t:n}function Ll(e){let t=e.label.trim(),n=Xe(e.domain);return t&&t.toLowerCase()!==e.domain.toLowerCase()&&t.toLowerCase()!==n.toLowerCase()?t:null}function Rl({row:e,aliases:t=[],autoAliases:n=[]}){let r=Ll(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 zl(e){let t=Ll(e);return t?`${t} (${e.domain})`:e.domain}function Bl(e,t){return t&&e>=Ml?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:e})}function Vl({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 Hl({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 Ul({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:Pl(n)})}function Wl({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`:Pl(t)});let{figure:r,sign:i}=Nr(U(e,et.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 Gl({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)(Rl,{row:e})}),(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:Fl(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{count:e.mentionCount,of:n,state:t,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{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)(Hl,{urls:e.sampleUrls}):null,i?(0,Q.jsx)(Vl,{action:`pin`,domain:e.domain,mutation:i}):null]})})]},e.domain))})]})})}function Kl({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 ql({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=Nl(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)(Vl,{action:`unpin`,domain:e.domain,mutation:l}):null:c?(0,Q.jsx)(Vl,{action:`pin`,domain:e.domain,mutation:c}):null:null,N=w.some(e=>M(e)!==null),P=[m,E?Ol[E]:null,Dl[e],t?.basis?C?`observed competitors only`:`tracked competitors only`:null].filter(Boolean).join(` · `),ee=[];if(t&&!C&&w.length===0&&ee.push({key:`no-pins`,text:`No pinned competitors.`}),t?.reason&&ee.push({key:`reason`,text:`Mention share: ${Al[t.reason]}`}),t&&T.length>0){let e=T.length;ee.push({key:`others`,text:O&&e>=Ml?`${Ml} or more other competitors seen`:`${e} other ${Il(e,`competitor`,`competitors`)} seen`})}D>0&&ee.push({key:`pending`,text:`${t?.scope.kind===`all-markets`?`Pending publication across markets`:`Pending publication`}: ${D} ${Il(D,`competitor`,`competitors`)}`});let te=[x&&x.missingAnswerTextResults>0?`Answer data incomplete`:null,x&&x.incompleteSourceResults>0?`Citation data incomplete`:null].filter(Boolean);te.length>0&&ee.push({key:`incomplete`,text:te.join(` · `),className:oc.caution});let ne=[];if(t&&x){ne.push(t.runCount===void 0?(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,Il(x.answeredResults,`answer`,`answers`)]}):(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:t.runCount}),` `,Il(t.runCount,`check`,`checks`),`, `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,Il(x.answeredResults,`answer`,`answers`)]})),!t.reason&&S===`measured`&&t.project.shareOfVoice!==null&&ne.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`]})),ne.push((0,Q.jsxs)(Q.Fragment,{children:[`Answers with source links: `,(0,Q.jsx)(`strong`,{children:x.sourceResults})]})),T.length===0&&ne.push(`Other competitors seen: none`),x.missingAnswerTextResults>0&&ne.push((0,Q.jsxs)(Q.Fragment,{children:[`No answer text: `,(0,Q.jsx)(`strong`,{children:x.missingAnswerTextResults}),` `,Il(x.missingAnswerTextResults,`answer`,`answers`),`, left out of mention share`]})),x.incompleteSourceResults>0&&ne.push((0,Q.jsxs)(Q.Fragment,{children:[`Incomplete source lists: `,(0,Q.jsx)(`strong`,{children:x.incompleteSourceResults}),` `,Il(x.incompleteSourceResults,`answer`,`answers`),`, not counted as misses`]}));let e=x.excludedProbeResults+x.excludedNonCompletedResults;e>0&&ne.push((0,Q.jsxs)(Q.Fragment,{children:[`Left out: `,(0,Q.jsx)(`strong`,{children:e}),` `,Il(e,`answer`,`answers`),` from spot checks or unfinished checks`]}))}let F=[...t?[{name:`You`,row:t.project}]:[],...w.map(e=>({name:e.domain,row:e}))].filter(e=>e.row.sampleUrls.length>0);S===`measured`&&F.length>0&&ne.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:F.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&&ne.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other competitors seen: `,Bl(T.length,O)]}),(0,Q.jsx)(`div`,{className:`av-subdetails-body`,children:(0,Q.jsx)(Gl,{rows:T,state:S,named:k,cited:A,onPin:_?c:void 0})})]}));let I=t?.observedNames??[];if(I.length>0){let e=t?.observedNamesTotal??I.length;ne.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Company names in answers: `,e>I.length?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:I.length}),` of `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:I.length})]}),(0,Q.jsx)(`ul`,{className:`av-subdetails-body`,children:I.map(e=>(0,Q.jsxs)(`li`,{children:[e.name,` · `,e.answerCount,` `,Il(e.answerCount,`answer`,`answers`)]},e.name))})]}))}return b.length>0&&ne.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other sites cited: `,Bl(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:[zl(e),` · `,Fl(e.surfaceClass),` · `,e.citationCount,` `,Il(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?`${kl[E]} ${jl}`:jl})]}),(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)(As,{label:`Competitors over time window`,className:`flex-wrap`,options:El,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)(Wl,{percent:t.project.shareOfVoice,state:S,toneClass:j})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{count:t.project.mentionCount,of:k,state:S,toneClass:j})}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(Ul,{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:jr(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)(Rl,{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:Fl(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wl,{percent:e.shareOfVoice,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{count:e.mentionCount,of:k,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Ul,{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,ee.length>0?(0,Q.jsx)(`div`,{className:`space-y-1 text-label-13 text-secondary`,children:ee.map(e=>(0,Q.jsx)(`p`,{className:e.className,children:e.text},e.key))}):null]}),(0,Q.jsx)(Tl,{items:ne}),_&&u?(0,Q.jsx)(`div`,{className:`border-t border-subtle px-5 py-3`,children:(0,Q.jsx)(Kl,{onAddCompetitor:u})}):null]})}function Jl(e){return e.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function Yl(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 Xl(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 Zl({value:e,headLength:t,tailLength:n,className:r,title:i}){let a=Xl(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 Ql({rows:e,getSearchText:t,pageSize:n=25}){let[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(1),s=(0,Z.useMemo)(()=>Jl(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 $l({value:e,onChange:t,label:n,placeholder:r=`Filter rows`,className:i}){return(0,Q.jsxs)(`div`,{className:`relative ${i??``}`,children:[(0,Q.jsx)(S,{"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=>{Ve(e.target.value),t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&Ve(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 eu({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,f=r===void 0?void 0:Math.max(1,Math.ceil(r/t)),p=i??(f!==void 0&&e<f),m=e>1||p;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?`${p?`+`:``} ${o}`:` of ${r.toLocaleString(`en-US`)} ${o}`]}),m?(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)(d,{"aria-hidden":`true`,className:`size-3.5`}),`Previous`]}),(0,Q.jsx)(`span`,{className:`tabular-nums`,children:f===void 0?`Page ${e}`:`Page ${e} of ${f}`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>a(e+1),disabled:c||!p,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)(h,{"aria-hidden":`true`,className:`size-3.5`})]})]}):null]})}function tu({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":kr.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(`/`)?Re(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(`/`)?Re(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 nu(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 ru(e){let t=e.filter(e=>e!==`pending`);if(t.length===0)return`pending`;let n=ze(t.map(iu));return n===cr.cited?t.includes(`cited`)?`cited`:`emerging`:n===cr[`not-cited`]?t.includes(`lost`)?`lost`:`not-cited`:`not-measured`}function iu(e){switch(e){case`cited`:case`emerging`:return cr.cited;case`not-cited`:case`lost`:return cr[`not-cited`];case`not-measured`:return cr[`not-measured`]}}var au=320;function ou(e){return e===`branded`?`Branded`:e===`non-brand`?`Non-brand`:`Unclassified`}function su(e){return e===`non-brand`?0:e===`branded`?1:2}function cu(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 lu(e){return e.phrase}function uu(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 du(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 kr.label;case`lost`:return`Lost`;case`emerging`:return`Emerging`;case`pending`:return`Pending`}}function fu(e,t){return e.map(e=>pu(e,t))}function pu(e,t){return t===`citations`?e:{...e,citationState:uu(e,t),runHistory:e.runHistory.map(e=>({...e,citationState:uu(e,t)}))}}function mu(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:kr.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 hu(e){let t=nu(fu(e,`mentions`)),n=nu(e);return[mu(t,`mentions`),mu(n,`citations`)]}function gu({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 _u({items:e}){return(0,Q.jsx)(`div`,{className:`query-evidence-signals`,"aria-label":`Latest run mention and citation signals`,children:hu(e).map(e=>(0,Q.jsx)(gu,{signal:e},e.key))})}function vu({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)(qs,{}),t]})}):null,e?(0,Q.jsx)(Fs,{queryClass:e,manage:!!t}):null]})}function yu({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=Ys(),[p,m]=(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(pu(r,p)),s.rawItems.push(r),n.set(o,s)}return[...n.values()].sort((e,t)=>su(e.queryClass)-su(t.queryClass))},[e,p,t,S]),E=Ql({rows:(0,Z.useMemo)(()=>T.filter(e=>v===`all`||(v===`unclassified`?e.queryClass===null:e.queryClass===v)),[T,v]),getSearchText:lu}),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(Ye)),[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`,ee=p===`mentions`?`mentioned`:`cited`;return(0,Q.jsxs)(`div`,{className:`query-evidence`,children:[(0,Q.jsx)(vu,{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:()=>m(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`;m(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)($l,{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:Bo(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`})})]})}),cu(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:[ou(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),m=`${l}-query-${d}`,_=O.has(Ye(n)),v=ru(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=nu(a),S=a.filter(e=>e.citationState===cr.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 ${ee}${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":m,"aria-expanded":s,onClick:t=>{t.stopPropagation(),M(e)},children:[(0,Q.jsx)(h,{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:m,className:`query-evidence-meta`,children:[(0,Q.jsx)(`span`,{children:ou(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)(gl,{state:v,label:du(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)(Rs,{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)(tu,{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)(_u,{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?Bo(e.provider):`Awaiting engine`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(gl,{state:e.citationState,className:`rounded-none border-0 bg-transparent p-0 text-label-14`,label:du(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)(tu,{history:e.runHistory,signal:p})}),(0,Q.jsx)(`td`,{className:`evidence-change-cell`,children:_?null:(0,Q.jsx)(_u,{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?Bo(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)(Su,{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)(eu,{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 bu(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 xu(e,t){let n=t.toLowerCase().replace(/^www\./,``);return(e.citedCompetitorDomains??[]).some(e=>e.toLowerCase().replace(/^www\./,``)===n)}function Su({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)(Cu,{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:kr.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}),xu(e,Bt(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,xu(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)(Cu,{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 Cu({item:e,onViewFull:t,contextOnly:n=!1}){let{matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}=e,s=(0,Z.useMemo)(()=>bu({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>au;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:au,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,xu(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 wu({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&&Et(`window`),n(e)},children:i?i(e):e},e))})}var Tu=[``,`sm:grid-cols-1`,`sm:grid-cols-2`,`sm:grid-cols-3`],Eu=[``,`lg:grid-cols-1`,`lg:grid-cols-2`,`lg:grid-cols-3`,`lg:grid-cols-4`,`lg:grid-cols-5`,`lg:grid-cols-6`],Du=14,Ou=Rr[1],ku={current:`current`,previous:`previous`},Au=e=>e.series?.filter(e=>e.current!==null).length??0,ju=e=>e.interactive??Au(e)>=2,Mu=e=>e!=null;function Nu(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Pu(e){if(!e)return``;if(e.kind===`note`)return Nu(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 Fu({date:e,observedAt:t}){return t?Qr(Wr(t)):ni(e)}function Iu({date:e,observedAt:t}){return t?Ur(Wr(t)):Number(e.slice(0,4))}function Lu(e){return e.label??Fu(e)}function Ru(e,t){if(!e)return;let n=`since ${Lu(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`?`${dn(r).magnitude} pts`:r.toLocaleString(),direction:e.difference>0?`up`:`down`,tone:e.tone,basis:n}}function zu(e){let t=new Set(e.map(e=>e.change?Lu(e.change.basis):null)),[n]=[...t];return t.size===1&&n?`since ${n}`:void 0}function Bu(e){return e.series.map(e=>({date:e.observedAt??e.date,current:e.value,...e.label?{label:e.label}:{}}))}function Vu(e,t){if(e.label&&t.label)return e.label===t.label?e.label:`${e.label} to ${t.label}`;let n=(e,t)=>t?`${Fu(e)}, ${Iu(e)}`:Fu(e);return`${n(e,Iu(e)!==Iu(t))} to ${n(t,!0)}`}function Hu({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`?_:w,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 Uu({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 Wu(e,t){return e.formatExact?.(t)??e.formatValue?.(t)??t.toLocaleString()}function Gu({active:e,payload:t,figure:n,previousLabel:r,rowLabel:i}){let a=t?.[0]?.payload;if(!e||!a)return null;let o=e=>Mu(e)?Wu(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?Jr(a.previousDate):r}),(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:o(a.previous)})]})]})}function Ku({name:e,groups:t,mode:n=`single`,selected:i,onSelect:a,span:o,cadence:s=`day`,instants:c=!1,currentLabel:l,previous:u,chart:d,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=>c?Hr(Wr(e)):Jr(e),E=e=>e.label??T(e.date),D=e=>Yr(Wr(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===i[0]&&ju(e)):void 0,ee=P?.series??[],te=c?ee.map(e=>({...e,at:Date.parse(e.date)})):ee,ne=new Map(ee.flatMap(e=>e.label?[[e.date,e.label]]:[])),F=!!u?.available&&ee.some(e=>Mu(e.previous)),I=ee.some(e=>e.current!==null||F&&Mu(e.previous)),L=x<=1||Au(P??{key:``,label:``,value:``})>=x,re=!F||!O.has(ku.current),ie=F&&!O.has(ku.previous),ae=Au(P??{key:``,label:``,value:``})<Du?`linear`:`monotone`,R=`per ${s}`,z=l?Nu(l):o,B=P?`${P.label} ${R}${z?`, ${z}`:``}${F?` and the previous period`:``}`:``,V=N.filter(ju).map(e=>e.key),oe=V.includes(i[0]??``)?i[0]:V[0],H=e=>{a(e),document.getElementById(`${w}-tab-${e}`)?.focus()},se=(e,t)=>{let n=V.indexOf(t),r=V.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(),H(V[i]))},le=e=>k(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),ue=(e,t,o)=>{let s=ju(e),c=s&&i.includes(e.key),l=!!t.basis,u=[`${e.label} ${e.spokenValue??e.value}${e.detail?` ${e.detail}`:``}`,Pu(e.change)].filter(Boolean).join(`, `),d=(0,Q.jsxs)(`div`,{className:`flex min-h-5 items-center gap-1.5`,children:[n===`compare`&&s&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2.5 shrink-0 rounded-full`,style:{backgroundColor:c?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 ${c?`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)(r,{"aria-hidden":`true`,className:`pointer-events-none absolute right-0 size-3.5 ${c?`text-link`:`text-muted`}`})]}):(0,Q.jsx)(`span`,{className:`${b?`text-label-12 sm:text-label-14-strong`:`text-label-14-strong`} ${c?n===`single`?`text-link`:`text-heading`:`text-secondary`}`,children:e.label}),e.help&&(0,Q.jsx)(X,{text:e.help})]});return o?(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 ${c&&n===`single`?`bg-surface-active`:s?`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 ${c?`opacity-100`:`opacity-0`}`}),d,(0,Q.jsxs)(`button`,{type:`button`,id:`${w}-tab-${e.key}`,...n===`single`?{role:`tab`,"aria-selected":c,"aria-controls":`${w}-panel`,"aria-disabled":!s||void 0,tabIndex:s&&e.key===oe?0:-1,onKeyDown:t=>se(t,e.key)}:{"aria-pressed":c},"aria-label":u,disabled:n===`compare`&&(e.disabled||!s),onClick:s?()=>a(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 ${s?``:`cursor-default`} ${e.disabled?`disabled:cursor-not-allowed disabled:opacity-50`:``}`,children:[(0,Q.jsx)(Uu,{figure:e,active:c,compact:b}),(0,Q.jsx)(Hu,{change:e.change,hideBasis:l})]})]},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:d}),(0,Q.jsxs)(`dd`,{className:`mt-auto pt-1`,children:[(0,Q.jsx)(Uu,{figure:e,active:!1,compact:b}),(0,Q.jsx)(Hu,{change:e.change,hideBasis:l}),e.change&&(0,Q.jsx)(`span`,{className:`sr-only`,children:Pu(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(ju),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`} ${Tu[Math.min(t.figures.length,3)]} ${Eu[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=>ue(e,t,!0))}):(0,Q.jsx)(`dl`,{className:o,children:t.figures.map(e=>ue(e,t,!1))})]},t.key)})}),(0,Q.jsxs)(`div`,{id:`${w}-panel`,...n===`single`&&P&&V.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`?d:!P||!I||!L?(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":B,style:{height:_},children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:[...te],margin:{top:8,right:0,bottom:0,left:4},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),c?(0,Q.jsx)(fe,{dataKey:`at`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:D,minTickGap:32,padding:{left:12,right:12}}):(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:e=>ne.get(e)??Vr(e),minTickGap:32,padding:ne.size>0?{left:40,right:40}:{left:12,right:12}}),(0,Q.jsx)(ve,{orientation:`right`,reversed:P.reverseValueAxis,domain:P.reverseValueAxis?[1,`auto`]:void 0,tick:Xr,tickLine:!1,axisLine:!1,width:52,allowDecimals:P.allowDecimals??!1,tickFormatter:e=>P.formatValue?.(e)??e.toLocaleString()}),(0,Q.jsx)(_e,{cursor:{stroke:Gr.textFaint,strokeWidth:1},wrapperStyle:{outline:`none`},content:(0,Q.jsx)(Gu,{figure:P,previousLabel:F?u?.label:void 0,rowLabel:E})}),ie&&(0,Q.jsx)(ye,{type:ae,dataKey:ku.previous,stroke:Ou,strokeOpacity:.65,strokeWidth:1.5,strokeDasharray:`4 4`,dot:!1,activeDot:{r:3,strokeWidth:0,fill:Ou},connectNulls:!1,isAnimationActive:M,animationDuration:320,animationEasing:`ease-out`}),re&&(0,Q.jsx)(ye,{type:ae,dataKey:ku.current,stroke:Ou,strokeWidth:2.25,dot:ae===`linear`&&{r:3,strokeWidth:0,fill:Ou},activeDot:{r:5,strokeWidth:2,stroke:Ou,fill:`var(--color-bg)`},connectNulls:!1,isAnimationActive:M,animationDuration:320,animationEasing:`ease-out`})]})})}),n===`single`&&P&&I&&(l||y)||f||o&&!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&&I&&(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`}),(F||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&&I&&l&&u&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(qu,{label:l,checked:re,disabled:!F||re&&!ie,onChange:()=>le(ku.current),dash:void 0}),(0,Q.jsx)(qu,{label:F?u.label:`${u.label}: no earlier data`,checked:ie,disabled:!F||ie&&!re,onChange:()=>le(ku.previous),dash:`4 3`})]}),f]}),(0,Q.jsxs)(`div`,{className:`ml-auto flex flex-wrap items-center gap-x-4 gap-y-1`,children:[o&&!S&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:o}),p]})]}):null,n===`single`&&P&&I&&(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:B}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:ee.some(e=>e.label)?`Release`:`Date`}),(0,Q.jsx)(`th`,{scope:`col`,children:P.label}),F&&(0,Q.jsx)(`th`,{scope:`col`,children:u.label})]})}),(0,Q.jsx)(`tbody`,{children:ee.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`:Wu(P,e.current)}),F&&(0,Q.jsx)(`td`,{children:Mu(e.previous)?Wu(P,e.previous):`No data`})]},e.date))})]})})]})]})}function qu({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:Ou,strokeWidth:i?1.5:2.5,strokeDasharray:i})}),e]})}var Ju=`baseline`;function Yu(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,[Ju]:i.get(e)??null};for(let e of n)a[e.dataKey]=t?.[e.key]??0;return a}),series:n}}var Xu=`text-label-12-strong normal-case text-muted`;function Zu({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 Qu({children:e}){return(0,Q.jsx)(`div`,{className:`[&>details:first-child]:border-t-0`,children:e})}function $u({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 ed={3:`lg:grid-cols-3`,4:`lg:grid-cols-4`,5:`lg:grid-cols-5`};function td({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 ${ed[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 nd({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:`${Xu} 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 rd({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:Xu,children:e}),(0,Q.jsx)(X,{text:n})]}):(0,Q.jsx)(`span`,{className:Xu,children:e})})}function id(e,t,n=`desc`){return e.key===t?{key:t,dir:e.dir===`desc`?`asc`:`desc`}:{key:t,dir:n}}function ad(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 od(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 sd({groups:e,groupLabel:t,caption:n,childColumns:i,childRowKey:a,renderChildCells:o,pinLast:s,extraColumns:c=[],defaultSort:l,referenceRow:u}){let d=(0,Z.useId)(),[f,p]=(0,Z.useState)(new Set),[m,g]=(0,Z.useState)(l??{key:`sessions`,dir:`desc`}),_=(0,Z.useMemo)(()=>{let t=c.find(e=>e.key===m.key),n=t?.sortValue?od(t.sortValue,m.dir):ad(m.key,m.dir);return[...e].sort((e,t)=>Number(s?.(e)??!1)-Number(s?.(t)??!1)||n(e,t))},[e,m,s,c]),v=e=>g(t=>id(t,e,c.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 ${c.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)(nd,{label:t,sortKey:`label`,current:m.key,dir:m.dir,onSort:v,align:`left`}),(0,Q.jsx)(nd,{label:`Sessions`,sortKey:`sessions`,current:m.key,dir:m.dir,onSort:v,align:`right`}),(0,Q.jsx)(nd,{label:`Organic`,sortKey:`organicSessions`,current:m.key,dir:m.dir,onSort:v,align:`right`}),(0,Q.jsx)(nd,{label:`Paid`,sortKey:`paidSessions`,current:m.key,dir:m.dir,onSort:v,align:`right`}),(0,Q.jsx)(rd,{label:`Share`,align:`right`}),c.map(e=>e.sortValue?(0,Q.jsx)(nd,{label:e.label,sortKey:e.key,current:m.key,dir:m.dir,onSort:v,align:`right`,help:e.help},e.key):(0,Q.jsx)(rd,{label:e.label,align:`right`,help:e.help},e.key))]})}),(0,Q.jsxs)(`tbody`,{children:[u,_.map((e,t)=>{let n=f.has(e.label),s=`${d}-group-${t}`,l=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?s: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)(r,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-secondary`}):(0,Q.jsx)(h,{"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:[l,` `,l===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:U(e.share)}),c.map(t=>(0,Q.jsx)(Z.Fragment,{children:t.render(e)},t.key))]}),n&&(0,Q.jsx)(`tr`,{id:s,children:(0,Q.jsx)(`td`,{colSpan:5+c.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:i.map(e=>(0,Q.jsx)(rd,{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:o(e)},a(e)))})]})})})})]},e.label)})]})]})})}function cd(e,t){return e===`other`?Gr.textDim:Rr[t%Rr.length]}function ld({input:e,baseline:t,baselineLabel:n,label:r,height:i=224}){let{rows:a,series:o}=(0,Z.useMemo)(()=>Yu(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)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:a,margin:{top:4,right:4,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:Vr,minTickGap:24}),(0,Q.jsx)(ve,{tick:Xr,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(_e,{...ei,labelFormatter:Jr,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=cd(e.key,o.indexOf(e));return(0,Q.jsx)(ge,{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)(ye,{type:`monotone`,dataKey:`baseline`,name:`baseline`,stroke:Gr.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:cd(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:Gr.textFaint,strokeWidth:`2`,strokeDasharray:`5 3`})}),n]})]})]})}var ud=[`sessions`,`activeUsers`,`organicSessions`,`engagementRate`,`keyEvents`],dd=`canonry.siteTraffic.slots`;function fd(e){return typeof e==`string`&&Wn.some(t=>t===e)}function pd(){try{let e=JSON.parse(window.localStorage.getItem(dd)??`null`);if(Array.isArray(e)&&e.length===ud.length&&e.every(fd))return[...e]}catch{}return[...ud]}function md(e){try{window.localStorage.setItem(dd,JSON.stringify(e))}catch{}}function hd(e,t,n){let r=yr(e,t);return r===null||t===null?{kind:`note`,text:`No earlier data`}:{kind:`delta`,amount:U(Math.abs(t),et.percent),direction:t>0?`up`:t<0?`down`:`flat`,tone:r===ur.better?`better`:r===ur.worse?`worse`:`neutral`,basis:n}}function gd({overview:e,refreshing:t=!1}){let[n,r]=(0,Z.useState)(pd),[i,a]=(0,Z.useState)(0),o=mr(e.window)?Sn[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,md(r),r}),u=n.map((t,n)=>({key:t,slot:`slot-${n}`,label:gn[t].label,value:nn(t,e.totals[t],{compact:!0}),exactValue:nn(t,e.totals[t]),change:hd(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:Wn.map(e=>({value:e,label:gn[e].label})),onChange:e=>{fd(e)&&l(n,e)}},formatValue:e=>nn(t,e,{compact:!0}),formatExact:e=>nn(t,e),allowDecimals:gn[t].unit!==xr.count})),d=n[i]??ud[0],f=e.current.startDate&&e.current.endDate&&e.previous.startDate&&e.previous.endDate?`${_d(e.current.startDate,e.current.endDate,!0)} vs ${_d(e.previous.startDate,e.previous.endDate,!1)}`:void 0;return(0,Q.jsx)(Ku,{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 ${gn[d].label.toLowerCase()} yet.`,refreshing:t})}function _d(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 vd(e){return e?Jr(e.slice(0,10)):`—`}function yd({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 bd({rows:e,expanded:t,loading:n,onToggle:i,actions:a,lastReadLabel:o,empty:s}){let c=a?6:5,l=(e,o)=>{let s=t.has(e.url),c=n?.has(e.url)??!1;return(0,Q.jsxs)(`tr`,{className:`group`,children:[(0,Q.jsx)(`td`,{className:`max-w-md ${o?`pl-9`:``}`,children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[e.isIndex&&!o&&(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-label":`${s?`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:()=>i(e.url),children:s?(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,Q.jsx)(Zl,{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:c?`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?vd(e.submittedAt):o?(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?vd(e.lastReadAt):`Not yet`}),a&&(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:a(e,o)})})]},`${o?.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:o}),a&&(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:c,className:`py-6 text-center text-secondary`,children:s})}),e.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[l(e,null),e.isIndex&&t.has(e.url)&&(e.files??[]).map(t=>l(t,e))]},e.url))]})]})})}var xd=10,Sd={ok:`positive`,pending:`neutral`,warnings:`caution`,errors:`negative`,other:`neutral`},Cd={site:`on your site`,google:`in Google`,bing:`in Bing`};function wd(e){return e.map(e=>Cd[e]).join(` and `)}function Td(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 Ed(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:Sd[t.state],detail:Td(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:wd(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=Ql({rows:[...g,..._],getSearchText:e=>`${e.url} ${e.files?.map(e=>e.url).join(` `)??``}`,pageSize:xd});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)(ws,{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 `,qr(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)($l,{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)(bd,{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)(yd,{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)(yd,{disabled:!e.canSubmit||e.submitting,onClick:()=>void y([n.url]),children:n.submittedAt?`Resubmit`:`Submit`}),e.onInspect&&(0,Q.jsx)(yd,{disabled:e.inspecting,onClick:()=>e.onInspect(n.url),children:`Inspect URLs`}),e.onSetDefault&&!n.isDefault&&(0,Q.jsx)(yd,{disabled:e.settingDefault,title:`Canonry uses this sitemap when a command names none.`,onClick:()=>e.onSetDefault(n.url),children:`Set as default`})]})}),v.totalRows>xd&&(0,Q.jsx)(eu,{page:v.page,pageSize:xd,visibleRows:v.rows.length,totalRows:v.totalRows,onPageChange:v.setPage,itemLabel:`sitemaps`})]})]})}function Dd({label:e,items:t,disabled:n=!1,menuLabel:i,triggerRef:a}){let[o,s]=(0,Z.useState)(!1),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=a??l,d=(0,Z.useId)();return(0,Z.useEffect)(()=>{if(!o)return;c.current?.querySelector(`[role="menuitem"]:not([disabled])`)?.focus();let e=e=>{c.current&&!c.current.contains(e.target)&&s(!1)},t=e=>{e.key===`Escape`&&(s(!1),u.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[o,u]),(0,Q.jsxs)(`div`,{className:`relative inline-flex`,ref:c,children:[(0,Q.jsxs)(q,{ref:u,type:`button`,variant:`outline`,size:`sm`,disabled:n,"aria-haspopup":`menu`,"aria-expanded":o,"aria-controls":o?d:void 0,onClick:()=>s(e=>!e),children:[e,(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),o&&(0,Q.jsx)(`div`,{id:d,role:`menu`,"aria-label":i,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=>{c.current?.contains(e.relatedTarget)||s(!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:()=>{s(!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 Od(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 kd=`Unexpected OAuth redirect URL. Please try again.`;async function Ad(e,t,n){let{authUrl:r,redirectUri:i}=await Xt(e,t);if(!r.startsWith(`https://accounts.google.com/`))throw Error(kd);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 jd=`Search Console is not connected yet. Your Canonry team can set this up.`,Md=[`7d`,`30d`,`90d`,`all`],Nd=500,Pd=[{key:`clicks`,label:`Clicks`,color:Rr[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:Rr[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Zr.caution,format:e=>U(e)},{key:`position`,label:`Avg position`,color:Rr[2],inverted:!0,format:e=>e.toFixed(1)}],Fd=25;function Id(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`?`${dn(Math.abs(o)).magnitude} pts`:$n(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:U(Math.abs(s)),direction:s>0?`up`:`down`,tone:a(s>0),basis:i}}var Ld=[{key:`google-indexed`,engine:`google`,color:Rr[0]},{key:`bing-indexed`,engine:`bing`,color:Rr[6]}];function Rd(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 zd(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 Bd({projectName:e,refreshNonce:t}){let n=L(),{isAdmin:r}=oi(),i=ot(),[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=H({...Co({client:Y,path:{name:e},query:j?{surface:`index-coverage`,...j}:{surface:`index-coverage`,window:k}}),staleTime:ui,placeholderData:re}),[P,ee]=(0,Z.useState)([`clicks`,`impressions`]),[te,ne]=(0,Z.useState)(!0),[F,I]=(0,Z.useState)(null),[ie,ae]=(0,Z.useState)(0),[R,z]=(0,Z.useState)({startDate:``,endDate:``,query:``,page:``}),[B,oe]=(0,Z.useState)(0),[se,ce]=(0,Z.useState)(!1),[le,ue]=(0,Z.useState)(0),[de,fe]=(0,Z.useState)(!1),[pe,me]=(0,Z.useState)(``),[he,ge]=(0,Z.useState)(!0),[_e,ve]=(0,Z.useState)(!1),[ye,be]=(0,Z.useState)(!1),[xe,Ce]=(0,Z.useState)(!1),[Te,Ee]=(0,Z.useState)(!1),[De,Oe]=(0,Z.useState)(!1),[ke,Ae]=(0,Z.useState)(!1),[W,je]=(0,Z.useState)(null),[Me,Ne]=(0,Z.useState)(!1),[Pe,Fe]=(0,Z.useState)(null),[Ie,Le]=(0,Z.useState)(!1),[Re,ze]=(0,Z.useState)(!1),[Be,Ve]=(0,Z.useState)(!1),[He,We]=(0,Z.useState)(!1),[Ge,Ke]=(0,Z.useState)(`indexed`),qe=(0,Z.useId)(),[G,Je]=(0,Z.useState)(null),Ye=!!(R.query.trim()||R.page.trim()||G),Xe=G!==null,Ze=(0,Z.useMemo)(()=>{if(!G)return d;let{key:e,dir:t}=G;return[...d].sort((n,r)=>{let i=e===zr.CTR?Number.isFinite(n.ctr)?n.ctr:0:n[e],a=e===zr.CTR?Number.isFinite(r.ctr)?r.ctr:0:r[e];return t===`asc`?i-a:a-i})},[d,G]),Qe=Ql({rows:Ze,pageSize:25}),et=de?Qe.rows:Ze,[tt,nt]=(0,Z.useState)([]),[rt,it]=(0,Z.useState)(null),[at,st]=(0,Z.useState)(1),ct=(0,Z.useMemo)(()=>{if(tt.length<2)return null;let e=tt[tt.length-1],t=tt[tt.length-2];return{indexed:e.indexed-t.indexed,notIndexed:e.notIndexed-t.notIndexed}},[tt]);(0,Z.useEffect)(()=>{st(1)},[W,Ge,rt]);let lt=(0,Z.useMemo)(()=>rt?(W?.reasonGroups??[]).find(e=>e.reason===rt):void 0,[W,rt]),ut=(0,Z.useMemo)(()=>W?Ge===`indexed`?W.indexed:Ge===`deindexed`?W.deindexed:Ge===`notIndexed`?rt?lt?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,Ge,rt,lt]),dt=Math.max(1,Math.ceil(ut.length/Fd)),ft=Math.min(Math.max(1,at),dt),pt=(ft-1)*Fd,mt=(0,Z.useMemo)(()=>W?.indexed.slice(pt,pt+Fd)??[],[W,pt]),ht=(0,Z.useMemo)(()=>W?.notIndexed.slice(pt,pt+Fd)??[],[W,pt]),gt=(0,Z.useMemo)(()=>W?.deindexed.slice(pt,pt+Fd)??[],[W,pt]),_t=(0,Z.useMemo)(()=>(lt?.urls??[]).slice(pt,pt+Fd),[lt,pt]),[yt,bt]=(0,Z.useState)(!1),[xt,St]=(0,Z.useState)(null),[wt,Tt]=(0,Z.useState)(null),[Et,Dt]=(0,Z.useState)(null),[Ot,kt]=(0,Z.useState)(null);function At(e,t){let n=Cs(e),r=Od(n);r?(Tt(r),St(null)):(Tt(null),St(n.message||t))}let jt=s.find(e=>e.connectionType===`gsc`),Mt=(jt?.scopes??[]).includes(`https://www.googleapis.com/auth/webmasters`),Nt=H({...bo({client:Y,path:{name:e}}),staleTime:ui,enabled:!!jt?.propertyId&&!i}),Pt=Nt.data?.google?.sitemaps??[],Ft=Pt.filter(e=>e.parentUrl===null),It=Ft.filter(e=>e.isIndex).map(e=>e.url),Lt=It.length>0?It:Ft.map(e=>e.url),Rt=It.length,zt=Rt===1?`Resubmit sitemap index`:Rt>1?`Resubmit sitemap indexes`:`Resubmit all sitemaps`,Bt=d.length>0||h.length>0||_.length>0,Vt=Ac(),Ht=vc();async function Ut(t,r=!1){if(i)u([]);else if(!t)u([]),S(``);else{be(!0);try{let{sites:i}=await n.fetchQuery({...so({client:Y,path:{name:e}}),staleTime:r?0:ui});u(i),S(t.propertyId??i[0]?.siteUrl??``),Tt(null)}catch(e){u([]),At(e,`Failed to load Search Console properties`)}finally{be(!1)}}}async function Wt(t){Ee(!0);let r=t??B;try{let t=Ye?Nd:25,i=Ye?0:r,a={limit:String(t)};R.startDate&&(a.startDate=R.startDate),R.endDate&&(a.endDate=R.endDate),R.query&&(a.query=R.query),R.page&&(a.page=R.page),i>0&&(a.offset=String(i)),k&&k!==`all`&&!R.startDate&&(a.window=k);let o=await n.fetchQuery({...za({client:Y,path:{name:e},query:a}),staleTime:ui}),s=o.rows;Ye?(ce(!1),f(s),ue(s.length),fe(!0)):(ce(i+s.length<o.totalMatching),f(s),ue(0),fe(!1))}catch(e){f([]),ce(!1),ue(0),St(e instanceof Error?e.message:`Failed to load GSC performance data`)}finally{Ee(!1)}}async function Gt(){try{let t={};R.startDate&&(t.startDate=R.startDate),R.endDate&&(t.endDate=R.endDate),k&&k!==`all`&&!R.startDate&&(t.window=k);let r=await n.fetchQuery({...Pa({client:Y,path:{name:e},query:t}),staleTime:ui});m(r),M(t.startDate||t.endDate?{...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{}}:null)}catch{m(null)}}async function Kt(t=!1){Oe(!0);try{let r=pe.trim()||void 0,i={limit:`20`};r&&(i.url=r);let[a,o]=await Promise.all([n.fetchQuery({...xo({client:Y,path:{name:e},query:i}),staleTime:t?0:ui}),n.fetchQuery({...Za({client:Y,path:{name:e}}),staleTime:t?0:ui})]);g(a),v(o)}catch(e){g([]),v([]),St(e instanceof Error?e.message:`Failed to load GSC inspection history`)}finally{Oe(!1)}}async function Jt(t=!1){Ne(!0);try{let[r,i]=await Promise.all([n.fetchQuery({...ja({client:Y,path:{name:e}}),staleTime:t?0:ui}),n.fetchQuery({...go({client:Y,path:{name:e}}),staleTime:t?0:ui}).catch(()=>[])]);je(r),nt(i)}catch(e){je(null),nt([]),St(e instanceof Error?e.message:`Failed to load coverage data`)}finally{Ne(!1)}}async function Yt(t){bt(!0),St(null);try{let{succeeded:n,failed:r,total:i}=(await $e(e,{urls:t})).summary;ci({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){St(e instanceof Error?e.message:`Failed to request indexing`)}finally{bt(!1)}}async function Xt(){bt(!0),St(null);try{let{succeeded:t,failed:n,total:r}=(await $e(e,{urls:[],allUnindexed:!0})).summary;ci({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){St(e instanceof Error?e.message:`Failed to request indexing`)}finally{bt(!1)}}async function Zt(t){let n=[];if(!Mt||t.length===0)return n;let r=[...new Set(t)];ze(!0),St(null),Fe({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 Nn(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,Fe({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}`,St(s),ci({title:`Sitemap resubmission partially completed`,detail:f,tone:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`}),n}}let t=r.length;ci({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){St(e instanceof Error?e.message:`Failed to submit sitemap to Google`)}finally{ze(!1),Fe(null),s&&St(s)}return n}async function Qt(){let e=Pt.filter(e=>!e.isIndex).map(e=>e.url),t=It.filter(e=>!Pt.some(t=>t.parentUrl===e));await Zt([...e,...t])}async function $t(t){Le(!0),St(null);try{await we(e,`gsc`,t),await li(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,sitemapUrl:t}:e)),ci({title:`Default sitemap updated`,detail:t,tone:`positive`,dedupeKey:`gsc:sitemap-default:${e}`,dedupeMode:`replace`})}catch(e){St(e instanceof Error?e.message:`Failed to set the default sitemap`)}finally{Le(!1)}}async function en(t){try{await Ht.mutateAsync({projectName:e,projectLabel:e,opts:t?{sitemapUrl:t}:void 0})}catch{}}async function tn(){try{let t=(await n.fetchQuery({...Ni({client:Y,path:{name:e},query:{kind:gr[`gsc-sync`],limit:1}}),staleTime:ui}))[0];kt(t?.status===vt.failed&&t.error?`Last saved Search Console sync failed: ${Ct(t.error)}`:null)}catch{kt(`Saved Search Console sync status is unavailable.`)}}async function nn(){ge(!0),St(null);try{let[t,a]=await Promise.all([i||!r?Promise.resolve(null):jn().catch(()=>null),n.fetchQuery({...io({client:Y,path:{name:e}}),staleTime:ui}).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?Ut(s):Promise.resolve(),!i&&s?tn():Promise.resolve(),Wt(),Gt(),Kt(),Jt()])}finally{ge(!1)}}(0,Z.useEffect)(()=>{u([]),Ve(!1),kt(null),Tt(null),Dt(null)},[e]);let rn=(0,Z.useRef)(t);(0,Z.useEffect)(()=>{nn(),rn.current!==t&&(rn.current=t,N.refetch())},[e,t,r]),(0,Z.useEffect)(()=>{oe(0),I(null),z(e=>e.startDate||e.endDate?{...e,startDate:``,endDate:``}:e),ae(e=>e+1),Gt()},[k]);let an=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{an.current?(oe(0),Qe.setPage(1),Wt(0)):an.current=!0},[ie]);function on(e){let t=F===e?null:e;I(t),z(e=>({...e,startDate:t??``,endDate:t??``})),ae(e=>e+1)}let sn=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{sn.current?(oe(0),Wt(0)):sn.current=!0},[Xe]);async function cn(){if(!a)St(`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`);else{ve(!0),St(null),Dt(null);try{await Ad(e,`gsc`,e=>{(async()=>{Dt(e?`Google connected. Refreshing access…`:`Refreshing Google connection…`);try{await li(n,`google`),await nn()}finally{Dt(null)}})()})===`popup`&&Dt(`Finish the Google consent flow in the popup. This page will refresh automatically.`)}catch(e){St(e instanceof Error?e.message:`Failed to start OAuth flow`)}finally{ve(!1)}}}async function ln(){St(null),Dt(null);try{await dr(e,`gsc`),await li(n,`google`),c(e=>e.filter(e=>e.connectionType!==`gsc`)),u([]),S(``)}catch(e){St(e instanceof Error?e.message:`Failed to disconnect`)}}async function un(){if(x){Ce(!0),St(null);try{await qt(e,`gsc`,x),await li(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,propertyId:x}:e)),ci({title:`GSC property updated`,detail:`${e} is now linked to ${x}.`,tone:`positive`,dedupeKey:`gsc:property:${e}`,dedupeMode:`drop`})}catch(e){St(e instanceof Error?e.message:`Failed to save GSC property`)}finally{Ce(!1)}}}async function dn(){St(null),Dt(null);try{await Vt.mutateAsync({projectName:e,projectLabel:e,opts:{days:parseInt(T,10)||void 0,full:D||void 0}}),await li(n,`gsc`)}catch{}}async function fn(){if(C.trim()){Ae(!0),St(null),Dt(null);try{let t=await hr(e,C.trim());await li(n,`gsc`),b(t),w(``),await Kt()}catch(e){St(e instanceof Error?e.message:`Failed to inspect URL`)}finally{Ae(!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`})})}),Ot&&(0,Q.jsx)(`p`,{role:`status`,className:`mb-3 text-copy-14 text-caution`,children:Ot}),wt&&(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:wt.title}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-caution-200/90`,children:wt.message}),(mc(wt.enableUrl)||mc(wt.indexingApiUrl))&&(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3`,children:[mc(wt.enableUrl)&&(0,Q.jsx)(`a`,{href:mc(wt.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(wt.indexingApiUrl)&&(0,Q.jsx)(`a`,{href:mc(wt.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:()=>Tt(null),children:`×`})]})}),xt&&(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:[xt,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>St(null),children:`×`})]}),Et&&(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:[Et,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-positive-400 hover:text-positive-200`,onClick:()=>Dt(null),children:`×`})]}),he?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading…`}):(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[jt?(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:jt.domain}),(0,Q.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Coverage measured`,` `,W?.lastInspectedAt?qr(W.lastInspectedAt):`never`]}),!i&&(0,Q.jsx)(`button`,{type:`button`,className:`ml-auto text-muted transition-colors hover:text-negative-400`,onClick:si(ln),children:`Disconnect`})]}):r?(0,Q.jsxs)(ws,{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:_e,onClick:si(cn),children:_e?`Opening…`:`Connect Google Search Console`}):(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,asChild:!0,children:(0,Q.jsx)(V,{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)(ws,{className:`surface-card`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jd})}),(jt||Bt)&&(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(ws,{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:`${Rd(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 ${Nd.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)(wu,{windows:Md,value:k,onChange:e=>{A(e),oe(0),Qe.setPage(1)},label:`Search Console time period`,formatOption:e=>e===`all`?`All`:e}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Te,onClick:()=>{oe(0),Qe.setPage(1),Wt(0),Gt()},children:Te?`Loading…`:`Apply filters`})]})]}),p&&p.daily.length>0&&(()=>{let{totals:e,daily:t,trends:n,periodComparison:r}=p,i=t=>e[t]??null,a=Ld.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=Ue(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=[...Pd.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:te?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:Pd.map(e=>{let t=i(e.key);return{key:e.key,label:e.label,color:e.color,value:t===null?`—`:e.format(t),change:Id(r,e.key,e.inverted),interactive:!0,disabled:t===null}})},h=a.length===0?null:{key:`indexed`,label:`Indexed pages`,basis:zu(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:Ru(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)(Ku,{name:`Search performance figures`,frame:`none`,mode:`compare`,groups:h?[m,h]:[m],selected:P,onSelect:e=>ee(t=>t.includes(e)?t.length===1?t:t.filter(t=>t!==e):[...t,e]),chart:(0,Q.jsx)(Br,{data:d,xKey:`date`,series:f,xTickFormatter:Vr,labelFormatter:Jr,onSelectX:on,selectedX:F}),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:te,onChange:e=>ne(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":F===e.date,onClick:()=>on(e.date),children:[Jr(e.date),`: `,e.clicks,` clicks, `,e.impressions,` impressions`]},e.date))}),F&&(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 `,Jr(F)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`text-link hover:underline`,onClick:()=>on(F),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:R.startDate,onChange:e=>z(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:R.endDate,onChange:e=>z(t=>({...t,endDate:e.target.value}))}),(0,Q.jsx)($l,{value:R.query,onChange:e=>z(t=>({...t,query:e})),label:`Filter search queries`,placeholder:`Contains query…`}),(0,Q.jsx)($l,{value:R.page,onChange:e=>z(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(zr).map(e=>(0,Q.jsx)(`th`,{className:`text-right`,"aria-sort":G?.key===e?G.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:()=>{Qe.setPage(1),Je(t=>t?.key===e?t.dir===`desc`?{key:e,dir:`asc`}:null:{key:e,dir:`desc`})},children:[ii[e],G?.key===e?G.dir===`desc`?` ↓`:` ↑`:``]})},e))]})}),(0,Q.jsx)(`tbody`,{children:et.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)(Zl,{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:U(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)(eu,{page:de?Qe.page:Math.floor(B/25)+1,pageSize:25,visibleRows:et.length,totalRows:de?le:void 0,hasNextPage:de?void 0:se,disabled:Te,itemLabel:de?`matches`:`rows`,onPageChange:e=>{if(de){Qe.setPage(e);return}let t=(e-1)*25;oe(t),Wt(t)}}),de&&le>=Nd?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Results are capped at `,Nd.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)(ws,{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:[W&&W.notIndexed.length>0&&(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:yt,onClick:()=>void Xt(),children:yt?`Requesting…`:`Request indexing (${W.notIndexed.length})`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Me,onClick:()=>void Jt(!0),children:Me?`Loading…`:`Reload saved coverage`})]})]}),W&&W.summary.total>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mt-6 flex flex-col items-center`,children:(()=>{let e=W.summary.indexedShare??0,t=W.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:Gr.trackSubtle,strokeWidth:`14`}),(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Zr.positiveDeep,strokeWidth:`14`,strokeDasharray:n,strokeDashoffset:r,strokeLinecap:`round`,transform:`rotate(-90 64 64)`,style:{transition:`stroke-dashoffset 0.6s ease`}}),W.summary.notIndexed>0&&(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Gr.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:U(W.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:W.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:W.summary.notIndexed.toLocaleString()}),(0,Q.jsxs)(`p`,{className:`text-label-12 normal-case text-muted`,children:[`Not indexed`,(W.reasonGroups??[]).length>0&&(0,Q.jsxs)(`span`,{className:`ml-1 text-faint`,children:[`· `,(W.reasonGroups??[]).length,` `,(W.reasonGroups??[]).length===1?`reason`:`reasons`]})]})]})]}),W.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:W.summary.deindexed.toLocaleString()}),(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Deindexed`})]})]})]})]})]})})()}),(0,Q.jsx)(_l,{id:qe,label:`Coverage status`,value:Ge,onChange:e=>{Ke(e),it(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 (${W.indexed.length})`],[`notIndexed`,`Not Indexed (${W.notIndexed.length})`],[`deindexed`,`Deindexed (${W.deindexed.length})`]]}),(0,Q.jsxs)(`div`,{id:`${qe}-panel`,role:`tabpanel`,"aria-labelledby":`${qe}-${Ge}`,tabIndex:0,className:`mt-3 overflow-x-auto`,children:[Ge===`indexed`&&W.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:mt.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))})]}),Ge===`notIndexed`&&!rt&&(W.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:(W.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:()=>it(e.reason),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),it(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))})]}),Ge===`notIndexed`&&!rt&&(W.reasonGroups??[]).length===0&&W.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: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.indexingState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`})]},e.id))})]}),Ge===`notIndexed`&&rt&&(()=>{let e=(W.reasonGroups??[]).find(e=>e.reason===rt);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:()=>it(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:yt,onClick:()=>void Yt(e.urls.map(e=>e.url)),children:yt?`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:_t.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:yt,onClick:()=>void Yt([e.url]),title:`Request indexing`,children:`Index`})})]},e.id))})]})]}):null})(),Ge===`deindexed`&&W.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:gt.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}`))})]}),(Ge===`indexed`&&W.indexed.length===0||Ge===`notIndexed`&&!rt&&W.notIndexed.length===0||Ge===`deindexed`&&W.deindexed.length===0)&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No URLs in this category.`}),(0,Q.jsx)(eu,{page:ft,pageSize:Fd,visibleRows:Math.min(Fd,ut.length-pt),totalRows:ut.length,onPageChange:st,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":He,onClick:()=>We(e=>!e),children:[(0,Q.jsx)(`span`,{children:`Coverage history`}),(0,Q.jsx)(`span`,{children:He?`Hide snapshots`:tt.length>0?`View ${tt.length} snapshots`:`View history`})]}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Current: `,W.summary.indexed.toLocaleString(),` indexed, `,W.summary.notIndexed.toLocaleString(),` not indexed.`,ct&&(0,Q.jsxs)(Q.Fragment,{children:[` Since the last snapshot: `,ct.indexed>=0?`+`:``,ct.indexed.toLocaleString(),` indexed, `,ct.notIndexed>=0?`+`:``,ct.notIndexed.toLocaleString(),` not indexed.`]})]}),He&&(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:tt.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:tt.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:Me?`Loading coverage data…`:`No coverage data yet. Inspect your sitemap to populate this view.`})]}),!i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ed,{engine:`Google`,data:Nt.isError?null:Nt.isPending&&Nt.fetchStatus!==`idle`?void 0:Nt.data?.google??null,loadError:Nt.isError?Se(Nt.error):null,label:e=>zd(e,jt?.propertyId),canSubmit:Mt,submitBlocked:jt?(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:si(cn),children:`Reconnect`})]}):void 0,onSubmit:Zt,submitting:Re,defaultUrl:jt?.sitemapUrl??null,onSetDefault:e=>void $t(e),settingDefault:Ie,onInspect:e=>void en(e),inspecting:Ht.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:Ft.length>0?(0,Q.jsx)(Dd,{label:Pe?`Submitting ${Pe.completed} of ${Pe.total}`:`Resubmit all`,menuLabel:`Resubmit sitemaps to Google`,disabled:!Mt||Re,items:[{key:`primary`,label:zt,description:Rt>0?`Google rereads every sitemap the index lists.`:`Each sitemap in the list, once.`,disabled:Lt.length===0,onSelect:()=>void Zt(Lt)},{key:`files`,label:`Resubmit all files`,description:`Every file inside each index, one by one.`,onSelect:()=>void Qt()}]}):void 0}),(0,Q.jsxs)(ws,{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 fn()}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:ke||!jt?.propertyId||!C.trim(),onClick:si(fn),children:ke?`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:Tr(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:qr(y.crawlTime)})]})]})]})]}),(0,Q.jsxs)(ws,{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:De,onClick:()=>void Kt(!0),children:De?`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:pe,onChange:e=>me(e.target.value)})]}),(0,Q.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`self-end`,disabled:De,onClick:()=>void Kt(!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:Tr(e.isMobileFriendly??null)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:qr(e.inspectedAt)})]},e.id))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No inspection history yet.`})]}),(0,Q.jsxs)(ws,{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:qr(e.transitionDate)})]},`${e.url}:${e.transitionDate}`))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No deindexed transitions recorded.`})]})]}),jt&&!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:()=>{Be||Ut(jt),Ve(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 ${Be?`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`})]})}),Be&&(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)(ws,{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:ye||l.length===0,onChange:e=>S(e.target.value),children:l.length===0?(0,Q.jsx)(`option`,{value:``,children:ye?`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:ye,onClick:()=>void Ut(jt,!0),children:ye?`Refreshing…`:`Refresh properties`}),(0,Q.jsx)(q,{type:`button`,size:`sm`,disabled:!x||xe,onClick:si(un),children:xe?`Saving…`:`Save property`})]})]})]}),(0,Q.jsxs)(ws,{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:Vt.isPending||!jt.propertyId,onClick:si(dn),children:Vt.isPending?`Queueing…`:`Queue sync`}),!jt.propertyId&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-caution-400`,children:`Select a Search Console property before queueing a sync.`})]})]})]})})]})]})]})}var Vd=[`7d`,`30d`,`90d`,`all`],Hd=10,Ud=[{key:`clicks`,label:`Clicks`,color:Rr[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:Rr[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Zr.caution,format:e=>U(e)},{key:`position`,label:`Avg position`,color:Rr[2],inverted:!0,format:e=>e.toFixed(1)}],Wd=`bing-indexed`,Gd=`Impression-weighted across the queries Bing names. Bing reports these per week, so the line moves weekly.`,Kd=`Asks Bing directly. Counts against the shared Bing request limit for this key.`;function qd(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:$n(t),direction:t>0?`up`:`down`,tone:t>0?`worse`:`better`,basis:n}}function Jd(e){return e==null?`—`:e.toFixed(1)}function Yd(e){return e==null?`—`:Math.round(e).toLocaleString()}function Xd(e){return e.replace(/^https?:\/\//,``).replace(/\/+$/,``)}function Zd(e,t){let n=t.replace(/\/+$/,``);return e.startsWith(n)?e.slice(n.length)||`/`:e}function Qd(e,t){return e?.find(e=>e.kind===t)}function $d(e){let t=e?.payload;return t&&typeof t.dailyQuota==`number`&&typeof t.monthlyQuota==`number`?{dailyQuota:t.dailyQuota,monthlyQuota:t.monthlyQuota}:null}function ef(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 tf(e){return Array.isArray(e?.payload)?e.payload.filter(e=>typeof e==`object`&&!!e):null}var nf=new Set([`entityType`,`requestType`,`type`,`role`]);function rf(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)?Jr(e.slice(0,10)):nf.has(t)&&/^[a-z]+(?:-[a-z]+)*$/.test(e)?e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`-`,` `):e:JSON.stringify(e)}function af({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 of({projectName:e,refreshNonce:t}){let n=L(),{canWrite:r,isAdmin:i}=oi(),a=r&&!K()&&!ot(),[o,s]=(0,Z.useState)(),c=!i&&a&&o?.project===e?o.sites:void 0,l=H({...Li({client:Y,path:{name:e}}),staleTime:ui}),u=l.data??null,d=H({...Oi({client:Y,path:{name:e}}),staleTime:ui,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 Un(e,f.trim()||void 0);if(!i){let n=Wt(t.domain),r=t.availableSites.filter(e=>e.verified&&n!==null&&Wt(e.url)===n);s({project:e,sites:r})}p(``),await li(n,`bing`)}catch(e){_(Ss(e))}}}async function y(){_(null);try{await Mn(e),s(void 0),h(``),await li(n,`bing`)}catch(e){_(Ss(e))}}async function b(){if(a&&m.trim()){_(null);try{await _n(e,m.trim()),await li(n,`bing`)}catch(e){_(Ss(e))}}}if(l.isPending)return(0,Q.jsx)(af,{children:(0,Q.jsx)(ws,{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)(af,{children:(0,Q.jsxs)(ws,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load the Bing connection: `,Ss(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)(af,{children:(0,Q.jsxs)(ws,{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)(ds,{size:`sm`,disabled:!i&&!f.trim(),onClick:si(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)(af,{children:(0,Q.jsxs)(ws,{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)(ds,{size:`sm`,variant:`ghost`,onClick:si(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?qr(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:si(async e=>{e.preventDefault(),await b()}),children:[(0,Q.jsx)(`input`,{type:`url`,required:!0,"aria-label":`Verified Bing site URL`,placeholder:Wt(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:Ss(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:si(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)(sf,{projectName:e,connection:u,siteUrl:u.siteUrl,onDisconnect:y,error:g})}function sf({projectName:e,connection:t,siteUrl:n,onDisconnect:i,error:a}){let[o,s]=(0,Z.useState)(`30d`),c=ot(),l={name:e},u=H({...Ki({client:Y,path:l,query:{window:o}}),staleTime:ui,placeholderData:re,enabled:!c}),d=H({...Xi({client:Y,path:l}),staleTime:ui,enabled:!c}),f=H({...ea({client:Y,path:l}),staleTime:ui,enabled:!c}),p=!c&&!!(u.data?.latestAvailableDate||d.data?.syncedAt||f.data?.syncedAt),m=!u.isPending&&!d.isPending&&!f.isPending,h=[u,d,f].find(e=>e.isError)?.error??null,g=tf(Qd(d.data?.snapshots,`blocked-urls`))?.length??0;return(0,Q.jsx)(af,{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:Xd(n)}),u.data?.latestAvailableDate&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Data through `,Jr(u.data.latestAvailableDate)]})]}),d.data?.syncedAt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Synced `,qr(d.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)(r,{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?qr(t.updatedAt):`—`})]}),!K()&&!c&&(0,Q.jsx)(ds,{size:`sm`,variant:`ghost`,onClick:si(i),children:`Disconnect`})]})]}),children:(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[a&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-negative`,children:a}),!c&&(m&&!p&&h?(0,Q.jsxs)(ws,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load Bing data: `,Ss(h)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{u.refetch(),d.refetch(),f.refetch()},children:`Retry`})]}):m&&!p?(0,Q.jsx)(uf,{projectName:e,loadedAt:d.dataUpdatedAt}):(0,Q.jsx)(df,{projectName:e,siteUrl:n,range:o,onRangeChange:s})),(0,Q.jsx)(gf,{projectName:e,siteUrl:n,snapshots:d.data?.snapshots}),p&&(0,Q.jsx)(_f,{projectName:e,siteUrl:n}),p&&(0,Q.jsx)(mf,{projectName:e}),p&&(0,Q.jsx)(yf,{siteUrl:n,snapshots:d.data?.snapshots??[]})]})})}var cf=5e3;function lf(e){return e?.status===vt.queued||e?.status===vt.running}function uf({projectName:e,loadedAt:t}){let n=L(),r=H({...Ni({client:Y,path:{name:e},query:{kind:gr[`bing-sync`],limit:1}}),refetchInterval:e=>lf(e.state.data?.[0])?cf:!1,enabled:!K()}),i=r.data?.[0],a=lf(i),[o,s]=(0,Z.useState)(!1),c=i&&!a&&i.finishedAt?Date.parse(i.finishedAt):0;(0,Z.useEffect)(()=>{c>t&&Ls(n,gr[`bing-sync`],e)},[c,t,n,e]);async function l(){s(!0);try{let t=await br(e);Ks({id:t.id,projectId:t.projectId,kind:gr[`bing-sync`],projectLabel:e,sourceAction:`bing-sync`}),await r.refetch(),ci({title:`Bing sync started`,detail:`Search data appears here when it finishes.`,tone:`neutral`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}catch(t){ci({title:`Bing sync could not start`,detail:Ss(t),tone:`negative`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}finally{s(!1)}}let u=!a&&i?.status===vt.failed;return(0,Q.jsxs)(ws,{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===vt.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?`: ${Ct(i.error)}`:`.`]}),!K()&&(0,Q.jsx)(ds,{className:`mt-3`,size:`sm`,disabled:a||o,onClick:si(l),children:a||o?`Sync running…`:u?`Try the sync again`:`Sync Bing data now`})]})}function df({projectName:e,siteUrl:t,range:n,onRangeChange:r}){let i={name:e},a=H({...Ki({client:Y,path:i,query:{window:n}}),staleTime:ui,placeholderData:re}),o=H({...Ka({client:Y,path:i,query:{window:n,groupBy:`week`}}),staleTime:ui,placeholderData:re}),s=H({...Co({client:Y,path:i,query:{surface:`index-coverage`,window:n}}),staleTime:ui,placeholderData:re}),[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: `,Ss(a.error)]});else{let r=o.data?.totals?.avgImpressionPosition??null,i=qd(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:Ud.map(e=>{if(e.key===`position`)return{key:e.key,label:e.label,help:Gd,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:Id(m,e.key,!1),interactive:!0,disabled:f.rows.length===0}})},_=p?{key:`indexed`,label:`Indexed pages`,basis:zu([p]),figures:[{key:Wd,label:`Bing`,color:Rr[6],value:p.value===null?`—`:p.value.toLocaleString(),change:Ru(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?Ue(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,[Wd]:T.get(e)??null}}):[],D=[...Ud.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(Wd)&&p?[{dataKey:Wd,label:`Bing indexed pages`,color:Rr[6],axisId:Wd,formatValue:e=>e.toLocaleString(),connectNulls:!0}]:[]];h=(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(Ku,{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)(Br,{data:E,xKey:`date`,series:D,xTickFormatter:Vr,labelFormatter:Jr,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)(ff,{projectName:e,siteUrl:t,range:n})]})}return(0,Q.jsxs)(ws,{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:`${Rd(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:[Jr(f.window.startDate),` to `,Jr(f.window.endDate)]})]}),(0,Q.jsx)(wu,{windows:Vd,value:n,onChange:r,label:`Bing time period`,formatOption:e=>e===`all`?`All`:e})]}),h]})}function ff({projectName:e,siteUrl:t,range:n}){let[i,a]=(0,Z.useState)(`queries`),o=(0,Z.useId)(),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(void 0),[d,f]=(0,Z.useState)(1),[p,m]=(0,Z.useState)(null),g={name:e},_=(d-1)*Hd;(0,Z.useEffect)(()=>{let e=s.trim()||void 0;if(e===void 0){u(void 0);return}let t=setTimeout(()=>u(e),300);return()=>clearTimeout(t)},[s]);let v=H({...Ka({client:Y,path:g,query:{window:n,query:l,limit:Hd,offset:_}}),staleTime:ui,placeholderData:re,enabled:i===`queries`}),y=H({..._i({client:Y,path:g,query:{window:n,page:l,limit:Hd,offset:_}}),staleTime:ui,placeholderData:re,enabled:i===`pages`}),b=i===`queries`?v:y,x=i===`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=i===`queries`?`Query`:`Page`;return(0,Z.useEffect)(()=>{f(1),m(null)},[i,n,l]),(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)(_l,{id:o,label:`Bing search rows`,value:i,onChange:a,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)($l,{className:`mb-1.5 w-full sm:w-64`,value:s,onChange:c,label:i===`queries`?`Filter Bing queries`:`Filter Bing pages`,placeholder:i===`queries`?`Contains query…`:`Contains page URL…`})]}),(0,Q.jsxs)(`div`,{id:`${o}-panel`,role:`tabpanel`,"aria-labelledby":`${o}-${i}`,tabIndex:0,children:[b.isError?(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing `,i,`: `,Ss(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…`:l?`No ${i} match "${l}" in this window.`:`Bing named no ${i} in this window.`})}),x.map(a=>{let o=p===a.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":o,"aria-label":`${o?`Hide`:`Show`} details for ${a.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:()=>m(o?null:a.key),children:o?(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,Q.jsx)(`td`,{className:`max-w-md text-strong`,children:i===`pages`?(0,Q.jsx)(Zl,{value:Zd(a.key,t),title:a.key,className:`font-mono text-label-13`}):(0,Q.jsx)(`span`,{className:`block truncate`,title:a.key,children:a.key})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:a.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:a.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:U(a.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Jd(a.avgImpressionPosition)})]}),o&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:5,className:`pb-4`,children:(0,Q.jsx)(pf,{projectName:e,siteUrl:t,range:n,tab:i,rowKey:a.key})})]})]},a.key)})]})]})}),(0,Q.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Q.jsx)(eu,{page:d,pageSize:Hd,visibleRows:x.length,totalRows:S,disabled:b.isFetching,itemLabel:i,onPageChange:f})})]})]})}function pf({projectName:e,siteUrl:t,range:n,tab:r,rowKey:i}){let a={name:e},[o,s]=(0,Z.useState)(!1),c=H({...Ka({client:Y,path:a,query:{window:n,query:i,match:`exact`,groupBy:`week`}}),staleTime:ui,enabled:r===`queries`}),l=H({..._i({client:Y,path:a,query:{window:n,page:i,match:`exact`,groupBy:`week`}}),staleTime:ui,enabled:r===`pages`}),u=H({...Ji({client:Y,path:a,query:{query:i}}),staleTime:ui,retry:!1,enabled:o&&r===`queries`}),d=H({...Ya({client:Y,path:a,query:{page:i}}),staleTime:ui,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:Jr(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:Jd(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:Kd})]})),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:`${Ss(p.error)} Nothing was stored.`}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void p.refetch(),children:[(0,Q.jsx)(v,{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?Jr(e.date):`—`}),(0,Q.jsx)(`td`,{className:`max-w-xs`,children:r===`queries`?(0,Q.jsx)(Zl,{value:Zd(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:Jd(e.avgImpressionPosition)})]},`${e.date}:${e.key}:${n}`))})]}))]})]})}function mf({projectName:e}){let t=H({...$i({client:Y,path:{name:e}}),staleTime:ui}),[n,i]=(0,Z.useState)(null),a=t.data?.market,o=t.data?.rows??[];return(0,Q.jsxs)(ws,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`h3`,{children:`Search demand`}),a&&(0,Q.jsx)(X,{label:`${a.country.toUpperCase()} · ${a.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: `,Ss(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:[o.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.`})}),o.map(t=>{let a=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":a,"aria-label":`${a?`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:()=>i(a?null:t.query),children:a?(0,Q.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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:Yd(t.avgWeeklyImpressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Yd(t.latestImpressions)})]}),a&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:3,className:`pb-4`,children:(0,Q.jsx)(hf,{projectName:e,query:t.query})})]})]},t.query)})]})]})})]})}function hf({projectName:e,query:t}){let n=H({...$i({client:Y,path:{name:e},query:{query:t}}),staleTime:ui}),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:Jr(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 gf({projectName:e,siteUrl:t,snapshots:n}){let r=L(),i=ot(),a={name:e},o=H({...ua({client:Y,path:a}),staleTime:ui}),s=H({...Ti({client:Y,path:a}),staleTime:ui}),c=H({...Di({client:Y,path:a,query:{days:`30`}}),staleTime:ui,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=$d(Qd(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 bn(e,t)).summary;ci({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 li(r,`bing`)}catch(t){let r=Ss(t);y(r),ci({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 Me(e,m.trim());_(t),await li(r,`bing`)}catch(e){y(Ss(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:U(x.percentage,et.percent)}]:[],A=Ql({rows:l===`not-indexed`?C:l===`unknown`?w:l===`indexed`?T:[],pageSize:Hd}),j=Ql({rows:E,pageSize:Hd}),M=Ql({rows:c.data?.rows??[],pageSize:Hd}),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)(ws,{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 ${Jr(S.date)}. Crawl by day has the codes.`})]}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:o.data?.lastInspectedAt?`Last inspected ${qr(o.data.lastInspectedAt)}`:`No inspection history yet`})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:k.length>0?(0,Q.jsx)(td,{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)(_l,{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)(ds,{size:`sm`,variant:`outline`,disabled:f,onClick:si(()=>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)(Zl,{value:Zd(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?qr(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)(ds,{size:`sm`,variant:`ghost`,disabled:f,onClick:si(()=>D({urls:[n.url]},n.url)),children:`Submit`})})})]},n.id))]})]})})(),(l===`not-indexed`||l===`unknown`||l===`indexed`)&&(0,Q.jsx)(eu,{page:A.page,pageSize:Hd,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)(ds,{size:`sm`,disabled:!m.trim(),onClick:si(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)(Zl,{value:Zd(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:qr(e.inspectedAt)})]},e.id))]})]}),(0,Q.jsx)(eu,{page:j.page,pageSize:Hd,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:Jr(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)(eu,{page:M.page,pageSize:Hd,visibleRows:M.rows.length,totalRows:M.totalRows,onPageChange:M.setPage,itemLabel:`days`})]})]})]})}function _f({projectName:e,siteUrl:t}){let{canWrite:n}=oi(),r=H({...bo({client:Y,path:{name:e}}),staleTime:ui}),[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 Jt(e,r),n.push(r);let r=n.length;ci({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){ci({title:n.length>0?`Bing took ${n.length} of ${t.length}`:`Bing did not take the sitemap`,detail:Ss(r),tone:`negative`,dedupeKey:`bing:submit-sitemap:${e}`,dedupeMode:`replace`})}finally{a(!1)}return n}async function l(t){s(!0);try{await St(e,{sitemapUrl:t}),ci({title:`Checking sitemap URLs in Bing`,detail:`Coverage updates when the check finishes.`,tone:`neutral`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}catch(t){ci({title:`Sitemap check could not start`,detail:Ss(t),tone:`negative`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}finally{s(!1)}}return(0,Q.jsx)(Ed,{engine:`Bing`,data:r.isError?null:r.isPending?void 0:r.data.bing,loadError:r.isError?Ss(r.error):null,label:e=>Zd(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 vf=`Bing shows this only to the site owner key. Not a failure.`;function yf({siteUrl:e,snapshots:t}){let n=$d(Qd(t,`url-submission-quota`)),r=$d(Qd(t,`content-submission-quota`)),i=ef(Qd(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:vf};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=Qd(t,n),s=tf(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)(bf,{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)(Zl,{value:Zd(r,e),title:r,className:`font-mono text-neutral`}):rf(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)(ws,{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)(bf,{label:`URL submissions left`,value:l(n),help:`URL submissions Bing will still accept, as of the last sync.`}),(0,Q.jsx)(bf,{label:`Content submissions left`,value:l(r)}),(0,Q.jsx)(bf,{label:`Crawl boost`,value:i?i.crawlBoostEnabled?`On`:i.crawlBoostAvailable?`Off`:`Not offered`:`—`}),i&&i.crawlRate.length===24&&(0,Q.jsx)(bf,{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 bf({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)(h,{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 xf=Rr[0],Sf=Rr[1],Cf=Rr[2],wf=Rr[3],Tf=Rr[4],Ef=[`both`,`server`,`ga4`],Df=[`days`,`months`],Of={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.`},kf=e=>new Date(`${e}-01T00:00:00.000Z`),Af=e=>kf(e).toLocaleDateString(void 0,{month:`short`,timeZone:`UTC`}),jf=e=>kf(String(e)).toLocaleDateString(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),Mf=e=>Number(e.slice(0,4))*12+Number(e.slice(5,7)),Nf={fontSize:12,paddingTop:6},Pf={top:4,right:8,left:0,bottom:0},Ff=44,If=.4,Lf=`ai-visits`,Rf=e=>typeof e==`number`?pt(Math.round(e)):String(e),zf=`Page fetches`,Bf={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 ${Jr(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:zf,olderPageFetchesSeries:`${zf} (older count)`,visitors:`AI visitors`,visitorsDetail:`arrived from an AI answer`,visitorsOlderDetail:`older days may read high`},Vf=`Visits, server`,Hf=`Visits, GA4`,Uf=`${Vf} (older count)`,Wf=`${Vf} (part month)`,Gf=`${Vf} (part month, older count)`,Kf=`Visits, GA4 (part month)`,qf=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function Jf(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 Yf(e,t){if(!e||t<e.startMonth||t>e.endMonth)return null;let n=Mf(e.endMonth)-Mf(e.startMonth);return n<=0?null:e.start+(e.end-e.start)*((Mf(t)-Mf(e.startMonth))/n)}function Xf(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 Zf(e){let t=e=>e.measured!==!1;if(e.length===0||t(e[0]))return null;let n=e.findIndex(t)-1;return n<0?{from:e[0].bucket,to:e[e.length-1].bucket}:{from:e[0].bucket,to:e[n].bucket}}function Qf(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 $f(e){let t=e===null?NaN:Date.parse(e);return Number.isFinite(t)?new Date(t-1).toISOString().slice(0,10):void 0}function ep(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 tp({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 np({source:e,rows:t,monthly:n,height:r,showXAxis:i,showTrend:a,unmeasured:o,older:s}){let c=e===`server`,l=c?Cf:wf,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?Vf:Hf,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)(tp,{color:l}),c?Vf:Hf]}),d&&(0,Q.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(tp,{color:l,opacity:If}),`Older count, may read high`]})]}),(0,Q.jsx)(de,{width:`100%`,height:r,children:(0,Q.jsxs)(be,{data:t,syncId:Lf,margin:i?Pf:{...Pf,bottom:10},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`bucket`,hide:!i,tick:Xr,stroke:ti,tickFormatter:n?Af:Vr,minTickGap:n?8:28}),(0,Q.jsx)(ve,{tick:Xr,stroke:ti,width:Ff,allowDecimals:!1,tickFormatter:nt,tickCount:r<150?3:5}),(0,Q.jsx)(_e,{contentStyle:ei.contentStyle,labelStyle:ei.labelStyle,itemStyle:ei.itemStyle,labelFormatter:n?jf:Jr,formatter:Rf}),o&&o.from!==o.to&&(0,Q.jsx)(pe,{x1:o.from,x2:o.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)`}}),s&&(0,Q.jsx)(pe,{x1:s.from,x2:s.to,fill:`var(--color-overlay-hover)`,fillOpacity:.3,stroke:`none`}),s&&(0,Q.jsx)(xe,{x:s.to,stroke:Tf,strokeDasharray:`4 4`,strokeWidth:1.5}),c&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`aiReferralLandedHits`,name:Vf,stroke:l,strokeWidth:2,connectNulls:!1,dot:ep(u(`aiReferralLandedHits`),l)}),d&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`serverOlder`,name:Uf,stroke:l,strokeOpacity:If,strokeWidth:2,connectNulls:!1,dot:ep(u(`serverOlder`),l,!1,If)}),c&&n&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`serverPartial`,name:Wf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:ep(u(`serverPartial`),l,!0)}),d&&n&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`serverOlderPartial`,name:Gf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:ep(u(`serverOlderPartial`),l,!0,If)}),c&&a&&(0,Q.jsx)(ye,{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)(ye,{type:`monotone`,dataKey:`ga4Visits`,name:Hf,connectNulls:!1,stroke:l,strokeWidth:2,dot:ep(u(`ga4Visits`),l)}),!c&&n&&(0,Q.jsx)(ye,{type:`monotone`,dataKey:`ga4Partial`,name:Kf,legendType:`none`,connectNulls:!1,stroke:l,strokeWidth:0,activeDot:!1,dot:ep(u(`ga4Partial`),l,!0)}),!c&&a&&(0,Q.jsx)(ye,{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 rp({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=Qc(e,{range:d,granularity:`month`,limit:1},{enabled:u}),p=Qc(e,{sinceMinutes:t,granularity:`day`,limit:1}),m=el(e),h=H({...co({client:Y,path:{name:e}}),enabled:!!e,staleTime:fi}),g=h.data?.connected===!0,_=H({...fa({client:Y,path:{name:e},query:{window:t>=259200?`180d`:t>=129600?`90d`:t>=43200?`30d`:`7d`}}),enabled:!!e&&g,staleTime:fi}),v=H({...fa({client:Y,path:{name:e},query:{startDate:d.since.slice(0,10)}}),enabled:!!e&&g&&u,staleTime:fi}),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)(()=>Zf(y),[y]),C=p.data?.series?.coverageStart??null,w=p.data?.series?.aiReferralCountingChangedAt??null,T=(0,Z.useMemo)(()=>Qf(y,w?.slice(0,10)),[w,y]),E=p.data?.series?.aiUserFetchCountingChangedAt??null,D=(0,Z.useMemo)(()=>Qf(y,$f(E)),[E,y]),O=(e,t,n)=>{let r=n.payload?.bucket;return D&&t===zf&&r!==void 0&&r<=D.to?[Rf(e),Bf.olderPageFetchesSeries]:Rf(e)},k=p.data?.series?.trends,A=(0,Z.useMemo)(()=>{let e=Jf(k?.crawlerContentHits,y.length),t=Jf(k?.aiUserFetchHits,y.length),n=Jf(k?.aiReferralLandedHits,y.length);return y.map((r,i)=>({...r,crawlerContentHits:r.measured===!1?null:qf(r.crawlerContentHits),aiUserFetchHits:r.measured===!1?null:qf(r.aiUserFetchHits),aiReferralLandedHits:r.measured===!1?null:qf(r.aiReferralLandedHits),ga4Visits:b.get(r.bucket)??null,ga4Trend:Xf(x,r.bucket),crawlTrend:e[i],fetchTrend:t[i],visitTrend:n[i]}))},[y,b,x,k]),j=f.data?.series,M=v.data,N=(0,Z.useMemo)(()=>j?.points??[],[j]),P=(0,Z.useMemo)(()=>{let e=new Set(j?.partialBuckets??[]),t=new Map((M?.months??[]).map(e=>[e.month,e])),n=Jf(j?.trends?.aiReferralLandedHits,N.length),r=new Map(N.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?qf(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:Yf(M?.monthlyTrend,n),recorded:o!==null||(s?.sessions??null)!==null}}),a=i.findIndex(e=>e.recorded);return a>0?i.slice(a):i},[N,j,M]),ee=(0,Z.useMemo)(()=>{if(o===`ga4`)return null;if(!u)return S;let e=new Set(P.map(e=>e.bucket));return Zf(N.filter(t=>e.has(t.bucket)))},[o,u,N,P,S]),te=(0,Z.useMemo)(()=>u?Qf(N,j?.aiReferralCountingChangedAt?.slice(0,7)):T,[u,N,j,T]),ne=te!==null&&o!==`ga4`,F=(0,Z.useMemo)(()=>(u?P:A).map(e=>{let t=e.aiReferralLandedHits??null,n=`serverPartial`in e?e.serverPartial:null,r=te!==null&&e.bucket<=te.to;return{...e,aiReferralLandedHits:r?null:t,serverOlder:r?t:null,serverPartial:r?null:n,serverOlderPartial:r?n:null}}),[u,P,A,te]),I=[`server`,`ga4`].filter(e=>F.some(t=>e===`server`?t.aiReferralLandedHits!=null||t.serverOlder!=null||t.serverPartial!=null||t.serverOlderPartial!=null:t.ga4Visits!=null||t.ga4Partial!=null)),L=o===`both`?I.length>0?I:[`server`,`ga4`]:[o],re=(M?.months??[]).filter(e=>e.complete&&e.sessions!==null).at(-1)??null,ie=P.filter(e=>e.aiReferralLandedHits!==null).at(-1)??null,ae=o===`server`?ie?.bucket??null:o===`ga4`?re?.month??null:re?.month??ie?.bucket??null,R=ae?P.find(e=>e.bucket===ae)?.aiReferralLandedHits??null:null,z=M?.monthlyTrend??null,B=u&&o!==`ga4`,V=u&&o!==`server`,oe=V&&g,se=B&&f.isSuccess||oe&&v.isSuccess,le=(!B||f.isSuccess)&&(!V||h.isSuccess&&(!g||v.isSuccess)),ue=P.some(e=>B&&(e.aiReferralLandedHits!==null||e.serverPartial!==null)||oe&&(e.ga4Visits!==null||e.ga4Partial!==null)),he=P.find(e=>e.bucket===d.until.slice(0,7)),Se=oe?he?.ga4Partial??null:null,Ce=B?he?.serverPartial??null:null,we=Se!==null||Ce!==null,Te=p.data?.totals,Ee=Te&&{crawlers:qf(Te.crawlerContentHits),fetches:qf(Te.aiUserFetchHits),visits:qf(Te.aiReferralLandedHits)},De=(0,Z.useMemo)(()=>y.reduce((e,t)=>({crawlers:e.crawlers+qf(t.crawlerContentHits),fetches:e.fetches+qf(t.aiUserFetchHits),visits:e.visits+qf(t.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[y]),Oe=Ee??De,ke=Oe.crawlers>0||Oe.fetches>0||Oe.visits>0,Ae=null;if(p.isLoading)Ae=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading AI traffic history…`});else if(p.isError)Ae=(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(!ke){let e=m.data?.sources,t=e!==void 0&&e.length===0,n=!t&&C===null;Ae=(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.`:`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.`:`The window was measured and nothing was recorded. Try a longer range.`})]})}return(0,Q.jsxs)(`div`,{children:[Ae??(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mb-5`,children:(0,Q.jsx)(td,{label:`AI traffic totals`,items:[{label:`AI crawlers`,value:pt(Oe.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:Bf.pageFetches,value:pt(Oe.fetches),detail:D?Bf.pageFetchesOlderDetail:Bf.pageFetchesDetail,tooltip:Bf.pageFetchesTooltip(D?.to??null)},{label:Bf.visitors,value:pt(Oe.visits),detail:T?Bf.visitorsOlderDetail:Bf.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.`+(T?` Days through ${Jr(T.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&&(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:qf(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:qf(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:qf(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`}),Bf.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)(de,{width:`100%`,height:206,children:(0,Q.jsxs)(be,{data:A,margin:Pf,children:[(0,Q.jsx)(ce,{stroke:`var(--chart-grid, #2e2e2e)`,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`bucket`,tick:Xr,stroke:`var(--chart-axis, #2e2e2e)`,tickFormatter:Vr,minTickGap:28}),(0,Q.jsx)(ve,{tick:Xr,stroke:`var(--chart-axis, #2e2e2e)`,width:Ff,allowDecimals:!1,tickFormatter:nt}),(0,Q.jsx)(_e,{contentStyle:ei.contentStyle,labelStyle:ei.labelStyle,itemStyle:ei.itemStyle,labelFormatter:Jr,formatter:O}),S&&(0,Q.jsx)(pe,{x1:S.from,x2:S.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)`}}),n&&D&&(0,Q.jsx)(xe,{x:D.to,stroke:Tf,strokeDasharray:`4 4`,strokeWidth:1.5}),(0,Q.jsx)(me,{wrapperStyle:Nf,iconType:`plainline`,iconSize:14}),(0,Q.jsx)(ge,{type:`monotone`,dataKey:`crawlerContentHits`,name:`Pages crawled`,stroke:xf,fill:xf,fillOpacity:.22,strokeWidth:1.8}),n&&(0,Q.jsx)(ge,{type:`monotone`,dataKey:`aiUserFetchHits`,name:zf,stroke:Sf,fill:Sf,fillOpacity:.18,strokeWidth:1.6}),i&&(0,Q.jsx)(ye,{type:`linear`,dataKey:`crawlTrend`,legendType:`none`,name:`Pages crawled trend`,dot:!1,tooltipType:`none`,stroke:xf,strokeWidth:1.4,strokeDasharray:`5 4`,connectNulls:!0}),i&&n&&(0,Q.jsx)(ye,{type:`linear`,dataKey:`fetchTrend`,legendType:`none`,name:`Page fetches trend`,dot:!1,tooltipType:`none`,stroke:Sf,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)(wu,{windows:Df,value:c,onChange:l,label:`Visits by day or month`,formatOption:e=>e===`months`?`Months`:`Days`}),(0,Q.jsx)(wu,{windows:Ef,value:o,onChange:s,label:`Visit measurement source`,formatOption:e=>e===`ga4`?`GA4`:e===`both`?`Both`:`Server`})]})]}),B&&f.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:Of.serverLoading}),oe&&v.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:Of.gaLoading}),V&&h.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:Of.gaStatusLoading}),V&&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:Of.gaStatusError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":Of.retryGaStatus,disabled:h.isFetching,onClick:()=>{h.refetch()},children:`Retry`})]}),B&&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:Of.serverError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":Of.retryServer,disabled:f.isFetching,onClick:()=>{f.refetch()},children:`Retry`})]}),oe&&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:Of.gaError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,"aria-label":Of.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:Of.connectGa}),se&&le&&!ue&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Of.emptyMonths}),u&&ae&&(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:jf(ae)}),o!==`server`&&re?.month===ae&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:pt(re.sessions??0)}),`visits, GA4`]}),o!==`ga4`&&R!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:pt(R)}),`visits, server`]}),o!==`server`&&z?.changePct!=null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:[z.changePct>0?`▲`:z.changePct<0?`▼`:``,U(Math.abs(z.changePct),et.percent)]}),`trend since `,Af(z.startMonth)]}),o!==`server`&&re?.month===ae&&re.engines[0]&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:pt(re.engines[0].sessions)}),`from `,re.engines[0].label]})]}),we&&he&&(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:[jf(he.bucket),` so far`]}),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, GA4`]}),Ce!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong tabular-nums mr-1`,children:pt(Ce)}),`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?se&&ue:!Ae)&&(0,Q.jsx)(`div`,{className:`flex flex-col gap-3`,children:L.map((e,t)=>{let n=t===L.length-1;return(0,Q.jsx)(np,{source:e,rows:F,monthly:u,height:L.length===1?176:n?134:104,showXAxis:n,showTrend:i,unmeasured:e===`server`?ee:null,older:e===`server`&&ne?te:null},e)})})]})}function ip(e){return e.replace(/\+/g,` `)}var ap=Pn,op={"7d":10080,"30d":43200,"90d":129600,"180d":259200};function sp(e){return Yl(e.landingPage)}var cp=25,lp=10,up={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0,byEngine:{series:[],otherCount:0,days:[]}},dp={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 fp(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 pp(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function mp(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 hp({projectName:e}){let{data:t,isLoading:n,isError:r}=$c(e),i=t?.sources??[];return(0,Q.jsxs)(`section`,{"aria-labelledby":`server-activity-heading`,children:[(0,Q.jsx)(Zu,{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)(V,{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)(V,{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)(rd,{label:`Source`,align:`left`}),(0,Q.jsx)(rd,{label:`Status`,align:`left`}),(0,Q.jsx)(rd,{label:`Crawler hits`,align:`right`}),(0,Q.jsx)(rd,{label:`AI hits`,align:`right`}),(0,Q.jsx)(rd,{label:`AI sessions`,align:`right`}),(0,Q.jsx)(rd,{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:tl(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:il(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?fp(t.lastSyncedAt):`never`}),(0,Q.jsx)(`td`,{className:`py-2 pl-3 text-right`,children:!K()&&(0,Q.jsx)(V,{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 gp({projectName:e}){let[t,n]=(0,Z.useState)(`30d`);return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(hp,{projectName:e}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsx)(jp,{projectName:e,window:t,periodControl:(0,Q.jsx)(wu,{windows:ap,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)(Zu,{id:`ai-traffic-history-heading`,title:`AI traffic history`,tooltip:dp.aiHistoryTooltip}),(0,Q.jsx)(rp,{projectName:e,sinceMinutes:op[t]})]})]})})]})}var _p={session:`Session`,first_user:`First visit`,manual_utm:`UTM`},vp={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)`},yp=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Attribution`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}],bp=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}];function xp(e){return e.engine===null}function Sp({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:vp[e.sourceDimension]??``,children:_p[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:U(e.share)})]})}function Cp({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:ip(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:ip(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:U(e.share)})]})}var wp=[{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`}],Tp=`—`;function Ep({label:e}){return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,title:e,children:Tp}),(0,Q.jsx)(`span`,{className:`sr-only`,children:e})]})}function Dp({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:ip(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:ip(e.medium)}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:e.trafficClass===`paid`?dp.paidClassTitle:dp.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:U(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)(Ep,{label:dp.notMeasured}):e.conversions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.conversionsPerThousandSessionsDisplay})]})}function Op({performance:e}){let t=(0,Z.useMemo)(()=>[{key:`conversions`,label:`Conversions`,help:dp.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)(Ep,{label:dp.notMeasured}):e.conversions.toLocaleString()})},{key:`perThousand`,label:`Per 1,000 sessions`,help:dp.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:dp.tooFewSessions(e.minSessions),children:t.conversionsPerThousandSessionsDisplay})},{key:`rank`,label:`Rank`,help:dp.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:dp.tooFewSessions(e.minSessions),children:dp.notRanked}):(0,Q.jsx)(Ep,{label:dp.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)(sd,{groups:e.platforms,groupLabel:`Platform`,caption:`Social and creator platforms by sessions and conversions`,childColumns:wp,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(Dp,{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:[dp.siteLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:dp.siteScope})]}),(0,Q.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:n.sessions===null?(0,Q.jsx)(Ep,{label:dp.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)(Ep,{label:dp.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:dp.rateReasons[r]})]})}function kp({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)(td,{label:`Social sessions`,items:[{label:`Social sessions`,value:e.sessions.toLocaleString(),detail:`${e.sharePctDisplay} of all sessions`},{label:`Platforms`,value:String(t.length),detail:Pp(i,`source`),tooltip:dp.platformsTooltip},{label:`Paid social`,value:e.paidSessions.toLocaleString(),detail:`${U(e.paidShare)} of social`,tooltip:dp.platformPaidTooltip},{label:`Top platform`,value:n?.label??`None`,detail:n?Pp(n.sessions,`session`):void 0},{label:`Best converting`,value:r?.label??(e.conversionRateAvailable?dp.noneRanked:dp.notMeasured),detail:r?`${r.conversionsPerThousandSessionsDisplay} per 1,000 sessions`:void 0,tooltip:dp.bestConvertingTooltip}]}),(0,Q.jsxs)(Qu,{children:[(0,Q.jsx)($u,{label:dp.socialChartLabel,meta:t.length>0?Pp(e.sessions,`session`):dp.noneInPeriod,children:t.length>0?(0,Q.jsx)(ld,{input:e.daily,label:dp.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noSocial})}),(0,Q.jsx)($u,{label:`Social platforms`,meta:t.length>0?`${Pp(t.length,`platform`)} · ${Pp(i,`source`)}`:dp.noneInPeriod,children:t.length>0?(0,Q.jsx)(Op,{performance:e}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noSocial})})]})]})}function Ap(e,t){let n=L(),[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)(up),[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({...co({client:Y,path:{name:e}}),staleTime:fi});if(r.current)return;if(i(a),!a.connected){o(null),v(up),b([]),S(null),c(!1);return}let s=t===`all`?void 0:t,[l,u,d,f]=await Promise.all([n.fetchQuery({...Bi({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:fi}),n.fetchQuery({...fa({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:fi}).catch(()=>up),n.fetchQuery({...Ui({client:Y,path:{name:e},query:s?{window:s}:void 0}),staleTime:fi}).catch(()=>[]),n.fetchQuery({...ga({client:Y,path:{name:e},query:{window:mr(t)?t:`30d`}}),staleTime:fi}).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 _r(e,mr(t)?Sn[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 li(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 Je(e),await li(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 li(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 jp({projectName:e,window:t,periodControl:n,between:r}){let i=Ap(e,t??`30d`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Mp,{ga:i,projectName:e,periodControl:n}),r,(0,Q.jsx)(Np,{ga:i,projectName:e})]})}function Mp({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()&&!ot(),d=i?mp(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)(gd,{overview:e.overview,refreshing:e.loading}):i?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(td,{label:`Site traffic`,items:[{label:`Total sessions`,value:pp(i.totalSessions),detail:i.totalSessions.toLocaleString()},{label:`Organic sessions`,value:pp(i.totalOrganicSessions),detail:`${i.organicSharePctDisplay} of total`},{label:`Total users`,value:i.totalUsers===null?`n/a`:pp(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()&&!ot()&&(0,Q.jsxs)(q,{variant:`outline`,size:`sm`,disabled:a,onClick:si(s),children:[(0,Q.jsx)(v,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),`Sync from GA4`]})]}):K()||ot()?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Google Analytics 4 property connected.`}):(0,Q.jsx)(Hp,{projectName:t,onConnected:()=>{e.handleConnected()}}),(0,Q.jsxs)(`section`,{"aria-labelledby":`site-traffic-heading`,children:[(0,Q.jsx)(Zu,{id:`site-traffic-heading`,title:`Site traffic`,tooltip:e.overview?dp.siteTrafficTooltip:d?`${dp.siteTrafficFallbackTooltip} Data covers ${d}.`:dp.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:si(s),children:[(0,Q.jsx)(v,{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:si(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 Np({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=Ql({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=>Yl(e.landingPage),pageSize:lp}),u=Ql({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:sp,pageSize:cp}),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?mp(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)(Zu,{id:`traffic-by-channel-heading`,title:`Traffic by channel`,tooltip:dp.channelTooltip,meta:m}),(0,Q.jsx)(td,{label:`Sessions by channel`,items:[{label:`Organic search`,value:h.organic.sharePctDisplay,detail:`${h.organic.sessions.toLocaleString()} sessions`,tooltip:dp.organicTooltip},{label:`Social`,value:h.social.sharePctDisplay,detail:`${h.social.sessions.toLocaleString()} sessions`,tooltip:dp.socialTooltip},{label:`Direct`,value:h.direct.sharePctDisplay,detail:`${h.direct.sessions.toLocaleString()} sessions`,tooltip:dp.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:dp.aiTooltip},{label:`Other channels`,value:h.other.sharePctDisplay,detail:`${h.other.sessions.toLocaleString()} sessions`,tooltip:dp.otherTooltip}]}),(0,Q.jsxs)(Qu,{children:[(0,Q.jsx)($u,{label:dp.aiChartLabel,meta:r.days.length>0?Pp(r.totalSessions,`session`):dp.noneInPeriod,children:r.days.length>0?(0,Q.jsx)(ld,{input:r.byEngine,baseline:d,baselineLabel:`Total sessions`,label:dp.aiChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noAiReferrals})}),(0,Q.jsx)($u,{label:`Where AI visitors came from`,meta:_.length>0?`${Pp(_.filter(e=>e.engine!==null).length,`engine`)} · ${Pp(n.aiReferrals.length,`source`)}`:dp.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)(sd,{groups:_,groupLabel:`Engine`,caption:`AI referral sessions by engine`,childColumns:yp,childRowKey:e=>`${e.source}:${e.medium}:${e.sourceDimension}:${e.trafficClass}`,renderChildCells:e=>(0,Q.jsx)(Sp,{row:e}),pinLast:xp})}),(0,Q.jsx)(X,{text:dp.aiEnginesTooltip})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noAiReferrals})}),(0,Q.jsx)($u,{label:`Pages AI visitors landed on`,meta:x??dp.noneInPeriod,children:n.aiReferralLandingPages.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($l,{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)(nd,{label:`Landing page`,sortKey:`landingPage`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(nd,{label:`Source`,sortKey:`source`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(rd,{label:`Attribution`,align:`left`}),(0,Q.jsx)(nd,{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)(Wp,{row:e},`${e.landingPage}:${e.source}:${e.medium}:${e.sourceDimension}`))})]})}),(0,Q.jsx)(eu,{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:dp.noAiLandingPages})})]})]}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`social-heading`,children:[(0,Q.jsx)(Zu,{id:`social-heading`,title:`Social`,tooltip:b?dp.socialPlatformTooltip:dp.socialTooltip2,meta:m}),b?(0,Q.jsx)(kp,{performance:b}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(td,{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:dp.platformsTooltip},{label:`Paid social`,value:(n.paidSocialSessions??0).toLocaleString(),detail:`${U(n.paidSocialShare??0)} of social`,tooltip:dp.paidSocialTooltip},{label:`Top platform`,value:y?.label??`None`,detail:y?`${y.sessions.toLocaleString()} sessions`:void 0}]}),(0,Q.jsxs)(Qu,{children:[(0,Q.jsx)($u,{label:dp.socialChartLabel,meta:v.length>0?Pp(n.socialSessions,`session`):dp.noneInPeriod,children:v.length>0?(0,Q.jsx)(ld,{input:n.socialPlatformDaily,label:dp.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.noSocial})}),(0,Q.jsx)($u,{label:`Social platforms`,meta:v.length>0?`${Pp(v.length,`platform`)} · ${Pp(n.socialReferrals.length,`source`)}`:dp.noneInPeriod,children:v.length>0?(0,Q.jsx)(sd,{groups:v,groupLabel:`Platform`,caption:`Social sessions by platform`,childColumns:bp,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(Cp,{row:e})}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:dp.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)(Zu,{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)($l,{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)(nd,{label:`Landing page`,sortKey:`landingPage`,current:a.key,dir:a.dir,onSort:f,align:`left`}),(0,Q.jsx)(nd,{label:`Sessions`,sortKey:`sessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(nd,{label:`Organic`,sortKey:`organicSessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(rd,{label:`Organic share`,align:`right`})]})}),(0,Q.jsx)(`tbody`,{children:l.rows.map(e=>(0,Q.jsx)(Up,{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)(eu,{page:l.page,pageSize:l.pageSize,visibleRows:l.rows.length,totalRows:l.totalRows,onPageChange:l.setPage,itemLabel:l.hasQuery?`matches`:`pages`})]})]}),(0,Q.jsx)(Vp,{projectName:t}),(0,Q.jsx)(`p`,{className:`mt-6 text-copy-13 text-secondary`,children:n?.lastSyncedAt?`Last synced ${fp(n.lastSyncedAt)}`:`Never synced`})]})}function Pp(e,t){return`${e.toLocaleString()} ${e===1?t:`${t}s`}`}var Fp=25,Ip=`n/a`,Lp={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 Rp(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 zp(e){return e===null?Ip:e.toFixed(1)}function Bp(e){return e===null?Ip:U(e)}function Vp({projectName:e}){let[t,n]=(0,Z.useState)(`28d`),[r,i]=(0,Z.useState)(`clicks`),[a,o]=(0,Z.useState)(`desc`),s=H({...ji({client:Y,path:{name:e},query:{window:t,limit:vn}}),staleTime:fi}),c=s.data,l=Ql({rows:(0,Z.useMemo)(()=>[...c?.rows??[]].sort((e,t)=>{let n=Rp(e,r),i=Rp(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=>Yl(je(e.landingPage)),pageSize:Fp});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()&&!ot();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:Lp.heading}),(0,Q.jsx)(X,{text:Lp.tooltip})]}),c?.windowStart&&c.windowEnd&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[Qe(c.windowStart),` to `,Qe(c.windowEnd),c.timeZone?` (${c.timeZone})`:``]})]}),(0,Q.jsx)(wu,{windows:Yt,value:t,onChange:e=>{l.setPage(1),n(e)},label:Lp.windowLabel})]}),s.isPending?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary py-6 text-center`,children:Lp.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:Lp.loadError}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>{s.refetch()},children:Lp.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:Lp.notLinkedBadge}),(0,Q.jsx)(X,{text:Lp.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:Lp.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:Lp.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:Lp.thresholdedBadge}),(0,Q.jsx)(X,{text:Lp.thresholded})]}),c.status!==`ready`&&d&&c.syncedAt&&(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[Lp.previousSnapshot,` `,fp(c.syncedAt),`.`]}),c.status===`unavailable`&&d&&(0,Q.jsx)(`p`,{className:`w-full text-copy-14 text-secondary`,children:Lp.unavailableAction})]}),d?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)($l,{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)(nd,{label:`Landing page`,sortKey:`landingPage`,current:r,dir:a,onSort:u,align:`left`}),(0,Q.jsx)(nd,{label:`Clicks`,sortKey:`clicks`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{label:`Impressions`,sortKey:`impressions`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{label:`CTR`,sortKey:`ctr`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{label:`Avg. position`,sortKey:`position`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(nd,{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:[Lp.totalLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:Lp.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:Bp(d.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:zp(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:je(e.landingPage),children:je(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:Bp(e.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:zp(e.organicGoogleSearchAveragePosition)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.activeUsers.toLocaleString()})]},e.landingPage))]})]})}),!xt(d)&&!f&&(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary mt-3 space-y-1`,children:[(0,Q.jsx)(`p`,{children:Lp.noSearchTraffic}),(0,Q.jsx)(`p`,{children:c.searchConsoleLink?.state===`no-search-data`?Lp.noSearchTrafficConfirmed:Lp.noSearchTrafficAction})]}),l.totalRows===0&&l.hasQuery&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-3`,children:c.totalRows>c.rows.length?Lp.noFilterMatchInLoaded(c.rows.length):Lp.noFilterMatch}),(0,Q.jsx)(eu,{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 `,fp(c.syncedAt)]})]}):(0,Q.jsx)(ws,{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:Lp.unavailable}),(0,Q.jsx)(`p`,{children:Lp.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:Lp.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:Lp.neverSynced}),p&&(0,Q.jsx)(`p`,{children:Lp.neverSyncedAction})]})})]})]})]})}function Hp({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 fr(e,{propertyId:n.trim(),keyJson:o});try{await _r(e)}catch{}t()}catch(e){d(e instanceof Error?e.message:`Failed to connect GA4`)}finally{l(!1)}}}return(0,Q.jsxs)(ws,{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)(C,{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:si(m),children:c?`Connecting & syncing…`:`Connect GA4`})]})}function Up({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:U(e.organicShare)})]})}function Wp({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)(Zl,{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:vp[e.sourceDimension]??``,children:_p[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 Gp=new Set([`gbp-listing-discrepancy`,`gbp-lodging-gap`,`gbp-cta-gap`,`gbp-metric-drop`,`gbp-keyword-drop`]),Kp={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.`},qp=`Google Business Profile is not connected yet. Your Canonry team can set this up.`,Jp={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.`},Yp={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 Xp({projectName:e,projectId:t}){let n=L(),[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}=oi(),y=!K()&&!ot(),b=y&&v,x=(0,Z.useRef)(null),S=(0,Z.useRef)(null),C=(0,Z.useRef)(null),w=(0,Z.useRef)(!1),T=H(io({client:Y,path:{name:e}})),E=T.data?.find(e=>e.connectionType===`gbp`),D=!!E,O=r?{locationName:r}:void 0,k=H({...Sa({client:Y,path:{name:e}}),enabled:D}),A=H({...yo({client:Y,path:{name:e},query:O}),enabled:D}),j=H({...va({client:Y,path:{name:e},query:O}),enabled:D}),M=H({...ra({client:Y,path:{name:e},query:O}),enabled:D}),N=H({...hi({client:Y,path:{name:e},query:O}),enabled:D}),P=H({...Ia({client:Y,path:{name:e},query:O}),enabled:D}),ee=H({queryKey:[`gbp-section-insights`,e],queryFn:()=>Kn(e),enabled:D});function te(){li(n,`gbp`)}let ne=oe({...qa(),onSuccess:n=>{Ks({id:n.runId,projectId:t,kind:gr[`gbp-sync`],projectLabel:e,sourceAction:`gbp-sync`}),ci({title:`Business Profile sync started`,detail:`${e} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`gbp-sync:${e}`,dedupeMode:`replace`})}}),F=(0,Z.useSyncExternalStore)(Ms,Qs,Qs),I=Object.values(F.runs).some(e=>e.kind===gr[`gbp-sync`]&&e.projectId===t),re=ne.isPending||I,ie=oe({..._a(),onSuccess:()=>te()}),ae=H({...da({client:Y}),enabled:!T.isLoading&&!D&&b}),R=!!ae.data?.google?.configured,z=D&&k.data!==void 0&&k.data.locations.length===0,B=z&&b,V=H({...ba({client:Y,path:{name:e}}),enabled:B,retry:!1}),se=oe({...vi(),onSuccess:t=>{c(!0),ci({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`})}}),ce=oe({..._o(),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&&ae.isLoading)return;let t=e&&!e.disabled?e:C.current;t&&(w.current=!1,t.focus())});function le(){ce.reset(),g(!1),x.current?.focus()}(0,Z.useEffect)(()=>{z&&c(!0)},[z]);async function ue(){if(!R)m(Kp.credentialsMissing);else{u(!0),m(null),f(null);try{await Ad(e,`gbp`,()=>{f(Kp.refreshing),Promise.all([li(n,`google`),li(n,`gbp`)]).finally(()=>f(null))})===`popup`&&f(Kp.waiting)}catch(e){m(Se(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)(ws,{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)(ds,{ref:S,type:`button`,disabled:l||ae.isLoading,onClick:()=>void ue(),children:l?Kp.connecting:Kp.connect}),!ae.isLoading&&!R?(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:qp}):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 de=A.data,fe=k.data?.locations??[],pe=fe.filter(e=>e.selected),me=j.data?.keywords??[],he=M.data?.lodging??[],ge=N.data?.placeActions??[],_e=P.data?.places??[],ve=fe.length>0?fe[0].accountName:E.domain,ye=r?fe.find(e=>e.locationName===r)?.displayName??null:null,be=r?fe.filter(e=>e.locationName===r):pe,xe=new Set(be.map(e=>e.locationName)),Ce=he.filter(e=>xe.has(e.locationName)),we=ge.filter(e=>xe.has(e.locationName)),Te=_e.filter(e=>xe.has(e.locationName)),Ee=new Set(pe.map(e=>e.locationName)),De=r?me:me.filter(e=>Ee.has(e.locationName)),Oe=!r&&pe.length>1,ke=(ee.data??[]).filter(e=>!e.dismissed&&Gp.has(e.type)&&(!ye||e.query===ye||e.query===r||e.title.startsWith(ye)));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)(ds,{type:`button`,variant:`outline`,size:`sm`,disabled:re,onClick:()=>ne.mutate({client:Y,path:{name:e},body:{}}),children:re?`Syncing…`:`Sync`}),y&&(0,Q.jsx)(ds,{ref:x,type:`button`,variant:`ghost`,size:`sm`,"aria-expanded":h,"aria-controls":`gbp-disconnect-confirm`,disabled:ce.isPending,onClick:()=>{h?le():g(!0)},children:Yp.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:Yp.confirmTitle}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:Yp.confirmBody}),ce.isError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative break-words`,children:Ss(ce.error)}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,Q.jsx)(ds,{type:`button`,variant:`destructive`,size:`sm`,disabled:ce.isPending,onClick:()=>ce.mutate({client:Y,path:{name:e}}),children:ce.isPending?Yp.disconnecting:Yp.confirm}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:ce.isPending,onClick:le,children:Yp.cancel})]})]}),(0,Q.jsxs)(`p`,{className:`mb-4 text-copy-13 text-muted`,children:[ve?(0,Q.jsxs)(Q.Fragment,{children:[`Account `,(0,Q.jsx)(`span`,{className:`font-mono text-secondary`,children:ve}),` · `]}):null,k.data?`${k.data.totalSelected} of ${k.data.totalDiscovered} locations tracked`:`Loading locations…`]}),pe.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`}),pe.map(e=>(0,Q.jsx)(`option`,{value:e.locationName,children:e.displayName},e.id))]})]}),pe.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:z?B?Jp.noneDiscovered:y&&_?Jp.noneDiscoveredDefaultAccount:Jp.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:[ke.length>0&&(0,Q.jsxs)(`div`,{className:`mb-6 grid gap-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Needs attention`}),ke.map(e=>(0,Q.jsx)(`div`,{className:[`surface-card insight-card`,hm(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))]}),de&&(0,Q.jsx)(Cm,{performance:de.performance,freshness:de.freshness,timeseries:de.timeseries}),de?.profileCompleteness&&(0,Q.jsx)($p,{summary:de.profileCompleteness}),be.length>0&&(0,Q.jsx)(em,{locations:be,lodging:Ce,places:Te,placeActions:we,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:[U(j.data.thresholdedPct,et.percent),` privacy-thresholded`]})]}),De.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`}),Oe&&(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:De.slice(0,25).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.keyword}),Oe&&(0,Q.jsx)(`td`,{className:`text-muted`,children:fe.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 (`,fe.length,`)`]}),s&&(0,Q.jsxs)(`div`,{className:`mt-3`,children:[y&&(0,Q.jsx)(Qp,{firstDiscovery:z,chooseAccount:B,accounts:V.data?.accounts??null,accountsLoading:V.isLoading,accountsError:V.error?Se(V.error):null,pending:se.isPending,onDiscover:t=>se.mutate({client:Y,path:{name:e},body:t})}),fe.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:fe.map(t=>(0,Q.jsx)(Zp,{location:t,showAction:!K(),columnCount:K()?3:4,disabled:ie.isPending,onSetSelected:async n=>{await ie.mutateAsync({client:Y,path:{name:e,locationName:t.locationName},body:{selected:n}})}},t.id))})]})]})]})]})})}function Zp({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(Se(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)(ds,{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)(ds,{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 Qp({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:Jp.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:Jp.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:Jp.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)}),Jp.trackNew]}),(0,Q.jsx)(ds,{type:`button`,variant:e?`default`:`outline`,size:`sm`,disabled:a||f,onClick:()=>o(t?{accountName:d,selectAllNew:l}:{selectAllNew:l}),children:a?Jp.discovering:e?Jp.discover:Jp.refresh})]})}function $p({summary:e}){if(e.locationCount===0)return null;let t=e.locationCount,n=[{label:`Description`,value:`${e.withDescription}/${t}`,tone:pm(e.withDescription,t,`caution`)},{label:`Hours`,value:`${e.withHours}/${t}`,tone:pm(e.withHours,t,`caution`)},{label:`Phone`,value:`${e.withPrimaryPhone}/${t}`,tone:pm(e.withPrimaryPhone,t,`caution`)},{label:`Service area`,value:`${e.withServiceArea}/${t}`,tone:pm(e.withServiceArea,t,`neutral`)},{label:`Secondary categories`,value:`${e.withSecondaryCategories}/${t}`,detail:`${e.secondaryCategoryTotal} total`,tone:pm(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 ${mm(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 em({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:_m(e.openStatus)})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(nm,{location:e})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(rm,{lodging:t})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(am,{place:n,mapsUri:e.mapsUri})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(sm,{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)(um,{location:e,lodging:t,place:n,placeActions:r})})})]},e.id)})})]})})]})}function tm(e){return[{label:`Description`,tone:gm(e.description)?`positive`:`neutral`,value:gm(e.description)?`set`:`not returned`},{label:`Hours`,tone:e.regularHours?`positive`:`neutral`,value:e.regularHours?`set`:`not returned`},{label:`Phone`,tone:gm(e.primaryPhone)?`positive`:`neutral`,value:gm(e.primaryPhone)?`set`:`not returned`},{label:`Website`,tone:gm(e.websiteUri)?`positive`:`neutral`,value:gm(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 nm({location:e}){let t=tm(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 rm({lodging:e}){return(0,Q.jsx)(lm,{...im(e)})}function im(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 am({place:e,mapsUri:t}){return(0,Q.jsx)(lm,{...om(e,t)})}function om(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 sm({actions:e}){return(0,Q.jsx)(lm,{...cm(e)})}function cm(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 lm({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 um({location:e,lodging:t,place:n,placeActions:r}){let i=t?xm(t.attributes):[];return(0,Q.jsxs)(`div`,{className:`grid gap-5 text-label-12 lg:grid-cols-3`,children:[(0,Q.jsxs)(dm,{title:`Owner profile · Business Information`,children:[(0,Q.jsx)(fm,{label:`Primary category`,value:e.primaryCategoryDisplayName??`Not returned`}),(0,Q.jsx)(fm,{label:`Secondary categories`,value:e.additionalCategories.length>0?e.additionalCategories.join(`, `):`Not returned`}),(0,Q.jsx)(fm,{label:`Description`,value:gm(e.description)?e.description:`Not returned`}),(0,Q.jsx)(fm,{label:`Hours`,value:e.regularHours?`Returned by Google`:`Not returned`}),(0,Q.jsx)(fm,{label:`Service area`,value:e.serviceArea?`Returned by Google`:`Not returned`}),(0,Q.jsx)(fm,{label:`Phone`,value:e.primaryPhone??`Not returned`}),(0,Q.jsx)(fm,{label:`Website`,value:e.websiteUri??`Not returned`}),(0,Q.jsx)(fm,{label:`Open status`,value:_m(e.openStatus)}),(0,Q.jsx)(fm,{label:`Opening date`,value:e.openingDate??`Not returned`})]}),(0,Q.jsx)(dm,{title:`Hotel data · Lodging API`,children:t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(fm,{label:`Last checked`,value:bm(t.syncedAt)}),(0,Q.jsx)(fm,{label:`Groups returned`,value:String(t.populatedGroupCount)}),(0,Q.jsx)(fm,{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)(dm,{title:`Public listing + CTAs`,children:[n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(fm,{label:`Places tier`,value:n.tier}),(0,Q.jsx)(fm,{label:`Last checked`,value:bm(n.syncedAt)}),(0,Q.jsx)(fm,{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:[vm(e.placeActionType),e.isPreferred?` · preferred`:``]}),(0,Q.jsxs)(`span`,{className:`text-faint`,children:[vm(e.providerType),e.uri?` · ${ym(e.uri)}`:``]})]},e.placeActionLinkName))})})]})]})}function dm({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 fm({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 pm(e,t,n){return e===t?`positive`:e===0?n:`caution`}function mm(e){switch(e){case`positive`:return`text-positive`;case`caution`:return`text-caution`;case`negative`:return`text-negative`;case`neutral`:return`text-neutral`}}function hm(e){return e===`critical`||e===`high`?`insight-card-negative`:e===`medium`?`insight-card-caution`:``}function gm(e){return typeof e==`string`&&e.trim().length>0}function _m(e){return e?vm(e):`Not returned`}function vm(e){return e?e.toLowerCase().split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `):`Unknown`}function ym(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function bm(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}function xm(e){return Object.entries(e).filter(([e,t])=>e!==`name`&&e!==`metadata`&&Sm(t)).map(([e])=>vm(e.replace(/([a-z])([A-Z])/g,`$1_$2`)))}function Sm(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e!=`object`||Object.keys(e).length>0}function Cm({performance:e,freshness:t,timeseries:n}){let r=e.totals,i=De.filter(e=>(r[e]??0)>0),a=At.filter(e=>(r[e]??0)>0),o=Object.keys(r).filter(e=>(r[e]??0)>0&&Ke(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 ${Jr(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)(wm,{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:[Tt(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)(wm,{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=>Tt(e)).join(`, `)]})]})}function wm({data:e,metrics:t,kind:n,firstPending:r,lastDate:i}){return(0,Q.jsx)(`div`,{className:`h-48 w-full`,children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:e,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:Vr,minTickGap:24}),(0,Q.jsx)(ve,{tick:Xr,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(_e,{...ei,labelFormatter:Jr,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),Tt(String(t??``))]}),(0,Q.jsx)(me,{wrapperStyle:{fontSize:12,color:Gr.text},formatter:e=>Tt(e)}),r&&i&&(0,Q.jsx)(pe,{x1:r,x2:i,fill:Gr.surface,fillOpacity:.55,stroke:`none`,label:{value:`pending`,position:`insideTopRight`,fill:Gr.textDim,fontSize:12}}),t.map((e,t)=>n===`line`?(0,Q.jsx)(ye,{type:`monotone`,dataKey:e,stroke:Rr[t%Rr.length],strokeWidth:2,dot:!1,isAnimationActive:!1},e):(0,Q.jsx)(ge,{type:`monotone`,dataKey:e,stackId:`reach`,stroke:Rr[t%Rr.length],fill:Rr[t%Rr.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},e))]})})})}var Tm=25;function Em(e){return typeof window>`u`?e:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,``)??``}${e}`}function Dm(e){return e.toLocaleString()}function Om(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 km(e){let t=e.filter(e=>e.kind===gr[`backlink-extract`]&&!Ps(e.status));return t.length===0?null:t.reduce((e,t)=>e.createdAt>t.createdAt?e:t)}function Am(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 jm({projectName:e}){let t=ot(),[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(null),[o,u]=(0,Z.useState)(null),[d,f]=(0,Z.useState)(null),[p,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([Rt().catch(()=>null),Ge(e,{excludeCrawlers:!0}).catch(()=>null),kt(e,{limit:Tm,offset:b,excludeCrawlers:!0}).catch(e=>{if(e instanceof zn&&e.code===`NOT_FOUND`)return null;throw e}),un(e,{surface:An.backlinks}).catch(()=>null),Ut(e).catch(()=>[])]);f(t),r(n),a(i),u(o);let c=km(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(!p)return;let e=p.id,t=!1,n=async()=>{try{let n=await nr(e);if(t)return;Ps(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)}},[p,O]),(0,Z.useEffect)(()=>{if(!p)return;let e=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(e)},[p]),(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 lr(e);h(t)}catch(e){e instanceof zn&&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??[],j=i?.total??0,N=n?.excludedLinkingDomains??0,P=Math.floor(b/Tm)+1;return(0,Z.useEffect)(()=>{b>0&&b>=j&&x(0)},[b,j]),(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)(ws,{className:`surface-card p-4 mb-4 bg-negative-soft`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:E})}),p&&(0,Q.jsx)(ws,{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)(c,{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:p.status}),(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:[Am(p.startedAt??null,p.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&&!p&&(0,Q.jsx)(ws,{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)(m,{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:Dr(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.`})]})]})}),ee()]});function ee(){return S?(0,Q.jsx)(ws,{className:`surface-card p-6`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading backlinks…`})}):te()}function te(){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`,c=d&&(d.status===`downloading`||d.status===`querying`||d.status===`queued`);return e?ne((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||p!==null,onClick:si(k),children:[(0,Q.jsx)(s,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsx)(Hc,{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:Em(`/backlinks`),children:`Open admin`})})]})):(0,Q.jsx)(ws,{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)(l,{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:Em(`/backlinks`),children:`Set up backlinks`})})})]}),c&&(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:Em(`/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:Em(`/backlinks`),children:`Go to Backlinks admin`})})})]}),a&&!c&&!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||p!==null,onClick:si(k),children:[(0,Q.jsx)(M,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:w?`Queuing…`:`Run extract`]}),(0,Q.jsx)(Hc,{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:Em(`/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:Em(`/backlinks`),children:`Go to Backlinks admin`})}),(0,Q.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:w||p!==null,onClick:si(k),children:[(0,Q.jsx)(M,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsxs)(Hc,{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 ne(e){if(!n)return null;let t=`release`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Mm,{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 `,Om(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)(ws,{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:Dm(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&&j===0?`Every referring domain in this ${t} was a crawler/proxy host (${N} hidden).`:`No referring domains in this ${t}.`})})]})]})}),(0,Q.jsx)(eu,{page:P,pageSize:Tm,visibleRows:A.length,totalRows:j,onPageChange:e=>x((e-1)*Tm)})]}),(0,Q.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:e})]})}}function Mm({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?Ru(o.change,o.unit):void 0,series:o?Bu(o):void 0,formatValue:i,allowDecimals:o?.unit===`fraction`}},s=[o(`referring-domains`,`Referring domains`,`Unique domains linking to ${e.targetDomain}.`,e.totalLinkingDomains,Dm),o(`hosts`,`Total linking hosts`,`Aggregate linking hosts across referring domains.`,e.totalHosts,Dm),o(`top-10-concentration`,`Top-10 concentration`,`Share of linking hosts from the 10 largest linking domains.`,Number(e.top10HostsShare),e=>U(e))],c=s.some(ju),l=a.get(`referring-domains`)?.series??[],u=l[0],d=l.at(-1);return(0,Q.jsx)(Ku,{name:`Backlinks figures`,groups:[{key:`backlinks`,label:`Every release`,basis:i?zu(i.figures):void 0,figures:s}],selected:c?[n]:[],onSelect:r,cadence:`release`,span:c&&u&&d?Vu(u,d):void 0,emptyChartMessage:t?`One release so far. The trend starts with the next one.`:`Release history could not be loaded.`})}var Nm={[G[`keyword-metrics`]]:`Search demand`,[G[`domain-intelligence`]]:`Domain comparison`,[G[`ranked-keywords`]]:`Searches you rank for`,[G[`market-rankings`]]:`Market rankings`,[G[`competitor-discovery`]]:`Organic competitors`,[G[`keyword-gaps`]]:`Search gaps`},Pm={[Mt.shared]:`Shared`,[Mt.missing]:`Missing`,[Mt.outranked]:`Competitor ahead`},Fm=`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.`,Im={[Gt.queued]:`Queued`,[Gt.running]:`Refreshing`,[Gt.completed]:`Completed`,[Gt.partial]:`Partial results`,[Gt.failed]:`Failed`,[Gt.cancelled]:`Cancelled`,[Gt[`reconciliation-required`]]:`Needs review`},Lm=25,Rm=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:1}),zm=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}),Bm=Intl.DateTimeFormat().resolvedOptions().timeZone,Vm=new Intl.DisplayNames([`en`],{type:`language`,fallback:`none`}),Hm=`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`,Um=`px-4 py-3 text-right align-top tabular-nums whitespace-nowrap`,Wm=`min-w-56 px-4 py-3 text-left align-top text-label-14`,Gm=`Position on the page, counting maps and other blocks`,Km={overview:`Overview`,"latest-rankings":`Latest rankings`,...Nm},qm=[G[`market-rankings`],G[`ranked-keywords`],G[`keyword-metrics`],G[`domain-intelligence`],G[`competitor-discovery`],G[`keyword-gaps`]];function Jm(e){return e?.status===Gt.queued||e?.status===Gt.running}function Ym(e){return e.status===Gt.completed||e.status===Gt.partial}function Xm({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?zm.format(e):Rm.format(e)})}function Zm({status:e}){let t=e===Gt.completed?`positive`:e===Gt.failed?`negative`:e===Gt.partial||e===Gt[`reconciliation-required`]?`caution`:`neutral`;return(0,Q.jsx)(J,{tone:t,children:Im[e]})}function Qm(e){let t=Rn(e).split(`/`).at(-1)??e,n=tr.safeParse(t.replaceAll(`_`,`-`));return n.success?Nm[n.data]:t.replaceAll(/[-_]/g,` `)}function $m(e){return e===`mobile`?`phone results`:e===`desktop`?`computer results`:`device not specified by source`}function eh(e){return e.capabilities.includes(G[`market-rankings`])?`Market locations`:`Location ${e.locationCode}`}function th(e){try{return Vm.of(e)??e}catch{return e}}function nh(e){return e.capabilities.includes(G[`market-rankings`])?`searches`:`tasks`}function rh(e){return e.capability!==G[`market-rankings`]||![Gt.queued,Gt.running,Gt.completed].includes(e.status)}function ih(e,t){let n=e.capabilities.includes(G[`market-rankings`]);return`${t} ${t===1?n?`search`:`task`:nh(e)}`}function ah(e,t){return Number.isFinite(Date.parse(e))?Jn(Lt(e,t)):null}var oh={[Gt.failed]:`Latest refresh failed`,[Gt.cancelled]:`Latest refresh cancelled`,[Gt[`reconciliation-required`]]:`Latest refresh needs review`};function sh(e,t){let n=e&&e.id!==t?.id?oh[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=`${ih(t,t.failedTasks)} failed`,n=t.capabilities.includes(G[`market-rankings`])?`Their queries show as Failed.`:`Open Refresh history for details.`;return{label:e,text:`${e}: ${t.failedTasks} of ${ih(t,t.taskCount)} in this refresh returned no results. ${n}`}}return t.status===Gt.partial?{label:`Partial results`,text:`Partial results: ${t.error??`some ${nh(t)} returned only part of their results or did not run. Open Refresh history for details.`}`}:null}function ch({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:Qm(e.dataset)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Search engine`}),(0,Q.jsxs)(`dd`,{children:[`Google · `,$m(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:Fn(e.collectedAt,Bm)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Source updated`}),(0,Q.jsx)(`dd`,{children:e.sourceUpdatedAt?Qe(e.sourceUpdatedAt):`Not supplied`})]})]})}function lh({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)(h,{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)(ch,{source:t})]})]})}function uh({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:Ss(e)}),(0,Q.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:t,children:`Retry`})]})}function dh({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 fh(e,t){return!e||!t?.supported?[]:qm.filter(n=>e.capabilities.includes(n)&&(t.capabilities?.includes(n)??!0))}function ph({projectName:e}){let{isAdmin:t}=oi(),n=R({strict:!1}),r=ae(),i=H(ya({client:Y,path:{name:e}})),a=H(po({client:Y,path:{name:e}})),s=H({...Ea({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()&&!ot(),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)(uh,{error:i.error,retry:()=>{i.refetch()}});if(a.error)return(0,Q.jsx)(uh,{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=>fh(t,e)))),S=G[`market-rankings`],C=b&&[...x].some(e=>e!==S),w=b&&x.has(S),T=g&&(C||g.rankings&&w),E=t&&!K()&&!ot()?(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:`${Hm} 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)(Dd,{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!==ft.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)(dg,{projectName:e,context:i.data,profile:c.profile,id:c.id,onClose:y,onSaved:e=>_(e,!0)},c.id),!ot()&&!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)(uh,{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)(dh,{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)(mh,{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)(dh,{title:`No SEO profiles yet`,children:`Set up market rankings with the CLI or API.`}):(0,Q.jsx)(dh,{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)(dh,{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)(dh,{title:`Profile unavailable`,children:`This saved profile is no longer available. Select another profile to view its data.`}):!c&&(0,Q.jsx)(dh,{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 mh({projectName:e,profile:t,context:n,selectedRunId:r,onLatest:i}){let a=L(),o=R({strict:!1}),s=ae(),l=(0,Z.useRef)(null),u=(0,Z.useRef)(null),[d,f]=(0,Z.useState)(!1),[p,m]=(0,Z.useState)(null),g=(0,Z.useRef)(null),_=(0,Z.useRef)(null),y={name:e},b=to({client:Y,path:y,query:{profileId:t.id,runId:r}}),x=H({...b,refetchInterval:e=>Jm(e.state.data?.latestRun)?2e3:!1}),S=oe({...xi({client:Y}),meta:{skipGlobalErrorToast:!0}}),C=oe({...Fi({client:Y}),meta:{skipGlobalErrorToast:!0}}),w=x.data?.latestRun,T=x.data?.evidenceRun,E=x.data?.evidenceRun?.capabilities??t.capabilities,D=[`overview`,...qm.filter(e=>E.includes(e))],O=o.seoRegion||o.seoMarket||o.seoShow||o.seoSort||o.seoQ,k=!r&&O&&E.includes(G[`market-rankings`])?G[`market-rankings`]:`overview`,A=o.seoView===`latest-rankings`?o.seoView:D.find(e=>e===o.seoView),M=A??k,N=o.seoView===`activity`||!(!r||A),P=d||N,ee=()=>{f(!1),N&&r?i():N&&s({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoView:void 0}),replace:!0})},te=t=>{f(!1),s({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})})},ne=(t,n=!1)=>{n&&l.current?.querySelector(`[data-seo-view="${t}"]`)?.focus();let i=t===G[`market-rankings`]?{}:{seoRegion:void 0,seoMarket:void 0,seoShow:void 0,seoSort:void 0,seoQ:void 0};s({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...i,seoView:t===`overview`&&!r?void 0:t})})},F=Jm(w),I=S.isPending||C.isPending,re=n.access.canRun&&!K()&&!ot(),ie=n.connections.find(e=>e.id===t.connectionId),z=n.scopes.find(e=>e.kind===t.scope.kind&&e.key===(t.scope.key??null)),B=H({...Gi({client:Y,path:y,query:{kind:In[`seo-sync`]}}),retry:!1}),V=!B.isError&&B.data?.enabled&&B.data.nextRunAt?B.data.nextRunAt:null,se=V?ah(V,B.data?.timezone??`UTC`):null,ce=T?.finishedAt&&Ym(T)?ah(T.finishedAt,Bm):null,le=re&&ie&&(t.capabilities.includes(G[`market-rankings`])?`Refresh now runs new Google searches through ${ie.label} for this profile’s tracked queries and markets.`:`Refresh now requests the latest data available from ${ie.label}. The source may return the same readings until its dataset updates.`),ue=[ce&&`Last refresh shows when Canonry saved these results.`,se&&`Next scheduled refresh ${se}.`,le].filter(Boolean).join(` `),de=F?null:sh(w,T);return(0,Z.useEffect)(()=>{w&&(Jm(w)?_.current=w.id:_.current===w.id&&(_.current=null,li(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:ce&&T?.finishedAt?(0,Q.jsxs)(Q.Fragment,{children:[r?`Viewing saved results from`:`Last refresh`,` `,(0,Q.jsx)(`time`,{dateTime:T.finishedAt,title:Fn(T.finishedAt,Bm)??void 0,children:ce})]}):`No saved results`}),!r&&ue&&(0,Q.jsx)(X,{placement:`bottom`,text:`About refreshes. ${ue}`}),F&&w&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),w.cancelRequested?`Cancellation requested`:Im[w.status],` · `,w.completedTasks,` of `,w.taskCount,` `,nh(w),` completed`]}),de&&(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:de.label,text:de.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)(j,{className:`size-4`,"aria-hidden":`true`}),`Refresh history`]}),r?(0,Q.jsx)(q,{variant:`secondary`,onClick:i,children:`View latest data`}):re&&(0,Q.jsxs)(q,{disabled:I||F||!x.data||!n.available||!ie,onClick:si(async()=>{if(!(!re||r||F||I)){m(null);try{if(!g.current){let e=await S.mutateAsync({path:y,body:{profileId:t.id}});if(e.availability!==jt.ready){m(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,Jm(n)&&(_.current=n.id,Ks({id:n.id,projectId:n.projectId,projectName:e,projectLabel:e,kind:gr[`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){Cs(e).code===`VALIDATION_ERROR`&&(g.current=null),m(Ss(e))}}}),children:[(0,Q.jsx)(v,{"aria-hidden":`true`,className:`size-4 ${I?`motion-safe:animate-spin`:``}`}),I?`Starting refresh…`:F?`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.`,re&&n.available&&ie&&` Refresh to use the current settings.`]}),!ot()&&z&&!z.supported&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:z.reason??`This scope is not supported for domain data.`}),x.isRefetchError&&(0,Q.jsx)(uh,{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:()=>ne(e),children:Km[e]},e)})}),x.isLoadingError?(0,Q.jsx)(`div`,{className:`pt-4`,children:(0,Q.jsx)(uh,{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)(Sh,{projectName:e,profileId:t.id,data:x.data,active:F,canRun:re,nextRefresh:se,snapshot:!!r||M===`latest-rankings`,historical:!!r,onOpen:e=>ne(e,!0)}):(0,Q.jsx)(kh,{projectName:e,profileId:t.id,runId:x.data.evidenceRunId,view:M,active:F,nextRefresh:se},`${t.id}:${M}:${x.data.evidenceRunId??`empty`}`)]}),(0,Q.jsx)(_c,{title:`Refresh history`,subtitle:t.name,open:P,onClose:ee,onCloseAutoFocus:e=>{let t=u.current;t?.isConnected&&!(N&&r)&&(e.preventDefault(),t.focus())},children:P&&(0,Q.jsx)(ug,{projectName:e,profileId:t.id,canRun:re,selectedRunId:r,exactRefresh:N&&!!r,onViewSaved:te,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)(h,{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: `,ot()?`Fictional demo data`:ie?.label??`Source unavailable`,`. Google · `,$m(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}`,`. `,eh(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)(ch,{source:x.data.summary.provenance})]})]})]})}var hh=6,gh=new Intl.DateTimeFormat(`en-US`,{month:`short`,year:`numeric`,timeZone:`UTC`}),_h=new Intl.DateTimeFormat(`en-US`,{month:`short`,year:`2-digit`,timeZone:`UTC`}),vh=new Intl.NumberFormat(`en-US`,{notation:`compact`,maximumFractionDigits:1}),yh=[{days:180,label:`180 days`},{days:90,label:`90 days`},{days:30,label:`30 days`}],bh={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 xh({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===mn.market,p=t.kind===mn.ranked,m=Oe[t.kind],h=m.map(e=>{let n=t.points.filter(t=>t[e]!=null).at(-1)?.[e]??null;return{...bh[e],key:e,value:n===null?`—`:Rm.format(n),stateValue:n===null,interactive:!0,change:Ru(t.changes[e]??null,or.count),series:t.points.map(t=>({date:t.observedAt,current:t[e]??null})),formatValue:e=>p?Rm.format(e):vh.format(e),formatExact:e=>Rm.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&&Th(t.target),`Google`,f?`Market locations`:null,t.languageCode&&th(t.languageCode)].filter(Boolean).join(` · `),b=(a?i??t.keyword:t.keyword)??``,x=t.rankedKeywords??[],S=b!==``&&!x.includes(b);Ws(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?Vu({date:C,observedAt:C},{date:w,observedAt:w}):void 0,E=t.points.filter(e=>e[_]!=null),D=E.length,k=E.at(-1),A=k?ah(k.observedAt,Bm):null,j=k&&k!==t.points.at(-1),M=m.length>1?zu(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,ee=[A&&j&&`Data through ${A}.`,T&&`Chart dates ${T}.`,D>=2&&`${Rm.format(D)} comparable refreshes.`,D===1&&A&&!j&&`Reading from ${A}.`,M&&`Change ${M}.`,t.marketQueryCount!==null&&`${Rm.format(t.marketQueryCount)} non-brand queries across markets.`,!f&&t.locationCode!==null&&`Search location code ${t.locationCode}.`].filter(Boolean).join(` `),te=D===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.`,ne=e=>{let t=Hn.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}),ee&&(0,Q.jsx)(X,{placement:`bottom`,text:`About this chart. ${ee}`})]}),(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:`${Hm} 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)(Ku,{name:v,groups:[{key:`seo`,figures:h,basis:M}],selected:[_],onSelect:e=>{let t=sn.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:te,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:`${Hm} min-w-28 sm:min-h-9`,"aria-label":`SEO trend range`,"aria-busy":u,value:n,onChange:e=>ne(e.target.value),children:yh.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)(O,{className:`size-4`,"aria-hidden":`true`})]})]})})})]})}function Sh({snapshot:e=!1,historical:t=!1,...n}){let r=R({strict:!1}),i=ae(),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===G[`domain-intelligence`]||e===G[`market-rankings`]||e===G[`ranked-keywords`])===!0,m=ho({client:Y,path:{name:u},query:{profileId:d,days:a,keyword:o}}),h=(0,Z.useRef)(void 0),g=H({...m,enabled:!e&&p,placeholderData:re});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)(Dh,{...n},l.evidenceRunId??`empty`)]});if(!p)return(0,Q.jsx)(Dh,{...n},l.evidenceRunId??`empty`);let _=g.data??h.current;if(g.error&&!_)return(0,Q.jsx)(`div`,{className:`pt-4`,children:(0,Q.jsx)(uh,{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??Oe[v].some(e=>_.points.some(t=>t[e]!=null)))&&v!==mn.market&&!(v===mn.ranked&&o)&&(l.keywordMetricsCount>0||l.rankedKeywordCount>0))return(0,Q.jsx)(Dh,{...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)(xh,{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}),Et(`window`)},onMetricChange:e=>{y({seoTrendMetric:e}),Et(`other`)},onKeywordChange:e=>{y({seoTrendKeyword:e||void 0}),Et(`other`)}}),g.error&&(0,Q.jsx)(uh,{error:g.error,retry:()=>{g.refetch()}})]})}function Ch({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?`—`:Rm.format(e.value)})),g=new Map(i.map(e=>[e.label,e.tick??e.label])),_=e=>vh.format(e),v=e=>g.get(e)??e,y=(0,Q.jsx)(_e,{...ei,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`?Rm.format(e):`—`),r]}}),b=Rr[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)(de,{width:`100%`,height:c?220:i.length*38+34,children:c?(0,Q.jsxs)(he,{data:h,accessibilityLayer:!1,margin:{top:12,right:12,bottom:2,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`label`,tick:Xr,tickFormatter:v,tickLine:!1,axisLine:!1,minTickGap:16}),(0,Q.jsx)(ve,{tick:Xr,tickFormatter:_,tickLine:!1,axisLine:!1,allowDecimals:!1,width:46}),y,(0,Q.jsx)(se,{dataKey:`plotted`,fill:b,maxBarSize:46,minPointSize:1,radius:[3,3,0,0],isAnimationActive:!1})]}):(0,Q.jsxs)(be,{data:h,layout:`vertical`,accessibilityLayer:!1,margin:{top:3,right:58,bottom:2,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,horizontal:!1}),(0,Q.jsx)(ve,{type:`category`,dataKey:`label`,tick:Xr,tickFormatter:v,tickLine:!1,axisLine:!1,width:a===G[`domain-intelligence`]?48:112,interval:0}),(0,Q.jsx)(fe,{type:`number`,tick:Xr,tickFormatter:e=>l&&e<1?``:_(e),tickLine:!1,axisLine:!1,allowDecimals:!1,domain:l?[1,`auto`]:[0,`auto`]}),y,l?(0,Q.jsx)(ye,{dataKey:`plotted`,stroke:`none`,dot:{r:5,fill:b,stroke:b},activeDot:!1,isAnimationActive:!1,children:(0,Q.jsx)(le,{dataKey:`display`,position:`right`,fill:Xr.fill,fontSize:12})}):(0,Q.jsxs)(se,{dataKey:`plotted`,fill:b,barSize:18,minPointSize:1,radius:[0,3,3,0],isAnimationActive:!1,children:[h.map((e,t)=>(0,Q.jsx)(ue,{fill:e.value===null?`transparent`:b},`${e.label}:${t}`)),(0,Q.jsx)(le,{dataKey:`display`,position:`right`,fill:Xr.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 ${Nm[a]}`,onClick:()=>o(a),children:[Nm[a],(0,Q.jsx)(O,{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)(Xm,{value:e.value})})]},`${e.label}:${t}`))})]})})]})}function wh(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 Th(e){return`${e.value} · ${e.includeSubdomains?`includes subdomains`:`exact host`}`}function Eh({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)(Xm,{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)(Xm,{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)(Xm,{value:e.estimatedOrganicTraffic})})]})]})}function Dh({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=H({...vo(d),enabled:p}),g=H({...Ca({...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?wh(v):[],b=y.some(e=>e.value!==null),x=f&&!p&&!b&&(!m||g.isSuccess)&&n.rankedKeywordCount>0,S=H({...Wa({...d,query:{...d.query,limit:hh}}),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,E=H({...gi({...d,query:{...d.query,limit:Lm,offset:(s-1)*Lm}}),enabled:T}),D=p?h:m&&!g.isSuccess?g:x&&!S.isSuccess?S:T?E:null,k;if(D?.error)k=(0,Q.jsx)(uh,{error:D.error,retry:()=>{D.refetch()}});else if(D?.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)(Ch,{title:`Google rank across markets`,caption:`Non-brand queries · ${eg(e)}`,category:`Outcome`,unit:`Queries`,points:ar(t,e).map(t=>({label:t.label,value:e[t.count]})),view:G[`market-rankings`],onOpen:o})}else if(v&&b)k=(0,Q.jsx)(Ch,{title:`Organic positions in the top 20`,caption:`${Th(v.target)} · Google · Location ${v.provenance.locationCode} · ${v.provenance.languageCode}`,category:`Position`,unit:`Ranking searches`,points:y,view:G[`domain-intelligence`],onOpen:o});else if(x&&w)k=(0,Q.jsx)(Ch,{title:`Organic positions for saved searches`,caption:`First ${C.length} of ${Rm.format(n.rankedKeywordCount)} saved results · Google`,category:`Search and target`,unit:`Organic position`,rankAxis:!0,view:G[`ranked-keywords`],onOpen:o,points:C.map(e=>({label:`${e.keyword} · ${Th(e.target)}`,tick:Oh(e.keyword),value:e.rankOrganic}))});else if(T&&E.data?.items.length){let e=E.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:gh.format(t),tick:_h.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:`${Hm} min-w-0 sm:max-w-96`,value:e.indexOf(t),onChange:e=>{u(Number(e.target.value)),Et(`other`)},children:e.map((e,t)=>(0,Q.jsx)(`option`,{value:t,children:e.keyword},`${e.keyword}:${t}`))})]}),E.data.total>Lm&&(0,Q.jsx)(eu,{page:s,pageSize:Lm,visibleRows:e.length,totalRows:E.data.total,disabled:E.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)(Ch,{title:`Monthly search demand`,caption:a,category:`Month`,unit:`Estimated searches`,points:n,monthAxis:!0,view:G[`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)(Ch,{title:`Search demand estimate`,caption:a,category:`Search`,unit:`Estimated monthly searches`,points:[{label:t.keyword,tick:Oh(t.keyword),value:t.searchVolume}],view:G[`keyword-metrics`],onOpen:o,controls:i})}else{let e=qm.find(e=>n.evidenceRun?.capabilities.includes(e));k=(0,Q.jsxs)(`div`,{className:`material-base`,children:[(0,Q.jsx)(dh,{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 ${Km[e]}`,onClick:()=>o(e),children:[Km[e],(0,Q.jsx)(O,{className:`size-4`,"aria-hidden":`true`})]})})]})}return(0,Q.jsxs)(`div`,{className:`space-y-4 pt-4`,children:[k,n.summary&&(0,Q.jsx)(Eh,{summary:n.summary})]})}function Oh(e){return e.length>16?`${e.slice(0,15)}…`:e}function kh({projectName:e,profileId:t,runId:n,view:r,active:i,nextRefresh:a}){return r===G[`market-rankings`]?n?(0,Q.jsx)($h,{projectName:e,profileId:t,runId:n,active:i}):(0,Q.jsx)(dh,{title:`No market rankings yet`,children:a?`First refresh ${a}`:`Refresh this profile to rank its tracked queries in each market.`}):(0,Q.jsx)(Ah,{projectName:e,profileId:t,runId:n,view:r,active:i})}function Ah({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:Lm,offset:(a-1)*Lm}},m=H({...Wa(p),enabled:!!n&&r===G[`ranked-keywords`]}),h=H({...gi(p),enabled:!!n&&r===G[`keyword-metrics`]}),g=H({...Ca(p),enabled:!!n&&r===G[`domain-intelligence`]}),_=H({...xa({...p,query:{...p.query,sort:l}}),placeholderData:re,enabled:!!n&&r===G[`competitor-discovery`]}),v=H({...ia({...p,query:{...p.query,kind:s||void 0,sort:d}}),placeholderData:re,enabled:!!n&&r===G[`keyword-gaps`]}),y=r===G[`ranked-keywords`]?m:r===G[`keyword-metrics`]?h:r===G[`competitor-discovery`]?_:r===G[`keyword-gaps`]?v:g;return n?(0,Q.jsxs)(`div`,{className:`space-y-3 pt-4`,children:[r===G[`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:`${Hm} 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:Mt.missing,children:`Missing`}),(0,Q.jsx)(`option`,{value:Mt.shared,children:`Shared`}),(0,Q.jsx)(`option`,{value:Mt.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===G[`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)(uh,{error:y.error,retry:()=>{y.refetch()}}):y.data?y.data.items.length===0?(0,Q.jsx)(dh,{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":`${Nm[r]} table`,"aria-busy":y.isFetching,tabIndex:0,children:[r===G[`ranked-keywords`]&&m.data&&(0,Q.jsx)(Fh,{rows:m.data.items}),r===G[`keyword-metrics`]&&h.data&&(0,Q.jsx)(Ih,{rows:h.data.items}),r===G[`domain-intelligence`]&&g.data&&(0,Q.jsx)(Lh,{rows:g.data.items}),r===G[`competitor-discovery`]&&_.data&&(0,Q.jsx)(Nh,{rows:_.data.items,sort:l,onSort:e=>{u(e),o(1)}}),r===G[`keyword-gaps`]&&v.data&&(0,Q.jsx)(Ph,{rows:v.data.items,sort:d,onSort:e=>{f(e),o(1)}})]}),(0,Q.jsx)(eu,{page:a,pageSize:Lm,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 `,Nm[r].toLowerCase(),`…`]})]}):(0,Q.jsxs)(dh,{title:`No saved data yet`,children:[`Refresh this profile to collect `,Nm[r].toLowerCase(),` for its saved scope.`]})}function jh({value:e}){return e===null?(0,Q.jsx)(Xm,{value:null}):(0,Q.jsxs)(Q.Fragment,{children:[e>0?`+`:``,Rm.format(e)]})}function Mh({label:e,sort:t,ascending:n,descending:r,align:i=`right`,onSort:a,help:o}){return(0,Q.jsx)(Qh,{label:e,align:i,sorted:t===n?`ascending`:t===r?`descending`:null,onSort:()=>a(t===n?r:n),help:o,showUnsorted:!0})}function Nh({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)(Mh,{label:`Competitor`,align:`left`,sort:t,ascending:Dt.domain,descending:Dt[`-domain`],onSort:n}),(0,Q.jsx)(Mh,{label:`Shared searches`,sort:t,ascending:Dt.shared,descending:Dt[`-shared`],onSort:n}),(0,Q.jsx)(Mh,{label:`Avg. position`,sort:t,ascending:Dt.position,descending:Dt[`-position`],onSort:n}),(0,Q.jsx)(Mh,{label:`Est. organic traffic`,sort:t,ascending:Dt.traffic,descending:Dt[`-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:Wm,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:Um,children:(0,Q.jsx)(Xm,{value:e.sharedKeywords})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.averagePosition})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(lh,{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)(Xm,{value:e.organicKeywords})]}),(0,Q.jsxs)(`p`,{children:[`Target: `,e.target.value,` · includes subdomains`]})]})})]},`${e.target.value}:${e.domain}:${t}`))})]})}function Ph({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)(Mh,{label:`Search`,align:`left`,sort:t,ascending:He.keyword,descending:He[`-keyword`],onSort:n}),(0,Q.jsx)(Mh,{label:`Comparison`,align:`left`,sort:t,ascending:He.kind,descending:He[`-kind`],onSort:n}),(0,Q.jsx)(Mh,{label:`Your rank`,sort:t,ascending:He[`target-rank`],descending:He[`-target-rank`],onSort:n}),(0,Q.jsx)(Mh,{label:`Competitor rank`,sort:t,ascending:He[`competitor-rank`],descending:He[`-competitor-rank`],onSort:n}),(0,Q.jsx)(Mh,{label:`Rank gap`,sort:t,ascending:He[`rank-gap`],descending:He[`-rank-gap`],onSort:n,help:Fm}),(0,Q.jsx)(Mh,{label:`Monthly searches`,sort:t,ascending:He.volume,descending:He[`-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:Wm,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===Mt.shared?`neutral`:`caution`,children:Pm[e.kind]})}),(0,Q.jsx)(`td`,{className:Um,children:e.kind===Mt.missing?(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Not found`}):(0,Q.jsx)(Xm,{value:e.targetRankOrganic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.competitorRankOrganic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(jh,{value:e.rankGap})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(lh,{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)(Xm,{value:e.keywordDifficulty})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(Xm,{value:e.cpcUsd,currency:!0})]})]})})]},`${e.target.value}:${e.competitor.value}:${e.keyword}:${t}`))})]})}function Fh({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:`${Um} text-label-13-strong`,children:`Position`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:`Est. traffic`}),(0,Q.jsx)(`th`,{className:`${Um} 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:Wm,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)(Zl,{value:e.url??e.target.value})})]}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.rankOrganic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.estimatedTraffic})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.keywordDifficulty})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(lh,{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:[Gm,`: `,(0,Q.jsx)(Xm,{value:e.rankAbsolute})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(Xm,{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 Ih({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:`${Um} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:`CPC`}),(0,Q.jsx)(`th`,{className:`${Um} 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:`${Wm} text-primary`,children:e.keyword}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.cpcUsd,currency:!0})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{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)(lh,{label:e.keyword,source:e.provenance,children:[(0,Q.jsxs)(`p`,{children:[`Ad competition: `,e.adCompetition===null?`Not supplied`:U(e.adCompetition,et.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)(Xm,{value:e.searchVolume})})]},`${e.year}-${e.month}`))})]})})]},`${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:`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:`${Um} text-label-13-strong`,children:`Searches ranked for`}),(0,Q.jsx)(`th`,{className:`${Um} 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:Wm,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:Um,children:(0,Q.jsx)(Xm,{value:e.organicKeywords})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsx)(lh,{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)(Xm,{value:e.top1})}),(0,Q.jsx)(`dt`,{children:`Positions 2–3`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.top2To3})}),(0,Q.jsx)(`dt`,{children:`Positions 4–10`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.top4To10})}),(0,Q.jsx)(`dt`,{children:`Positions 11–20`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.top11To20})}),(0,Q.jsx)(`dt`,{children:`Est. traffic value`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(Xm,{value:e.estimatedOrganicTrafficValueUsd,currency:!0})})]})})})]},`${e.target.value}:${t}`))})]})}var Rh=5,zh=10,Bh=`all`;function Vh(e){return e===Bh?Bh:Xn.safeParse(e).data??null}var Hh={column:`ranks11To20`,descending:!0},Uh={3:`sm:grid-cols-3`,4:`sm:grid-cols-4`,5:`sm:grid-cols-5`},Wh=`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`,Gh=`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 Kh(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 qh(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 Jh(e){let t=e.filter(e=>e.kind===qn.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 Yh(e,t){return e.counts[t]}function Xh(e){let t=e.descending?-1:1,n=e.column;return n===`label`?(e,n)=>t*(dt(e.label,n.label)||dt(e.key,n.key)):(e,r)=>t*(Yh(e,n)-Yh(r,n))||dt(e.label,r.label)||dt(e.key,r.key)}function Zh(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 Qh({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:`${Wh} ${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 $h({projectName:e,profileId:t,runId:n,active:r}){let i=R({strict:!1}),a=ae(),o=i.seoRegion,s=i.seoMarket,c=Vh(i.seoShow),l=Cn.safeParse(i.seoSort).data??It.rank,u=t=>{a({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...t}),replace:!0})},d=(0,Z.useId)(),f=H(vo({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)(uh,{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)(ng,{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)(dh,{title:`No rankings here`,children:[`This refresh has no rankings for this `,s===void 0?`region`:`market`,`.`]}):(0,Q.jsx)(dh,{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=ar(m,p),b=c??(p.needsWork>0?tt[`needs-work`]:Bh),x=h.length>1||h.some(e=>e.kind===qn.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:eg(p)})]}),(0,Q.jsxs)(`dl`,{className:`grid grid-cols-2 gap-5 border-b border-subtle pb-5 ${Uh[y.length+1]??`sm:grid-cols-5`}`,children:[y.map(e=>(0,Q.jsx)(tg,{label:e.label,help:Kh(e,m),value:p[e.count]},e.count)),(0,Q.jsx)(tg,{label:`Rival ahead`,help:qh(m),value:p.rivalAhead,className:`sm:border-l sm:border-subtle sm:pl-5`})]})]}),x&&(0,Q.jsx)(rg,{projectName:e,groups:h,bands:y},`groups\u0000${g}`),(0,Q.jsx)(ig,{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===It.rank?void 0:e}),urlQ:i.seoQ??``,onQ:e=>u({seoQ:e||void 0}),onClear:()=>u({seoShow:Bh,seoQ:void 0})},`queries\u0000${g}`)]})}function eg(e){return[`${Rm.format(e.queries)} ${e.queries===1?`query`:`queries`}`,...e.partlyChecked>0?[`${Rm.format(e.partlyChecked)} partly checked`]:[],...e.failed>0?[`${Rm.format(e.failed)} failed`]:[],...e.cancelled>0?[`${Rm.format(e.cancelled)} not searched`]:[]].join(` · `)}function tg({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:Rm.format(n)})]})}function ng({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)(V,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoView:G[`market-rankings`],seoRegion:void 0,seoMarket:void 0}),className:Gh,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)(V,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoMarket:void 0}),className:Gh,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 rg({projectName:e,groups:t,bands:n}){let r=ae(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(1),c=Jh(t),l=(i===null?t:[...t].sort(Xh(i))).slice((o-1)*Rh,o*Rh),u=i??(n.some(e=>e.count===Hh.column)?Hh: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??Hh;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,m=e=>e.kind===qn.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)(Qh,{label:c.label,align:`left`,sorted:p(`label`),onSort:()=>f(`label`)}),d.map(e=>(0,Q.jsx)(Qh,{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:m(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)(V,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:m(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:Um,children:Rm.format(t.counts[e.column])},e.column)),(0,Q.jsx)(`td`,{className:`px-4 py-3 text-right align-top`,children:(0,Q.jsx)(h,{"aria-hidden":`true`,className:`ml-auto size-4 text-muted`})})]},`${t.kind}:${t.key}`))})]})}),(0,Q.jsx)(eu,{page:o,pageSize:Rh,visibleRows:l.length,totalRows:t.length,onPageChange:s,itemLabel:c.plural,className:`text-label-13 [&_button]:min-h-11`})]})}function ig({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=Zh(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=H({...Fa({client:Y,path:{name:e},query:{profileId:t,runId:n,regionKey:r,marketKey:i,outcome:c===Bh?void 0:c,q:v||void 0,sort:u,limit:zh,offset:(C-1)*zh}}),placeholderData:re}),T=[{value:tt[`needs-work`],label:`Needs work`,count:a.needsWork},...o.map(e=>({value:e.filter,label:e.label,count:a[e.count]})),{value:tt[`rival-ahead`],label:`Rival ahead`,count:a.rivalAhead},{value:tt[`partly-checked`],label:`Partly checked`,count:a.partlyChecked},{value:tt.failed,label:`Failed`,count:a.failed},{value:tt.cancelled,label:`Not searched`,count:a.cancelled},{value:Bh,label:`All`,count:a.queries}],E=[tt[`partly-checked`],tt.failed,tt.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===It.rank?`ascending`:u===It[`-rank`]?`descending`:null,A=u===It.query?`ascending`:u===It[`-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`:`${Rm.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:`${Hm} min-w-0 sm:w-56`,children:D.map(e=>(0,Q.jsxs)(`option`,{value:e.value,children:[e.label,` (`,Rm.format(e.count),`)`]},e.value))})]}),(0,Q.jsx)($l,{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)(uh,{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)(Qh,{label:`Query`,align:`left`,sorted:A,onSort:()=>d(u===It.query?It[`-query`]:It.query)}),(0,Q.jsx)(Qh,{label:`Google rank`,align:`right`,sorted:k,onSort:()=>d(u===It.rank?It[`-rank`]:It.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:`${Um} text-label-13-strong`,children:`Rival rank`}),(0,Q.jsx)(`th`,{className:`${Um} text-label-13-strong`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Rank gap`,(0,Q.jsx)(X,{text:Fm,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)(ag,{row:e,requested:s},`${e.marketKey}\u0000${e.queryId??e.queryText}\u0000${t}`))})]})}),(0,Q.jsx)(eu,{page:C,pageSize:zh,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 ag({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:Wm,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:Um,children:(0,Q.jsx)(sg,{row:e,requested:t})}),(0,Q.jsx)(`td`,{className:`px-4 py-3 align-top text-label-13`,children:(0,Q.jsx)(cg,{row:e})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(Xm,{value:e.topCompetitor?.rankOrganic??null})}),(0,Q.jsx)(`td`,{className:Um,children:(0,Q.jsx)(jh,{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)(lg,{row:e,requested:t})})})]})}function og(e){return e.outcome===Ze.failed||e.outcome===Ze.cancelled}function sg({row:e,requested:t}){return e.outcome===Ze.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===Ze.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===Ze[`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 cg({row:e}){if(og(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 lg({row:e,requested:t}){let n=`text-muted`,r=`mt-0.5 text-primary`,i=e.outcome===Ze.failed?`No result: the search failed`:e.outcome===Ze.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:Gm}),(0,Q.jsx)(`p`,{className:`${r} tabular-nums`,children:(0,Q.jsx)(Xm,{value:e.rankAbsolute})})]}),e.searchStatus===Vt.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}`]})]}),!og(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)(ch,{source:e.provenance})})]})}function ug({projectName:e,profileId:t,canRun:n,selectedRunId:r,exactRefresh:i,onViewSaved:a,onLatest:o}){let s=L(),[c,l]=(0,Z.useState)(r??null),[u,d]=(0,Z.useState)(null),f={name:e},p=H({...ro({client:Y,path:f,query:{profileId:t}}),enabled:!i,refetchInterval:e=>e.state.data?.runs.some(Jm)?2e3:!1}),m=H({...Ea({client:Y,path:{...f,id:c??``}}),enabled:!!c,refetchInterval:e=>Jm(e.state.data)?2e3:!1}),h=oe({...ma({client:Y}),meta:{skipGlobalErrorToast:!0}}),g=async t=>{if(n&&!h.isPending){d(null);try{await h.mutateAsync({path:{...f,id:t}}),await li(s,`seo`,{projectName:e})}catch(e){d(Ss(e))}}},_=i?m:p;if(_.error)return(0,Q.jsx)(uh,{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)(dh,{title:`No refreshes yet`,children:`Refresh this profile to collect its first saved results.`});let y=m.data?.tasks.filter(rh)??[];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:Fn(e.createdAt,Bm)}),(0,Q.jsx)(Zm,{status:e.status})]}),(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[e.completedTasks,` of `,e.taskCount,` `,nh(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&&Jm(e)&&(0,Q.jsx)(q,{variant:`secondary`,size:`sm`,disabled:h.isPending||e.cancelRequested,onClick:si(()=>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,` · `,eh(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)(uh,{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:[Nm[e.capability],e.searchText===null?e.target?` · ${e.target.value}`:``:` · “${e.searchText}” from ${e.locationLabel??`its market`}`,e.comparison?` · ${e.comparison.competitor.value} · ${Pm[e.comparison.mode]} searches`:``,e.retried?` · retried once`:``]}),(0,Q.jsx)(Zm,{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…`}),Ym(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 dg({projectName:e,context:t,profile:n,id:r,onClose:i,onSaved:a}){let o=L(),s=G[`market-rankings`],c=(e,t)=>fh(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===ft.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??``}`:`${ft.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=G[`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:Ce.domain,value:``,includeSubdomains:!0}]),[E,D]=(0,Z.useState)(n?.competitors?.map(e=>e.value).join(`
3
3
  `)??``),[O,k]=(0,Z.useState)(n?.keywords.join(`
4
4
  `)??``),[A,j]=(0,Z.useState)(n?.locationCode.toString()??``),[M,N]=(0,Z.useState)(n?.languageCode??`en`),[P,ee]=(0,Z.useState)(n?.limit.toString()??`100`),[te,ne]=(0,Z.useState)(null),F=oe({...Vi({client:Y}),meta:{skipGlobalErrorToast:!0}}),I=t.connections.filter(e=>e===h||l.includes(e)),re=t.scopes.filter(e=>e===g||e.supported),ie=x.filter(e=>_.includes(e)),ae=ie.includes(G[`keyword-gaps`]),R=ae||ie.includes(G[`competitor-discovery`]),z=ie.some(e=>e!==G[`keyword-metrics`]),B=ie.includes(G[`ranked-keywords`])||R,V=ie.includes(G[`keyword-metrics`]),H=ie.includes(s),se=_.filter(e=>H?e===s:e!==s||ie.length===0),ce=h?.capabilities.includes(s)&&(g?.capabilities?.includes(s)??!0),le=g?.reason??(g&&!g.supported?`SEO reports are unavailable for this scope.`:null),ue=n&&!g?`The saved scope is unavailable. Choose a current scope.`:le,de=(0,Z.useId)(),fe=(0,Z.useId)(),pe=(0,Z.useId)(),me=e=>S(t=>{let r=t.filter(t=>e.includes(t));return n||r.length?r:v(e)}),he=async()=>{if(!t.access.canWrite||K()||ot()||F.isPending)return;if(!g){ne(`Choose a measurement scope.`);return}let i=O.split(`
5
5
  `).map(e=>e.trim()).filter(Boolean);if(V&&i.length===0){ne(`Enter at least one search to measure demand.`);return}if(z&&C.length===0){ne(`Add at least one domain or host to measure.`);return}if(R&&C.some(e=>e.kind!==Ce.domain||!e.includeSubdomains)){ne(`Organic competitors and search gaps require whole-domain targets including subdomains.`);return}let s={name:y,connectionId:d,capabilities:ie,targets:z?C:[],keywords:i,locationCode:Number(A),languageCode:M,limit:B?Number(P):n?.limit??100,scope:{kind:g.kind,...g.key?{key:g.key}:{},...g.planRevision===void 0?{}:{expectedPlanRevision:g.planRevision}},...H&&n?.rankings?{rankings:n.rankings}:{},...ae?{competitors:E.split(`
6
- `).map(e=>e.trim()).filter(Boolean).map(e=>({kind:Ce.domain,value:e,includeSubdomains:!0}))}:{}},c=$t.safeParse(s);if(!c.success)ne(c.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(` `));else{ne(null);try{await F.mutateAsync({path:{name:e,id:r},body:c.data}),await o.fetchQuery(po({client:Y,path:{name:e}})),a(r)}catch(e){ne(Ss(e))}}},ge=(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(),he()},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:Hm,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&&re.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:Hm,required:!0,value:g?p:``,"aria-describedby":ue?de:void 0,onChange:e=>{let n=t.scopes.find(t=>`${t.kind}:${t.key??``}`===e.target.value);m(e.target.value),me(c(h,n))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose a scope`}),re.map(e=>(0,Q.jsx)(`option`,{value:`${e.kind}:${e.key??``}`,children:e.label},`${e.kind}:${e.key}`))]})]}),ue&&(0,Q.jsx)(`p`,{id:de,className:`text-copy-13 text-secondary`,children:ue})]}),(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[h&&I.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:Hm,required:!0,value:h?d:``,"aria-describedby":n&&!h?fe:void 0,onChange:e=>{let n=t.connections.find(t=>t.id===e.target.value);f(e.target.value),me(c(n,g))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose a source`}),I.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),n&&!h&&(0,Q.jsx)(`p`,{id:fe,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`}),se.length?(0,Q.jsx)(`div`,{className:`grid gap-x-6 sm:grid-cols-2`,children:se.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:ie.includes(e),onChange:t=>{let n=t.currentTarget.checked;S(t=>n?[...t,e]:t.filter(t=>t!==e))}}),Nm[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.`}),ce&&!n?.rankings&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Set up market rankings with the CLI or API.`}),H&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Market rankings use their own profile.`})]})}),z&&(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:H?`Choose one of this project’s own domains.`:R||ie.includes(G[`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:Hm,value:e.value,placeholder:`example.com`,"aria-label":`Target ${t+1}`,onChange:e=>ge(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:Hm,"aria-label":`Target ${t+1} kind`,value:e.kind,onChange:e=>ge(t,{kind:e.target.value,includeSubdomains:e.target.value===Ce.domain}),children:[(0,Q.jsx)(`option`,{value:Ce.domain,children:`Domain + subdomains`}),(0,Q.jsx)(`option`,{value:Ce.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>=(H?1:20),onClick:()=>w(e=>[...e,{kind:Ce.domain,value:``,includeSubdomains:!0}]),children:`Add target`})]}),ae&&(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:`${Hm} 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.`})]}),V&&(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:`${Hm} 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":pe,children:[(0,Q.jsx)(`legend`,{className:`text-heading-14 text-heading`,children:`Search settings`}),(0,Q.jsx)(`p`,{id:pe,className:`text-copy-13 text-secondary`,children:H?`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 ${B?`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:Hm,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:Hm,required:!0,minLength:2,maxLength:10,value:M,onChange:e=>N(e.target.value)})]}),B&&(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:R?`Result limit`:`Ranked searches per target`}),(0,Q.jsx)(`input`,{className:Hm,type:`number`,min:1,max:1e3,step:1,required:!0,value:P,onChange:e=>ee(e.target.value)}),R&&(0,Q.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:ae?`Each gap comparison uses this limit separately for shared and missing searches.`:`Maximum rows per target.`})]})]})]})}),te&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-secondary`,children:te}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:F.isPending||!g?.supported||!h||!ie.length,children:F.isPending?`Saving…`:`Save profile`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:i,children:`Cancel`})]})]})}var fg=[{value:`7`,label:`7d`},{value:`30`,label:`30d`},{value:`90`,label:`90d`},{value:`180`,label:`180d`}],pg=[{value:`1`,label:`1h`},{value:`24`,label:`24h`},{value:`168`,label:`7d`},{value:`720`,label:`30d`}],mg=20,hg=12,gg=20,_g=50,vg=3,yg=`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`,bg=`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,xg=`inline-flex w-fit cursor-pointer list-none items-center gap-1 rounded text-label-14 text-secondary hover:text-heading ${bg} [&::-webkit-details-marker]:hidden`,Sg=`inline-flex items-center gap-1.5 rounded text-left ${bg}`,Cg={ai:`AI referral`,search:`Search`,social:`Social`,paid:`Paid`,referral:`Referral`,direct:`Direct`},wg={cloudflare:`Cloudflare`,vercel:`Vercel`,"cloud-run":`Cloud Run`,wordpress:`WordPress`},Tg={[Ie.matched]:`Matched`,[Ie.unmatched]:`No URL match`,[Ie.ambiguous]:`Ambiguous URL match`,[Ie[`unknown-host`]]:`Host not recorded`,[Ie.redacted]:`URL redacted`,[Ie[`not-configured`]]:`No Property plan`},Eg={[En.verified]:`text-positive`,[En.likely_real]:`text-heading`,[En.unknown]:`text-secondary`},Dg=`This project's traffic source logs no IP address, so one person can't be told from another. AI-referred visits are still counted.`,Og=`Each row is everyone on one browser version, so its visits are not one person's.`,kg=(e,t)=>`${e.toLocaleString()} ${t}${e===1?``:`s`}`,Ag=e=>e.entryName??Cg[e.entryClass],jg=e=>{if(!e.entryName)return e.paid&&e.entryClass!==`paid`?`Paid`:null;let t=e.paid&&e.entryClass!==`paid`?`${Cg[e.entryClass]}, paid`:Cg[e.entryClass];return t===Ag(e)?null:t},Mg=e=>Mr(e,e),Ng=e=>e&&e.toUpperCase()!==`GET`?e.toUpperCase():null;function Pg(){let e=R({strict:!1}),t=ae(),n=B({select:e=>e.location.pathname});return{search:e,update:e=>{t({to:n,search:t=>({...t,...e}),replace:!0})}}}function Fg({projectName:e}){let{account:t}=oi(),{search:n,update:r}=Pg();if(K()||t?.role===wt.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&&(Et(`other`),r({journeyView:e.value===`visitors`?void 0:e.value}))},className:`-mb-px border-b-2 pb-2 text-label-14 transition-colors ${bg} ${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)(Vg,{projectName:e},`visitors:${e}`):(0,Q.jsx)(Xg,{projectName:e},`agents:${e}`)]})}function Ig({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 ${bg} ${e.value===t?`bg-surface-active text-heading`:`text-secondary hover:text-heading`}`,children:e.label},e.value))})}function Lg({summary:e,children:t}){let[n,i]=(0,Z.useState)(!1);return(0,Q.jsxs)(`details`,{open:n,onToggle:e=>i(e.currentTarget.open),className:`text-copy-14 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:xg,children:[n?(0,Q.jsx)(r,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`size-3.5`,"aria-hidden":`true`}),e]}),(0,Q.jsx)(`div`,{className:`mt-3`,children:t})]})}function Rg({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,`. `,Ss(t)]}),(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:n,children:`Retry`})]})}function zg({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 Bg({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)(D,{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 `,wg[t.sourceType]??t.sourceType,`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:t.reason}),(0,Q.jsx)(V,{to:`/traffic/$projectName/$sourceId`,params:{projectName:e,sourceId:t.sourceId},className:`rounded text-link underline-offset-4 hover:underline ${bg}`,children:`Review source`})]},t.sourceId))})}function Vg({projectName:e}){let{search:t,update:n}=Pg(),r=fg.some(e=>e.value===t.journeyDays)?t.journeyDays:`30`,i=t.journeyEngine??``,a=t.journeyReturned===`true`||t.journeyReturned===`false`?t.journeyReturned:``,o=t.journeyMatching===ct.ua?ct.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=H({...wi({client:Y,path:{name:e},query:u}),staleTime:3e4}),f={...u,engine:i||void 0,returned:a||void 0,keyBasis:o||ct[`ip-ua`],limit:mg,offset:s},p=H({...la({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)(Rg,{what:`the visitor summary`,error:d.error,retry:()=>{d.refetch()}}):(0,Q.jsx)(Hg,{summary:d.data}),(0,Q.jsx)(Ig,{label:`First AI visit within`,options:fg,value:r,onChange:e=>{Et(`window`),l(new Date().toISOString()),n({journeyDays:e===`30`?void 0:e,journeyOffset:void 0,journeyVisitor:void 0})}})]}),m&&(0,Q.jsx)(Bg,{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)(Rg,{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:Dg}),(0,Q.jsx)(q,{className:`mt-3`,size:`sm`,variant:`outline`,onClick:()=>{Et(`other`),n({journeyMatching:ct.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)(V,{to:`/projects/$projectName/traffic`,params:{projectName:e},className:`mt-2 inline-block text-link hover:underline`,children:`Review traffic sources`})]}):m?(0,Q.jsx)(Wg,{projectName:e,data:m,engines:d.data?.byEngine.map(e=>e.engine)??[],engine:i,returned:a,matching:o,openKey:h,onToggle:e=>{e&&qe(`journeys.visitor_open`),n({journeyVisitor:e??void 0})},onFilter:e=>{Et(`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)(Lg,{summary:`About this data`,children:(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[d.data&&(0,Q.jsx)(Jg,{summary:d.data}),m&&(0,Q.jsx)(Yg,{data:m})]})})]})}function Hg({summary:e}){let t=(0,Q.jsx)(zg,{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)(zg,{label:`Visitors and returns`,help:Dg,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:U(e.returnRate,et.fraction),i=e.keyBasis.ua>0?`${kg(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)(zg,{label:`AI-referred visitors`,help:i,children:e.aiVisitors.toLocaleString()}),(0,Q.jsxs)(zg,{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)(zg,{label:`Median time to return`,children:e.medianDaysToReturn===null?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not available`}):Ht(e.medianDaysToReturn)}),(0,Q.jsx)(zg,{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:[Cg[e],` `,(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:t.toLocaleString()})]},e))})})]})}function Ug({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=`${Ag(e)}${e.paid?` (paid)`:``}`,n=r.at(-1);n?.label===t?n.visits++:r.push({label:t,visits:1})}let i=r.slice(0,vg),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 Wg({projectName:e,data:t,engines:n,engine:i,returned:o,matching:s,openKey:c,onToggle:l,onFilter:u,onPage:d}){let f=!!(i||o||s),p=s===ct.ua,m=t.totalVisitors===0?0:t.offset+1,g=t.offset+t.visitors.length,_=c!==null&&!t.visitors.some(e=>e.visitorKey===c);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:[m.toLocaleString(),` to `,g.toLocaleString(),` of `,kg(t.totalVisitors,p?`browser group`:`visitor`)]}),(0,Q.jsxs)(`details`,{className:`text-label-14`,open:f||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 ${bg} [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(a,{className:`size-3`,"aria-hidden":`true`}),`Filter`,f&&(0,Q.jsx)(`span`,{className:`text-heading`,children:[i,o===`true`?`Came back`:o===`false`?`No return yet`:``,p?`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:yg,value:i,onChange:e=>u({journeyEngine:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`All engines`}),i&&!n.includes(i)&&(0,Q.jsx)(`option`,{value:i,children:i}),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:yg,value:o,onChange:e=>u({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:yg,value:s,onChange:e=>u({journeyMatching:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`Network and browser`}),(0,Q.jsx)(`option`,{value:ct.ua,children:`Browser only (groups)`})]})]}),f&&(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>u({journeyEngine:void 0,journeyReturned:void 0,journeyMatching:void 0}),children:`Clear filters`})]})]})]}),p&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,Q.jsx)(D,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),Og]}),c&&_&&(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:()=>l(null),children:`Close`})]}),(0,Q.jsx)(Gg,{projectName:e,visitorKey:c,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 i=n.visitorKey===c,a=n.visits.find(e=>e.entryClass===`ai`),o=`journey-visitor-${n.visitorKey}`;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:i?`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":i,"aria-controls":i?o:void 0,"aria-label":`${n.firstAiEngine} visitor, first AI visit ${Mr(n.firstAiAt)}`,onClick:()=>l(i?null:n.visitorKey),className:`${Sg} whitespace-nowrap`,children:[i?(0,Q.jsx)(r,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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:Er(n.firstAiAt)})]})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 align-top`,children:a?(0,Q.jsx)(`span`,{className:`block max-w-[18rem] truncate text-label-13-mono text-heading`,title:a.landingPath,children:ol(a.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)(Ug,{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:Er(n.lastSeenAt)})})]}),i&&(0,Q.jsx)(`tr`,{id:o,children:(0,Q.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-8`,children:(0,Q.jsx)(Gg,{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:()=>d(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:()=>d(t.offset+t.limit),children:`Next visitors`})]})]})}function Gg({projectName:e,visitorKey:t,partialSources:n}){let[r,i]=(0,Z.useState)(0),[a,o]=(0,Z.useState)(Pe.pages),[s,c]=(0,Z.useState)(null),l=H({...ko({client:Y,path:{name:e,visitorKey:t},query:{limit:hg,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)(Rg,{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:kg(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===ct.ua?`Matched by browser only`:`Matched by network and browser`,(0,Q.jsx)(X,{placement:`bottom`,text:d.keyBasis===ct.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)(D,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`text-heading`,children:[`Some requests are missing on `,kg(d.cappedDays,`day`),`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:`At most ${300 .toLocaleString()} requests per visitor are kept each day.`})]}),(0,Q.jsx)(Kg,{visits:u.visits,openId:s,events:u.events,loading:l.isFetching,onToggle:e=>{e&&qe(`journeys.visit_open`),c(e)},onToggleEvents:()=>o(a===Pe.pages?Pe.all:Pe.pages)}),m&&(0,Q.jsxs)(`p`,{className:`text-label-13 text-secondary`,children:[`Later visits are not recorded by `,wg[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)(Lg,{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:qr(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 Kg({visits:e,openId:t,events:n,loading:i,onToggle:a,onToggleEvents:o}){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 s=e.id===t,c=jg(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":s,onClick:()=>a(s?null:e.id),className:`${Sg} text-label-14 text-heading`,children:[s?(0,Q.jsx)(r,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,Q.jsx)(`time`,{dateTime:e.startedAt,children:Mr(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:Ag(e)}),c&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` · `,c]})]}),(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:ol(e.landingPath)})}),(0,Q.jsx)(`td`,{className:`py-2 text-right align-top text-label-14 tabular-nums text-heading`,children:e.pageCount.toLocaleString()})]}),s&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`pb-3 pl-6`,children:(0,Q.jsx)(qg,{visit:e,events:n,loading:i,onToggleEvents:o})})})]},e.id)})})]})}function qg({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===Pe.pages?`No pages recorded for this visit.`:`No requests recorded for this visit.`}):(0,Q.jsx)(`ol`,{"aria-label":`${Ag(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:Mg(e.ts)}),(0,Q.jsxs)(`span`,{className:`min-w-0 break-all text-label-13-mono text-heading`,children:[Ng(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[Ng(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 ${bg}`,children:t===Pe.pages?`Show all ${kg(e.requestCount,`request`)}`:`Show fewer requests`})]})}function Jg({summary:e}){return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[kg(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: `,kg(e.keyBasis.ipUa,`visitor`),` by network and browser, `,kg(e.keyBasis.ua,`visitor`),` by browser only. Visitor figures count only the first: one browser version can be many people.`]})]})}function Yg({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 `,Mr(e.windowStart),` to `,Mr(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:[wg[e.sourceType]??e.sourceType,`:`]}),` `,e.reason]},e.sourceId))]})}function Xg({projectName:e}){let{search:t,update:n}=Pg(),i=pg.some(e=>e.value===t.agentHours)?t.agentHours:`24`,[o,s]=(0,Z.useState)(()=>new Date().toISOString()),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(``),[m,g]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(0),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)({properties:[],sources:[]}),T=(0,Z.useRef)(null),E={since:new Date(Date.parse(o)-Number(i)*36e5).toISOString(),until:o,sourceId:c||void 0,agentId:u?.id,trust:f||void 0,targetKey:m||void 0},D=H({...oo({client:Y,path:{name:e},query:{...E,limit:gg,offset:y}}),staleTime:3e4}),O=D.data;(0,Z.useEffect)(()=>{O&&w({properties:O.properties,sources:O.coverage.sources})},[O]);let k=O?.properties??C.properties,A=O?.coverage.sources??C.sources,j=k.find(e=>e.key===m),M=A.find(e=>e.sourceId===c),N=()=>{b(0),S(null)},P=!!(c||f||m||u);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:[O?(0,Q.jsx)(Zg,{context:O}):(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 ${bg} [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(a,{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:yg,value:c,onChange:e=>{Et(`other`),l(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All sources`}),A.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:yg,value:f,onChange:e=>{Et(`other`),p(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All trust levels`}),Object.values(En).filter(e=>e!==En.likely_fake).map(e=>(0,Q.jsx)(`option`,{value:e,children:rl[e]},e))]})]}),k.length>0&&(0,Q.jsxs)(`details`,{ref:T,className:`relative`,children:[(0,Q.jsxs)(`summary`,{className:`${yg} inline-flex cursor-pointer list-none items-center py-1.5 [&::-webkit-details-marker]:hidden`,children:[`Property: `,j?.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:_,onChange:e=>v(e.target.value),placeholder:`Find a property`,className:`${yg} 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`},...k.filter(e=>e.label.toLowerCase().includes(_.toLowerCase()))].map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":m===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 ${bg}`,onClick:()=>{Et(`other`),g(e.key),N(),T.current&&(T.current.open=!1,T.current.querySelector(`summary`)?.focus())},children:e.label},e.key))})]})]}),P&&(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>{Et(`other`),l(``),p(``),g(``),d(null),N()},children:`Clear filters`})]})]}),(0,Q.jsx)(Ig,{label:`Period`,options:pg,value:i,onChange:e=>{Et(`window`),s(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:[c&&(0,Q.jsxs)(`span`,{children:[`Source: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:M?.label??c})]}),f&&(0,Q.jsxs)(`span`,{children:[`Trust: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:rl[f]})]}),m&&(0,Q.jsxs)(`span`,{children:[`Property: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:j?.label??m})]}),u&&(0,Q.jsxs)(`span`,{children:[`Agent: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:u.label})]})]}),D.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-6 text-copy-14 text-secondary`,children:`Loading agent requests…`}):D.isError?(0,Q.jsx)(Rg,{what:`agent requests`,error:D.error,retry:()=>{D.refetch()}}):O?(0,Q.jsxs)(Q.Fragment,{children:[O.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:O.journeys.map(t=>{let n=x===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 ${Mr(t.startedAt)}`,onClick:()=>{n||qe(`journeys.agent_open`),S(n?null:t.id)},className:`${Sg} text-label-14-strong text-heading`,children:[n?(0,Q.jsx)(r,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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 ${Eg[e]}`,children:rl[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:Mr(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:kg(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)(Qg,{projectName:e,journey:t,selection:{...E,since:O.windowStart,until:O.windowEnd},onSelectAgent:()=>{Et(`other`),d({id:t.agentId,label:t.product}),N()}})})})]},t.id)})})]})}),(O.totalJourneys>O.limit||O.offset>0)&&(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:O.offset===0||D.isFetching,onClick:()=>{b(Math.max(0,O.offset-O.limit)),S(null)},children:`Previous`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:O.offset+O.limit>=O.totalJourneys||D.isFetching,onClick:()=>{b(O.offset+O.limit),S(null)},children:`Next agent visits`})]}),(0,Q.jsx)(Lg,{summary:`About this data`,children:(0,Q.jsx)(e_,{context:O})})]}):null]})}function Zg({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)(zg,{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)(zg,{label:`Requests`,children:e.observedRequests.toLocaleString()}),t!==null&&t>0&&(0,Q.jsx)(zg,{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)(D,{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)(D,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Some requests are missing: a source reached its daily limit.`]})]})}function Qg({projectName:e,journey:t,selection:n,onSelectAgent:r}){let[i,a]=(0,Z.useState)(0),o=H({...Ra({client:Y,path:{name:e,journeyId:t.id},query:{...n,limit:_g,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)($g,{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)(Rg,{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:[Ng(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[Ng(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:Tg[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 $g({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:Eg[t],children:rl[t]}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`: `,[...n].map(t=>nl(t,e)).join(` · `)]})]},t))})}function e_({context:e}){return(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[Mr(e.windowStart),` to `,Mr(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 t_={"non-brand":`Non-brand`,branded:`Branded`,unknown:`Unclassified`},n_={"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":kr.label};function r_({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?`—`:U(e.rate,et.fraction),(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` · `,t_[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:n_[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 i_({projectName:e,revision:t}){let n=(0,Z.useId)(),[r,i]=(0,Z.useState)(`non-brand`),a=jo({client:Y,path:{name:e},query:{queryClass:`all`,limit:1}}),o=H({...a,queryKey:[{...a.queryKey[0],tags:[t??`no-sweep`]}],staleTime:di}),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: `,Ss(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 `,t_[l.queryClass].toLowerCase(),` queries in this check.`]}):l&&(f=(0,Q.jsxs)(`table`,{className:`engine-comparison`,"aria-label":`By engine, ${t_[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)(Zc,{provider:e.provider})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(r_,{value:e.mentionCoverage,queryClass:l.queryClass})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(r_,{value:e.citationCoverage,queryClass:l.queryClass})})]},e.provider))})]})):f=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Te()?Is:`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:[t_[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 `,Mr(d),s?.selection.measurement.state===`partial`?` · incomplete`:``]}):null,c.length>1?(0,Q.jsx)(As,{label:`Query type`,className:`flex-wrap`,options:c.map(e=>({value:e.queryClass,label:t_[e.queryClass]})),value:l.queryClass,onChange:i}):null]})]}),(0,Q.jsx)(`div`,{className:`av-card-body`,children:f})]})}var a_={[vt.queued]:{word:`queued`,tone:`text-secondary`},[vt.running]:{word:`running`,tone:`text-info-300`},[vt.completed]:{word:`completed`,tone:`text-secondary`},[vt.partial]:{word:`partial`,tone:`text-caution-400`},[vt.failed]:{word:`failed`,tone:`text-negative-400`},[vt.cancelled]:{word:`cancelled`,tone:`text-secondary`}};function o_({runs:e,projectName:t,collapsed:n=!1}){let i=(0,Z.useId)(),a=(0,Z.useId)(),o=new Set(e.map(e=>e.location??``)).size>1,s=e.some(e=>e.kind!==gr[`answer-visibility`]),c=e.map(e=>`${e.startedAt}: ${e.summary}.${e.statusDetail?` ${e.statusDetail}`:``}`);return(0,Q.jsx)(`section`,{className:`overview-brief`,"aria-labelledby":i,children:(0,Q.jsxs)(`details`,{className:`av-history`,open:!n||void 0,children:[(0,Q.jsxs)(`summary`,{className:`av-card-head`,"aria-labelledby":i,"aria-describedby":e.length>0?a:void 0,children:[(0,Q.jsx)(`h2`,{id:i,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:a,className:`av-card-meta`,children:[e.length,` recent`]}):null,(0,Q.jsx)(r,{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":i,children:[(0,Q.jsx)(`thead`,{className:`sr-only`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Started`}),s?(0,Q.jsx)(`th`,{scope:`col`,children:`Type`}):null,(0,Q.jsx)(`th`,{scope:`col`,children:`Trigger`}),o?(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=a_[e.status],r=e.status===vt.partial||e.status===vt.failed;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label tabular-nums`,children:(0,Q.jsx)(Es,{run:e,projectName:t,className:`av-link`,label:e.opensSeoWorkspace?`View SEO refresh from ${e.startedAt}`:`View the ${e.startedAt} check`,children:e.startedAt})}),s?(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}),o?(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)(Tl,{items:c})]})})}var s_=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],c_=`Measured answers`,l_=`Close answers`,u_={"non-brand":`Non-brand queries`,branded:`Branded queries`,unknown:`Unclassified queries`},d_={"non-brand":`non-brand queries`,branded:`branded queries`,unknown:`unclassified queries`},f_={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.`},p_={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.`},m_=`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.`,h_=`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 g_(e){return e.kind===`project`?`Whole site`:e.kind===`group`?`${e.label} · Group`:e.kind===`market`?`${e.label} · Market`:e.label}function __(e){return e.reason===`identity-ambiguous`?wr.ambiguous:e.reason===`not-applicable`?`Not applicable`:`Not measured`}function v_({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:[__(e),(0,Q.jsx)(X,{text:Pr})]});if(e.rate===null)return(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:__(e)});let n=Fr(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:U(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 y_({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 b_(e,t){if(!e||e.state===`unavailable`)return null;let n=e[t];if(n.state===`unavailable`)switch(n.reason){case Ne[`previous-unavailable`]:return{text:f_.previousUnavailable,tone:`text-secondary`};case Ne[`current-unavailable`]:case Ne[`not-applicable`]:return null}let{direction:r,magnitude:i}=dn(n.delta);switch(r){case`up`:return{text:f_.up(i),tone:`text-positive`};case`down`:return{text:f_.down(i),tone:`text-negative`};case`none`:return{text:f_.none,tone:`text-secondary`}}}function x_(e,t){let n=Wr(e);return t!==null&&Ur(n)===Ur(Wr(t))?Qr(n):Hr(n)}function S_(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 C_(e,t){if(!e)return null;if(e.state===`unavailable`){let n=e.previousRun?x_(e.previousRun.createdAt,t):null;switch(e.reason){case Fe[`no-selected-run`]:return null;case Fe[`no-previous-run`]:return f_.noPreviousRun;case Fe[`definition-changed`]:return f_.definitionChanged(n);case Fe[`model-changed`]:return f_.modelChanged(n);case Fe[`legacy-unknown`]:return f_.legacyUnknown;case Fe[`partial-run`]:return f_.partialRun;case Fe[`scoped-run`]:return f_.scopedRun}}return f_.comparedWith(x_(e.previousRun.createdAt,t))}function w_(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 T_({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=Fr(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:[__(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:U(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 E_={otherQueries:`Other queries`},D_={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 O_(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(` · `)||E_.otherQueries;return r.sort((e,t)=>e.marketLabel.localeCompare(t.marketLabel)||e.query.localeCompare(t.query))}var k_={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 A_({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?k_.savedCite(r.citedAnswers,r.answers,r.citedTargetKeys.map(i).join(`, `)):k_.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:k_.partlySaved(r.answers)}):null,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:a})]})}function j_({value:e,signal:t,singleAnswer:n,row:r,targetLabels:a}){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)(b,{size:16,"aria-hidden":`true`}):(0,Q.jsx)(i,{size:16,"aria-hidden":`true`}),t?`Yes`:`No`]})}let o=t===`cited`&&r?.uncheckedSources?r: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)(v_,{value:e,signal:t}),o?(0,Q.jsx)(A_,{row:o,targetLabels:a??new Map,showCount:e.rate===null}):null]}),o?(0,Q.jsx)(X,{text:k_.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 M_({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 N_({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)(Rs,{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)(M_,{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:Bo(e.provider)}),(!e.model||e.model!==on(e.provider))&&(0,Q.jsx)(`span`,{className:`block break-words text-label-14 text-secondary`,title:e.model??void 0,children:e.model?on(e.provider)?Re(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)(M_,{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)(j_,{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)(j_,{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} · ${Bo(e.provider)}`,onClick:t=>a(e,t.currentTarget),children:[e.answerCount===1?`View answer`:`View answers`,(0,Q.jsx)(h,{size:16,"aria-hidden":`true`})]})})]},JSON.stringify([e.provider,e.model,e.location])))]})}var P_=`Cited counts only answers whose sources could be checked.`,F_=[{key:`mentioned`,label:`Mentioned`,color:Rr[1],dashed:!1},{key:`cited`,label:`Cited`,color:Zr.positive,dashed:!0}],I_=`var(--chart-tooltip-bg)`;function L_({population:e}){let t=(0,Z.useId)(),[n,r]=(0,Z.useState)({mentioned:!0,cited:!0}),i=F_.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)?[P_]:[],...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`}),F_.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?I_: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":`${u_[e.queryClass]} mention and citation trend`,children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`createdAt`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:e=>new Date(Number(e)).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),minTickGap:24}),(0,Q.jsx)(ve,{domain:[0,1],tick:Xr,tickLine:!1,axisLine:!1,width:48,tickFormatter:e=>U(Number(e))}),(0,Q.jsx)(_e,{...ei,formatter:e=>typeof e==`number`?U(e):`Not measured`,labelFormatter:e=>new Date(Number(e)).toLocaleDateString()}),c.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[n.mentioned?(0,Q.jsx)(ye,{type:`linear`,dataKey:`mentioned-${e}`,name:`Mentioned`,stroke:Rr[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Rr[1]}}):null,n.cited?(0,Q.jsx)(ye,{type:`linear`,dataKey:`cited-${e}`,name:`Cited`,stroke:Zr.positive,strokeWidth:2,strokeDasharray:`6 4`,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:I_,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":`${u_[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)(v_,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(v_,{value:e.citationCoverage,signal:`cited`})}),(0,Q.jsx)(`td`,{children:e.continuity.state.replaceAll(`-`,` `)})]},e.runId))})]})]})]})}function R_(e,t){return t?e?.populations.find(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===t)):void 0}function z_(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=R_(r,t)??R_(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 B_={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: ${Bo(e)}`,model:e=>`Model: ${e.includes(`/`)?Re(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(` `)},V_={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},H_=`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 U_(e,t){return e&&t?B_.dateRange(e.slice(0,4)===t.slice(0,4)?ni(e):Jr(e),Jr(t)):e?B_.dateFrom(Jr(e)):t?B_.dateThrough(Jr(t)):null}function W_(e,t){let n=[];e.provider&&n.push({key:`engine`,label:B_.engine(e.provider),patch:{measurementProvider:void 0}}),e.model&&n.push({key:`model`,label:B_.model(e.model),patch:{measurementModel:void 0}}),e.location&&n.push({key:`location`,label:e.location===`none`?B_.noLocation:B_.location(e.location),patch:{measurementLocation:void 0}});let r=U_(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?B_.resultsFrom(Hr(Wr(r.createdAt))):B_.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function G_(e,t,n){return t===``||e.some(e=>e.value===t)?e:[...e,{value:t,label:n}]}function K_({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=z_(e,t.queryKey,t.answer),_=t.queryClass===`all`?g.queryClass:t.queryClass,v=W_(t,e),y=t.measurementScope===`property`?t.measurementScopeKey:void 0,b=y?i?.({id:y,label:pl(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:h_,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:h_,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:B_.queryType}),(0,Q.jsxs)(`select`,{"aria-label":B_.queryType,className:H_,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:Hr(Wr(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:B_.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":B_.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:B_.manageQueries}):null]})]}),(0,Q.jsxs)(`div`,{id:f,role:`group`,"aria-label":B_.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,G_([{value:``,label:`All engines`},...p.providers.map(e=>({value:e,label:Bo(e)}))],x,Bo(x))),O(`Requested search location`,`measurementLocation`,C,G_([{value:``,label:`All requested locations`},...p.locations.flatMap(e=>e.kind===`exact`?[{value:e.value,label:e.value}]:e.kind===`none`?[{value:`none`,label:B_.noLocation}]:[])],C,C===`none`?B_.noLocation:C)),O(`AI model`,`measurementModel`,S,G_([{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(`/`)?Re(e):e}))],S,S.includes(`/`)?Re(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,G_([{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({...V_}),D()},children:B_.clearFilters})})]}),E?(0,Q.jsx)(`p`,{role:`status`,className:`border-b border-default py-3 text-copy-14 text-secondary`,children:B_.trackingChanged(a?Qr(Wr(a)):null,h.completedAt?Qr(Wr(h.completedAt)):null,o??null)}):null]})}function q_({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=z_(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="${c_}"]`);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=g_(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=O_(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=d_[t.queryClass],_=C_(t.comparison,S_(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.`:f_.explanation;return(0,Q.jsxs)(`section`,{"aria-label":u_[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:u_[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:w_(t.summary,_)}),(0,Q.jsx)(X,{text:v})]})]}),(0,Q.jsxs)(`dl`,{className:`report-headline mt-3`,"data-columns":m?3:2,"aria-label":`${u_[t.queryClass]} headline results`,children:[(0,Q.jsx)(T_,{label:m?`Answers mentioning a property`:`Mentioned answers`,help:x.mode===`advanced`?p_.advancedMention:p_.simpleMention,value:t.summary.mentionCoverage,signal:`mentioned`,unit:`answers`,classNoun:g,change:b_(t.comparison,`mentionCoverage`)}),(0,Q.jsx)(T_,{label:m?`Answers citing a property`:`Cited answers`,help:x.mode===`advanced`?p_.advancedCitation:p_.simpleCitation,value:t.summary.citationCoverage,signal:`cited`,unit:`answers`,classNoun:g,change:b_(t.comparison,`citationCoverage`)}),m?(0,Q.jsx)(T_,{label:`Properties mentioned`,help:p_.propertyReach,value:t.summary.propertyReach,signal:`mentioned`,unit:`properties`,classNoun:g,change:b_(t.comparison,`propertyReach`)}):null]}),(0,Q.jsx)(Fs,{queryClass:x.queryClass,manage:!0}),(0,Q.jsx)(L_,{population:t}),m&&(t.breakdown.groups.length>0||t.breakdown.properties.length>0)?(0,Q.jsx)(J_,{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":`${u_[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:k_.outcomes(t.summary.notMeasuredUnchecked)}):null,t.summary.notMeasuredNoSources?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:k_.outcomesNoSources(t.summary.notMeasuredNoSources)}):null]}),(0,Q.jsx)(X,{text:m_})]})]}):null,(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"data-query-results":t.queryClass,"aria-label":`${u_[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 ${u_[t.queryClass]}`,placeholder:`Search queries`,className:`${h_} 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":`${u_[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)(N_,{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":c_,"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:l_})]}),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:Bo(e.provider)}),e.model&&e.model!==on(e.provider)?(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.model,children:on(e.provider)?Re(e.model):e.model}):null,(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.location===null?B_.noLocation:B_.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`?wr.ambiguous:`Mention not checked`:e.mentioned?`Mentioned`:`Not mentioned`}),(0,Q.jsx)(J,{tone:`neutral`,children:e.cited===null?e.citationUnavailableReason===`citation-not-measured`?kr.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":`${u_[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)(v_,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(v_,{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 J_({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=Ql({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:`${h_} 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)(v_,{value:e.mentionCoverage,signal:`mentioned`}),(0,Q.jsx)(y_,{value:e.mentionCoverage})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(v_,{value:e.citationCoverage,signal:`cited`}),(0,Q.jsx)(y_,{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)(eu,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function Y_(e,t,{enabled:n}){return H({...jo({client:Y,path:{name:e},query:fc(t)}),enabled:n,staleTime:pi,retry:!1,placeholderData:re})}function X_(e,t){return t&&e.selection.mode===`simple`&&e.selection.measurement.state===`not-measured`}function Z_({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=L(),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=H({...jo({client:Y,path:{name:e},query:{...fc(t),cursor:a,search:s||void 0}}),staleTime:pi,retry:!1,placeholderData:re}),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=H({...jo({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&&!R_(p.data,t.queryKey)&&!g.data)return;let r=z_(p.data,t.queryKey,t.answer,g.data);if(!a&&!s){let{queryKey:n}=jo({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&&X_(p.data,i))return(0,Q.jsx)(Q.Fragment,{children:r});if(p.error){let e=Tn(On(p.error)),t=e?.reason===st[`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?D_.retiredMarket:e?D_.retiredScope:Se(p.error)}),t?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementMarketKey:void 0})},children:D_.showAllMarkets}):e?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementScope:`project`,measurementScopeKey:void 0})},children:D_.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)(q_,{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?Se(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 Q_({projectName:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,fallback:s,showUnmeasuredFallback:c=!1}){let l=Y_(e,t,{enabled:!0}),u=l.error?void 0:l.data,d=!l.isPlaceholderData&&u?.selection.availability.state===`available`?u.selection.run.id:null;Vc(d,null);let f=!(!u||u.selection.availability.state!==`available`||X_(u,c));return(0,Q.jsxs)(Q.Fragment,{children:[f?(0,Q.jsx)(K_,{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)(qs,{})}):null,(0,Q.jsx)(Z_,{projectName:e,selection:t,onSelectionChange:n,fallback:s,showUnmeasuredFallback:c},`${e}:${JSON.stringify({...t,queryKey:void 0,answer:void 0})}`)]})}var $_=[{value:`byProvider`,label:`By engine`},{value:`overall`,label:`All engines`}],ev=[{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.`}],tv=[{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.`}],nv=Rr[2],rv=Rr[4],iv=`var(--chart-tooltip-bg)`,av={up:`text-positive-400`,down:`text-negative-400`,none:`text-muted`};function ov({direction:e,magnitude:t}){switch(e){case`up`:return`up ${t} points`;case`down`:return`down ${t} points`;case`none`:return`no change`}}function sv(e){return e.direction===`none`?`no change over the period`:`${ov(e)} over the period`}function cv(e){return e===`__cited__`||e===`__mentioned__`||e===`__mentionShare__`}function lv(e){return e===`__cited__`?`Cited`:e===`__mentioned__`?`Mentioned`:e===`__mentionShare__`?`Mention share`:Bo(e)}function uv(e,t){return e===`__cited__`?Zr.positive:e===`__mentioned__`?Rr[1]:e===`__mentionShare__`?nv:Lr(ys(e),t)}function dv(e){return e===`non-brand`?`non-brand answers`:`all answers`}function fv(e){return e===`cited`?`Cited`:e===`mentionShare`?`Mention share`:`Mentioned`}function pv(e,t){return e===`mentionShare`?`Mention share in ${dv(t)}`:fv(e)}function mv(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 hv={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 gv(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 _v(e,t,n){let r=e.byProvider[t];return r?gv(r,n):null}function vv(e){return e.rate===null?hv.point:`${e.count} of ${e.total}`}function yv(e,t){let n=fv(t).toLowerCase();return e.rate===null?`${n} ${hv.point}`:`${U(e.rate)} ${n}, ${e.count} of ${e.total} answers`}function bv(e,t){if(t===`mentionShare`){let{projectMentionSnapshots:t,competitorMentionSnapshots:n}=e.mentionShare;return`${t} of ${t+n} tracked-brand mentions`}let n=gv(e,t);return n.rate===null?hv.point:`${n.count} of ${n.total} answers`}function xv(e,t){if(t===void 0)return null;let n=String(t);return e.find(e=>e.startDate===n)??null}function Sv(e){let t=ss(e);return t===null?[]:Object.entries(t).sort(([e],[t])=>ys(e).localeCompare(ys(t))).map(([e,t])=>`${Bo(e)}: ${us(t)}`)}function Cv(e,t){return new Date(e).toDateString()===new Date(t).toDateString()}function wv(e){return`${e} ${e===1?`query`:`queries`}`}function Tv(e){let{added:t,removed:n}=e;return[...t.length>0?[`${wv(t.length)} added`]:[],...n.length>0?[`${t.length>0?n.length:wv(n.length)} removed`]:[]].join(`, `)}function Ev(e,t){let n=Wo(e),r=rs(e),i=vs(e,t);if(!n||!r||!i)return null;let a=Ko(i.moves),o=Cv(n.start,n.end),s=e=>Mr(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 Dv(e,t,n){let r=Ev(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?`, `:``,Tv(e),` `,(0,Q.jsx)(`strong`,{children:as(Wr(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 Ov=`Queries changed`;function kv(e){let t=Ko(e.moves);return t?`${Ov}: ${t} between the first and latest points, so the change compares different queries.`:`${Ov}: the first and latest points have answers for ${e.firstCount} and ${e.latestCount} queries, so the change compares different queries.`}function Av(e){return e.replace(/ /g,`\xA0`)}function jv({state:e,from:t=!1}){return(0,Q.jsx)(`span`,{className:t?`av-model av-model-from`:`av-model`,children:us(e)})}function Mv(e,t){return e.reroute?`Same preset, answered with a different model.`:is(e.provider,e.to)?e.served?`Preset picks its own model. Answered with ${us(e.served.to)} (was ${us(e.served.from)}).`:t&&t.length>0?`Preset picks its own model. Answered with ${t.map(e=>e.includes(`/`)?Re(e):e).join(`, `)}.`:`Preset picks its own model.`:null}function Nv({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=>as(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:Tv(e)}),toHelp:null}))});let p=[...new Set(n.map(e=>e.provider))].sort((e,t)=>Bo(e).localeCompare(Bo(t)));for(let e of p){let t=r[e]?.latestServedModelIds??null,a=n.filter(t=>t.provider===e);f.push({key:e,label:Bo(e),rows:a.map((n,r)=>{let a=d.get(e)===n?i.get(e).text:null,o=[Mv(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)(jv,{state:n.from,from:!0}),to:(0,Q.jsx)(jv,{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?rs(l):null;for(let[e,t]of Object.entries(l?ss(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 `,Bo(e),` models: `,ps(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)??[],Bo(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: `,Qo(t)]}):`Changed before this date range: ${Qo(t)}`);for(let e of a)h.push(`${Bo(e.provider)}: most recent ${e.shown} of ${e.total} changes`);for(let e of o)h.push(`${Bo(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:[Bo(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])=>Bo(e).localeCompare(Bo(t)))){let n=t.latestServedModelIds??[],r=n.length>0?n.map(e=>e.includes(`/`)?Re(e):e).join(`, `):us(t.latestObservation.state);h.push((0,Q.jsxs)(Q.Fragment,{children:[Bo(e),` last answered with `,(0,Q.jsx)(`strong`,{children:r}),` on `,(0,Q.jsx)(`strong`,{children:u(Wr(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=>Mr(e,e));y+=` ${t} = the ${Qo(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=xs(r[0],c,e,o);s&&(y+=` Check before: ${u(s)}.`)}let b=Zo({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 ${Av(u(t.at))}`:Av(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)(Tl,{items:h})]}):(0,Q.jsx)(`ul`,{className:`av-details-list`,children:h.map((e,t)=>(0,Q.jsx)(`li`,{children:e},t))})})]})}function Pv({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:Bo(e)}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`selected `,(0,Q.jsx)(jv,{state:t.configured}),` · answered `,(0,Q.jsx)(jv,{state:t.served})]}),(0,Q.jsx)(`span`,{className:`av-status text-caution-400`,children:`substituted`})]},e))})}function Fv({active:e,label:t,payload:n,metric:r,mode:i,buckets:a,basketChanges:o}){if(!e)return null;let s=xv(a,t);if(!s)return null;let c=Wo(s),l=c!==null&&Cv(c.start,c.end)?c.start:null,u=fs(s,o),d=Sv(s),f=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`trend-tooltip-label`,children:gs(s)}),u.map(e=>(0,Q.jsxs)(`p`,{className:`trend-tooltip-detail trend-tooltip-note`,children:[Tv(e),` `,Mr(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:nv},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-tooltip-name`,children:pv(`mentionShare`,s.mentionShare.scope)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:U(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`?ms:os}];return(0,Q.jsxs)(`div`,{className:`trend-tooltip`,children:[f,m.map((e,t)=>{let n=String(e.dataKey??e.name??``),a=(i===`byProvider`?_v(s,n,r):null)??gv(s,r),o=e.color??uv(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:lv(n)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:a.rate===null?hv.value:U(a.rate)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-count`,children:vv(a)})]})},`${n}-${t}`)}),p]})}function Iv({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:[pv(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=dv(e.mentionShare.scope);i=n>0?`${U(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=_v(e,n,t);return r?`${Bo(n)} ${yv(r,t)}`:`${Bo(n)} no data`}).join(`; `):yv(gv(e,t),t);let a=Sv(e);return a.length>0&&(i+=`; models: ${a.join(`; `)}`),(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:gs(e)}),(0,Q.jsx)(`td`,{children:i})]},e.startDate)})})]})})}function Lv({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)(()=>ls(t,n),[t,n]),b=H({queryKey:[`analytics-metrics`,e,c,y,r,h],queryFn:()=>Ee(e,c,h),staleTime:di}),x=b.data??null,S=b.error,C=u===`mentionShare`?`overall`:g,w=(0,Z.useMemo)(()=>x?hs(x,u,C):null,[x,u,C]),T=x?Go(x):null,E=(0,Z.useMemo)(()=>Yo(T??{}),[T]),D=(0,Z.useMemo)(()=>Lo(T??{}),[T]),O=(0,Z.useMemo)(()=>Object.entries(T??{}).filter(([,e])=>e.anchorUnavailable).map(([e])=>e).sort(),[T]),k=(0,Z.useMemo)(()=>x?Ho(x):{},[x]),A=(0,Z.useMemo)(()=>x?Jo(Vo(x)):[],[x]),j=(0,Z.useMemo)(()=>x?Io(x):[],[x]),M=(0,Z.useMemo)(()=>x?zo(x):[],[x]),N=(0,Z.useMemo)(()=>es(T??{},k),[T,k]),P=(0,Z.useMemo)(()=>x?qo(x):{},[x]),ee=(0,Z.useMemo)(()=>Nt(P,{engineName:Bo}),[P]),te=(0,Z.useMemo)(()=>{let e=new Map;for(let[t,n]of Object.entries(P).sort(([e],[t])=>e.localeCompare(t))){let r=Nt({[t]:n},{engineName:Bo});r?.kind===`no-known-change`&&e.set(t,{text:`${r.text} ${r.detail}`,modelIds:n.modelIds??[]})}return e},[P]),ne=(0,Z.useMemo)(()=>{let e=new Map(i.map(e=>[Ye(e),e]));return t=>e.get(Ye(t))??t},[i]),F=u!==`mentionShare`&&C===`byProvider`,I=x?.buckets??[],L=I[I.length-1]?.mentionShare.scope??x?.mentionShareScope??`pooled`,re=pv(u,L),ie=F?Gr.textDim:u===`cited`?Zr.positive:u===`mentionShare`?nv:Rr[1],ae=(0,Z.useMemo)(()=>{let e=new Map(I.map(e=>[e.startDate,ns(e)]));return t=>e.get(String(t))??``},[I]),R=u===`mentionShare`?I.filter(e=>typeof e.mentionShare.rate==`number`&&Number.isFinite(e.mentionShare.rate)):u===`cited`?I.filter(e=>e.citationRate!==null):I,z=R.at(-1),B=(x?Ro(x,u):[]).at(-1)??null,V=x?bs(x,u):null,oe=cs(R,j),se=Uo(oe,u,L,a),le=B!==null&&V!==null?dn(V.delta):null,ue=le!==null&&!se,pe=t.length,me=[];if(B!==null&&z&&me.push((0,Q.jsxs)(Q.Fragment,{children:[`Latest point: `,(0,Q.jsx)(`strong`,{children:bv(z,u)})]})),z&&V!==null&&oe&&!se&&me.push(Dv(oe,z,j)),z&&R.length===1){let e=Ev(z,j);e&&!Uo(vs(z,j),u,L,a)&&me.push(e)}if(le!==null&&R[0]){let e=rs(R[0]);e&&me.push((0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:e}),` point`]}))}if(F&&B!==null){let e=u===`cited`&&z&&z.citationNotMeasured>0?`all answers with sources`:`all answers`;me.push((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:U(B)}),` pools `,e,`; not an average of engines`]}))}let he=[...new Set([...E.buckets.map(e=>e.bucketStartDate),...I.filter(e=>fs(e,j).length>0).map(e=>e.startDate)])].sort(),ge=B!==null&&z&&(0,Q.jsxs)(`div`,{className:`visibility-trend-current`,children:[(0,Q.jsx)(`span`,{className:`visibility-trend-current-dot`,style:{backgroundColor:ie},"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-label`,children:[re,!m&&u!==`mentionShare`?` · ${h} queries`:``]}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-value`,children:[U(B),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`}),le!==null&&(0,Q.jsx)(`span`,{className:`visibility-trend-current-delta ${ue?`text-muted`:av[le.direction]}`,children:ov(le)}),ue&&oe?(0,Q.jsx)(X,{tone:`caution`,label:`Queries changed`,text:kv(oe)}):null]}),Ce=(0,Q.jsxs)(`div`,{className:`visibility-trend-controls`,children:[(0,Q.jsx)(As,{options:tv,value:u,onChange:d,label:`Metric`,className:`visibility-trend-metric-control`}),u!==`mentionShare`&&(0,Q.jsx)(As,{options:$_,value:g,onChange:_,label:`Series`}),(0,Q.jsx)(As,{options:s_,value:c,onChange:l,label:`Time window`,className:`sm:ml-auto`})]}),we;if(S)we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative-400`,children:Se(S)});else if(b.isLoading&&!x)we=(0,Q.jsx)(`div`,{className:`visibility-trend-chart animate-pulse rounded-md bg-bg-elevated/40`,"aria-hidden":`true`});else if(u===`mentionShare`&&pe===0)we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Add tracked competitors to measure mention share over time.`});else if(!x||!w)we=null;else{let{rows:e,series:t,hasData:n}=w;if(!n)we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:u===`mentionShare`?`No answer-text brand mentions for you or tracked competitors in ${dv(L)} in this window yet.`:h===`all`?Te()?Is:`Run a check to start tracking citations and mentions over time.`:`No ${h} answers in this window.`});else if(u===`cited`&&!ts(x))we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:hv.window});else if(F&&t.length===0)we=(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=`${re} rate${h===`all`?``:` in ${h} answers`} across ${e.length} ${e.length===1?`check`:`checks`}. Latest ${U(B)}${le===null?``:`, ${sv(le)}${ue?`, not the same queries`:``}`}.`;we=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`sr-only`,children:n}),(0,Q.jsx)(Iv,{buckets:I,metric:u,mode:C,series:t,mentionShareScope:L}),F&&t.length>0&&(0,Q.jsx)(`ul`,{className:`trend-legend`,"aria-label":`Engines`,children:t.map((e,t)=>{let n=_s(x,e,u);return(0,Q.jsxs)(`li`,{className:`trend-legend-item`,children:[(0,Q.jsx)(`span`,{className:`trend-legend-swatch`,style:{backgroundColor:uv(e,t)},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-legend-name`,children:lv(e)}),n===null?u===`cited`&&Xo(x,e)&&(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:hv.value}):(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:U(n)})]},e)})}),(0,Q.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"aria-label":`${re} trend chart over ${e.length} ${e.length===1?`point`:`points`}`,children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:e,margin:{top:8,right:20,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:ae,minTickGap:24}),(0,Q.jsx)(ve,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:e=>U(e,et.percent),tick:Xr,tickLine:!1,axisLine:!1,width:48}),(0,Q.jsx)(_e,{cursor:{stroke:ti,strokeWidth:1},content:(0,Q.jsx)(Fv,{metric:u,mode:C,buckets:I,basketChanges:j})}),he.map(e=>(0,Q.jsx)(xe,{x:e,stroke:rv,strokeDasharray:`4 4`,strokeWidth:1.5,ifOverflow:`extendDomain`},`setup-change-${e}`)),t.map((e,t)=>(0,Q.jsx)(ye,{type:`monotone`,dataKey:e,name:e,stroke:uv(e,t),strokeDasharray:e===`__mentionShare__`?`5 4`:void 0,strokeWidth:cv(e)?2.5:2,dot:e===`__mentionShare__`?{r:2.75,fill:`var(--chart-tooltip-bg)`,stroke:uv(e,t),strokeWidth:1.5}:{r:2.5,fill:uv(e,t),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:iv},connectNulls:e!==$o,isAnimationActive:!1},e))]})})}),he.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:mv(L)})]}),z?(0,Q.jsx)(`p`,{className:`av-card-meta`,children:gs(z)}):null]}),(0,Q.jsxs)(`div`,{className:`visibility-trend-body`,children:[ee?.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:ee.text}),m&&(0,Q.jsx)(`div`,{className:`mb-3`,children:(0,Q.jsx)(As,{options:ev,value:f,onChange:p,label:`Query type`})}),ge,Ce,we]}),(0,Q.jsx)(Tl,{items:me})]}),x&&!S?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Nv,{buckets:I,queryChanges:M,modelRows:N,served:k,pointerNotices:te,truncated:D,incompleteHistory:O,queryName:ne,sweepTimes:o}),(0,Q.jsx)(Pv,{substitutions:A})]}):null]})}var Rv=new Set([vr.queued,vr.running]),zv={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 Bv({projectName:e,onReviewForTracking:t,scopeOptions:n,planRevision:r,selectedScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c=[],viewerResearchConfig:l=null}){let u=L(),{account:d,canWrite:f}=oi(),p=d?.role===`viewer`&&l!==null,m=!f,h=ot(),[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=H({...Ai({client:Y,path:{name:e}}),staleTime:6e4}),k=H({...da({client:Y}),enabled:!m&&!h,staleTime:6e4}),A={client:Y,path:{name:e},query:{limit:20}},j=ie({...Ii(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=>Rv.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()],ee=N?.access?.canRun??(f||p),te=N?.access?N.access.dailyRunLimit:p?l.viewerDailyRunLimit:null;(0,Z.useEffect)(()=>{!b&&P[0]&&x(P[0].id)},[P,b]);let ne=P.find(e=>e.id===b)??null,F=H({...ha({client:Y,path:{name:e,runId:b??``}}),enabled:!M&&!!b,refetchInterval:ne&&Rv.has(ne.status)?3e3:!1}),I=M||F.isError?null:F.data??null,re=O.data?.locations??[],ae=(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=js(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)&&!Vn(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=>Gs(e,Ns)&&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=>Vn(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(Vn).flatMap(n=>{let r=on(n);if(!r)return[];let i=t.get(n),a=s.get(n),c=i??(o?{...o,name:n,displayName:Bo(n,[...e,...s.values()]),modelConfigurable:!1,defaultModel:r,knownModels:o.knownModels.filter(e=>e.id===r)}:a);return c?[{name:n,displayName:Bo(n,[...e,...s.values()]),configured:!0,defaultModel:r,catalog:c}]:[]});return[...i,...c,...a]},[N?.providers,m,O.data?.providers,k.data]),R=!(m?j.isPending:k.isPending)&&ae.length===0,z=ae.find(e=>e.name===g)??null;(0,Z.useEffect)(()=>{if(!g&&O.data&&!O.isError&&!k.isError){let e=ae.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,ae,O.data,O.isError,k.isError]);let B=z?.catalog.modelConfigurable??!1,V=m?z?.catalog.defaultModel:(z?O.data?.providerModels[z.name]:``)||z?.catalog.defaultModel,se=(B?v.trim():``)||V,ce=z?[...new Map([{id:z.catalog.defaultModel,displayName:Re(z.catalog.defaultModel)},...v.trim()?[{id:v.trim(),displayName:Re(v.trim())}]:[],...z.catalog.knownModels].map(e=>[e.id,e])).values()]:[],le=oe({...Po(),onSuccess:async e=>{w.current=null,D(e=>e+1),C(e.runs),x(e.runs[0]?.id??null),await ny(u),ci({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=>{ci({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)(ws,{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)(Uv,{projectName:e,canWrite:f,researchAllowed:ee&&!M,limitedAccess:m,isEmbed:K(),scopeOptions:n??[],planRevision:r??i?.planRevision??null,initialScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c,locations:re,defaultLocation:O.data?.defaultLocation??null,providerOptions:ae,provider:g,onProviderChange:e=>{_(e),y(``)},resolvedModel:se,visibilityModel:V,configurableModel:B,model:v,onModelChange:y,modelOptions:ce,settingsReady:m?!j.isPending&&!M:!k.isPending&&!k.isError&&!k.isFetching,projectReady:!O.isPending&&!O.isError&&!O.isFetching,isPending:le.isPending,errorMessage:le.isError?`The request could not be confirmed.`:void 0,onSubmit:(t,n)=>{!ee||M||K()||T.current||(w.current?.fingerprint!==n&&(w.current={fingerprint:n,key:crypto.randomUUID()}),T.current=!0,le.mutate({client:Y,path:{name:e},body:{...t,idempotencyKey:w.current.key}}))}},`${e}:${E}`),te!==null&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Up to `,te,` 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)&&R&&(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)(ws,{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:zv.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:zv.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:Qv(e.createdAt)})}),(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`span`,{className:`block`,title:e.provider,children:Bo(e.provider,k.data?.providerCatalog)}),(e.requestedModel??e.resolvedModel)!==on(e.provider)&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.requestedModel??e.resolvedModel,children:Re(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:ey(e.status),children:e.status})})]},e.id))})]})}),j.isFetchNextPageError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:zv.historyMoreError}),j.hasNextPage&&(0,Q.jsx)(q,{className:`mt-3`,variant:`outline`,disabled:j.isFetching,onClick:()=>{j.fetchNextPage()},children:j.isFetchingNextPage?zv.historyLoading:zv.historyMore})]})]}),!M&&F.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:()=>{F.refetch()},children:`Retry results`})]}):!M&&(I||b)?(0,Q.jsx)(Jv,{detail:I,engineLabel:I?Bo(I.provider,k.data?.providerCatalog):void 0,isLoading:F.isFetching,onReviewForTracking:h?void 0:t}):null]})}var Vv=`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`,Hv=`__none__`;function Uv(e){let{projectName:t,locations:n,provider:r,resolvedModel:i,planRevision:a}=e,o=e.providerOptions.map(e=>({...e,knownModels:e.catalog.knownModels})),s=on(r),c=[r?Bo(r,o):`Choose an engine`,i&&i!==s?Re(i):i?null:`Choose a model`].filter(Boolean).join(` · `),l=L(),[u,d]=(0,Z.useState)(`once`),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(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)([]),[j,N]=(0,Z.useState)(null),[P,ee]=(0,Z.useState)(!1),[te,ne]=(0,Z.useState)(!1),[F,I]=(0,Z.useState)(``),[re,ie]=(0,Z.useState)(``),ae=(0,Z.useRef)(null),R=(0,Z.useRef)(!1),z=(0,Z.useRef)(null),B=e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`;(0,Z.useEffect)(()=>{_(B),O(null)},[B]);let V=e.scopeOptions.filter(e=>e.kind===`market`||e.kind===`property`),H=u===`markets`?`market`:`property`,se=V.filter(e=>e.kind===H),ce=t=>({kind:t.kind,key:t.id,label:t.label,planRevision:a??e.initialScope?.planRevision??0}),le=e=>e===Hv?null:n.find(t=>t.label===e),ue=y??e.defaultLocation??Hv,de=V.find(e=>`${e.kind}:${e.id}`===g),fe=de?ce(de):null,pe=u===`once`?[{scope:fe,location:le(ue)}]:u===`locations`?x.map(e=>({scope:null,location:le(e)})):x.map(e=>se.find(t=>`${t.kind}:${t.id}`===e)).map(e=>e?{scope:ce(e),location:le(T[`${e.kind}:${e.id}`]??Hv)}:null),me=[...new Map([...k,...e.templates].map(e=>[e.id,e])).values()],he=D?me.find(e=>e.id===D.id):null,ge=D!==null&&he?.version!==D.version,_e=u===`once`?f:m,ve=_e.split(/\r?\n/).filter(e=>e.trim()),ye=bt(ve),be=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))],xe=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,``)),Se=[];ve.length||Se.push(u===`once`?`Enter at least one query.`:`Enter at least one query pattern.`),ve.some(e=>e.length>4e3)&&Se.push(`Keep each query under 4,001 characters.`),u!==`once`&&xe&&Se.push(`Use the name buttons to insert a supported variable. Remove unknown or incomplete braces.`),pe.length||Se.push(u===`locations`?`Select at least one location.`:`Select at least one destination.`),pe.some(e=>!e||e.location===void 0)&&Se.push(`A selected destination or location is no longer available. Update your selection.`);let Ce=u===`once`&&g!==`project`||u===`markets`||u===`properties`;Ce&&(e.scopePending||e.scopeError||!a||pe.some(e=>!e?.scope))&&Se.push(`Load the current published markets and properties before running scoped research.`);let U=(u===`once`?ye.length:ve.length)*pe.length;if(pe.length>20&&Se.push(`Select at most 20 destinations.`),U>50&&Se.push(`${U} queries selected. Reduce the selection to 50 or fewer.`),ge&&Se.push(`This saved pattern changed. Select its current version from Saved patterns.`),u!==`once`&&!xe){for(let e of pe)if(e&&e.location!==void 0)try{W(D??{pattern:m,variables:be},e.scope,e.location)}catch{Se.push(`Choose a location for {location}, or use only variables available for ${u===`markets`?`markets`:u===`properties`?`properties`:`locations`}.`);break}}let we=JSON.stringify({mode:u,source:_e,contexts:pe,provider:r,resolvedModel:i,template:D,...Ce?{planRevision:a}:{}}),Te=j!==null&&j.signature!==we,Ee=u===`once`?ye.map((e,t)=>({id:String(t),query:e,scope:fe,location:pe[0]?.location??null})):j?.rows??[],De=qv(Ee),Oe=[];u!==`once`&&j&&(Te&&Oe.push(`Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup.`),Ee.some(e=>!e.query.trim()||e.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(e.query))&&Oe.push(`Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables.`),Ee.some(e=>e.location&&!n.some(t=>JSON.stringify(t)===JSON.stringify(e.location)))&&Oe.push(`A preview location changed. Regenerate the preview.`),De.some(e=>bt(e.queries).length!==e.queries.length)&&Oe.push(`Remove duplicate queries within each destination and location.`),De.length>20&&Oe.push(`The preview exceeds 20 runs.`));let ke=e.researchAllowed&&!e.isEmbed&&!e.isPending&&e.settingsReady&&e.projectReady&&!!(r&&i)&&!Se.length&&!Oe.length&&(u===`once`||j!==null),Ae=()=>({runs:De.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}:{}}))}),je=()=>{if(ee(!0),Se.length)return;let e=pe.flatMap((e,t)=>ve.map((n,r)=>({id:`${t}:${r}`,scope:e.scope,location:e.location,...D?{template:{templateId:D.id,templateVersion:D.version,bindingLocation:e.location}}:{},query:W({pattern:n,variables:[...new Set([...n.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))]},e.scope,e.location).output})));N({signature:we,rows:e})},Me=e=>{d(e),S([]),O(null),w(``),ee(!1)},Ne=e=>{if(ie(``),u===`once`)try{p(W(e,fe,le(ue)).output)}catch{ie(`Select a matching market, property, or location before using this pattern.`);return}else h(e.pattern);O(e)},Pe=e=>{let t=z.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)})},Fe=oe({...lo(),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),ne(!1),I(``),ie(``),ae.current=null,await l.invalidateQueries({queryKey:Ja({client:Y,path:{name:t}})}),ci({title:`Pattern saved`,detail:`Available in Saved patterns. Tracking was not changed.`,tone:`positive`})},onError:()=>ie(`Could not save the pattern. Your text is preserved. Retry to save the same pattern.`),onSettled:()=>{R.current=!1}}),Ie=()=>{if(!e.canWrite||e.isEmbed||R.current)return;let n=u===`once`?f:m,r=u===`once`?[]:be;if(!F.trim()||!n.trim()||n.length>4e3||u!==`once`&&xe){ie(`Enter a name and a valid pattern of 1 to 4,000 characters.`);return}let i={name:F.trim(),pattern:n,variables:r},a=JSON.stringify(i);ae.current?.fingerprint!==a&&(ae.current={fingerprint:a,id:crypto.randomUUID()}),R.current=!0,Fe.mutate({client:Y,path:{name:t,templateId:ae.current.id},body:i})},Le=[...new Set([...P||_e.trim()?Se:[],...Oe])],ze=me.filter(e=>{let t=u===`once`?pr(fe,le(ue)):pr(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)(ws,{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||Fe.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:Vv,value:u,disabled:e.isPending,onChange:e=>Me(e.target.value),children:[(0,Q.jsx)(`option`,{value:`once`,children:`Run once`}),(0,Q.jsx)(`option`,{value:`markets`,disabled:!V.some(e=>e.kind===`market`),children:`Repeat across markets`}),(0,Q.jsx)(`option`,{value:`properties`,disabled:!V.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:[(V.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:Vv,value:g,onChange:e=>{_(e.target.value),O(null)},children:[(0,Q.jsx)(`option`,{value:`project`,children:`Whole site`}),g!==`project`&&!de&&(0,Q.jsx)(`option`,{value:g,disabled:!0,children:`Selected destination unavailable`}),V.map(e=>(0,Q.jsxs)(`option`,{value:`${e.kind}:${e.id}`,children:[e.label,` (`,e.kind,`)`]},`${e.kind}:${e.id}`))]})]}),(0,Q.jsx)(Wv,{label:`Answer engine location`,value:ue,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:Vv,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})):se.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)(Wv,{label:`Answer engine location for ${e.label}`,value:T[e.key]??Hv,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:z,className:`${Vv} min-h-32`,"aria-describedby":`research-query-guidance research-query-count`,value:_e,placeholder:u===`once`?zv.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:()=>Pe(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:[U,` / `,50,` queries`,u===`once`?``:` across ${pe.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.`}),ze.length?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:ze.map(e=>(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>Ne(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:()=>ne(!te),children:te?`Cancel save`:`Save as a pattern`}),te&&(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:Vv,value:F,maxLength:120,onChange:e=>I(e.target.value)})]}),(0,Q.jsx)(q,{size:`sm`,disabled:Fe.isPending||!F.trim()||!_e.trim(),onClick:Ie,children:Fe.isPending?`Saving…`:`Save pattern`})]})]}),re&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:re})]})]}),(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:Vv,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:Bo(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:Vv,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?` · ${Re(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:Vv,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))})]})]})]}),Le.length>0&&(0,Q.jsx)(Kv,{errors:Le}),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:je,children:[(0,Q.jsx)(v,{size:14}),j?zv.refreshPreview:`Preview queries`]}),j&&(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:[Ee.length,` query executions in `,De.length,` saved runs · `,c,`. Edit any query or location below.`]}),(0,Q.jsx)(Gv,{rows:Ee,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:!ke,onClick:()=>{if(ke){let n=Ae();e.onSubmit(n,JSON.stringify({projectName:t,...n}))}},children:[(0,Q.jsx)(M,{size:14}),e.isPending?`Starting…`:zv.runAction]}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[u===`once`?`${ye.length} queries`:`${Ee.length} reviewed queries`,` · `,c]})]})]})]})}function Wv({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:Vv,value:t,onChange:e=>r(e.target.value),children:[(0,Q.jsx)(`option`,{value:Hv,children:`No location context`}),n.map(e=>(0,Q.jsx)(`option`,{value:e.label,children:e.label},e.label))]})]})}function Gv({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:`${Vv} 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)(Wv,{label:`Location for query ${r+1}`,value:e.location?.label??Hv,locations:t,onChange:r=>n(e.id,{location:t.find(e=>e.label===r)??null})})]},e.id))})}function Kv({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 qv(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 Jv({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)(ws,{id:e?`research-run-${e.id}`:void 0,className:`surface-card min-w-0`,role:`region`,"aria-label":zv.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 ${$v(e.id)}`:zv.resultsEmpty})}),e&&(0,Q.jsx)(J,{tone:ey(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??Bo(e.provider)})]}),(e.requestedModel??e.resolvedModel)!==on(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:Re(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:zv.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:zv.methodologySummary}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-prose text-copy-14`,children:zv.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`?zv.brandedQuery:e.queryClass===`non-brand`?zv.discoveryQuery:zv.unclassifiedQuery})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:ty(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===tn.failed?`negative`:`caution`,children:e.answerMentioned===null?e.status===tn.failed?`Unavailable`:`Pending`:e.answerMentioned?`Matched`:`No match`})}),(0,Q.jsx)(`td`,{children:e.citationMeasured===!1&&e.status===tn.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===tn.failed?`negative`:`caution`,children:e.citationState===null?e.status===tn.failed?`Unavailable`:`Pending`:e.citationState===`cited`?`Cited`:`Not cited`})})]},e.id))})]})}),(0,Q.jsx)(Yv,{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 Yv({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)(ds,{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===tn.failed?`This query did not return an answer.`:e.status===tn[`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)(Zv,{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 Xv={"explicit-citation":`Cited in the answer`,"answer-support":`Used for the answer`,"search-result":`Search result`,"page-read":`Page read`};function Zv({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:at(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:ut(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:Xv[e.relationship]}),(0,Q.jsx)(Cc,{url:e.url,title:e.title??e.url})]},`${e.url}-${t}`))})]})}function Qv(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 $v(e){return e.length>8?e.slice(0,8):e}function ey(e){return e===vr.completed?`positive`:e===vr.partial||e===vr[`waiting-upstream`]?`caution`:e===vr.failed?`negative`:`neutral`}function ty(e){return e===tn.completed?`positive`:e===tn.failed?`negative`:e===tn[`waiting-upstream`]?`caution`:`neutral`}async function ny(e){await li(e,`researchRuns`)}var ry=new Set([`queued`,`seeding`,`probing`]);function iy({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}=oi(),[d,f]=(0,Z.useState)(`tracked`),[p,m]=(0,Z.useState)(`find`),[h,g]=(0,Z.useState)(null),_=u?.role===`viewer`?yn():null,v=ul(u?.role,_),y=dl(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)(_l,{id:x,label:`Query workspace`,value:y,onChange:S,className:`flex border-b border-default`,tabClassName:ay,activeTabClassName:oy,inactiveTabClassName:sy,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)(Wy,{projectName:e,selection:a,onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,pendingTrackingSource:h,onPendingTrackingSourceHandled:()=>g(null),publishGuard:l}):(0,Q.jsx)(cy,{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 ay=`-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`,oy=`border-mono-400 text-heading`,sy=`border-transparent text-muted hover:border-strong hover:text-strong`;function cy({projectName:e,selection:t,mode:n,onModeChange:r,onReviewSavedSource:i,viewerResearchConfig:a}){let{canWrite:o}=oi(),s=(0,Z.useId)(),c=!o||n===`test`,l=H({...Fo({client:Y,path:{name:e}}),enabled:c,staleTime:6e4}),u=H({...yi({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)(_l,{id:s,label:`Research workspace`,value:n,onChange:r,className:`flex border-b border-default`,tabClassName:ay,activeTabClassName:oy,inactiveTabClassName:sy,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)(Gy,{projectName:e,onReviewDiscoveryProbe:e=>i({source:`discovery`,discoveryProbeId:e})}):(0,Q.jsx)(Bv,{...p,onReviewForTracking:({researchRunQueryId:e,scope:t})=>i({source:`research`,researchRunQueryId:e},t??null)})})]}):(0,Q.jsx)(Bv,{...p,viewerResearchConfig:a})}function ly({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),[v,b]=(0,Z.useState)(()=>uy(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=fl(e,t),O=(0,Z.useMemo)(()=>by(e.tracked,t,e.mode),[t,e.mode,e.tracked]),k=O.some(e=>e.provenance!==null),A=Ql({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}:${Sy(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`?_y(t):void 0,scopeLabel:vy(t,e)}),b(dy(i,t)),S(null))},[t,r,D,e]),(0,Z.useEffect)(()=>{if(D||!a)return;let e=uy(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({...uy(t),source:e}),S(null),i?.(void 0)}function M(n){E.current=`${n.queryId}:${Sy(t)}`,_({kind:`edit`,row:n,audience:e.mode===`advanced`?_y(t):void 0,scopeLabel:vy(t,e)}),b(dy(n,t)),S(null),i?.(n.queryId)}function N(n){E.current=`${n.queryId}:${Sy(t)}`,_({kind:`remove`,row:n,audience:e.mode===`advanced`?_y(t):void 0,scopeLabel:vy(t,e)}),S(null),i?.(n.queryId)}function P(){T.current=!0,_(null),b(uy(t)),S(null),i?.(void 0)}let ee=g?fy(g,v,e):null,te=g!==null&&g.kind===`add`&&e.mode===`advanced`&&!hy(v),ne=ee!==null&&(!te||v.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)(xy,{selection:t,onSelectionChange:n}):null,(0,Q.jsx)($l,{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)(ds,{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)(Ty,{row:n,workspace:e,selection:t})}):null,e.mode===`advanced`?(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(Dy,{row:n})}):null,k?(0,Q.jsx)(`td`,{className:`whitespace-nowrap text-secondary`,children:Cy(n)}):null,(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(Oy,{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)(ds,{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)(ds,{type:`button`,variant:`ghost`,size:`sm`,disabled:d,"aria-label":`Remove ${n.queryText}`,onClick:()=>N(n),children:[(0,Q.jsx)(y,{"aria-hidden":`true`,size:13}),` Remove`]})]})})]},n.queryId))})]})}),(0,Q.jsx)(eu,{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)(ky,{workspace:e,templates:c,action:g,draft:v,onDraftChange:e=>{b(e),S(null)},onClose:P,canReview:ne,isPreviewing:u,editorHeadingRef:C,onReview:()=>{ee&&(S(ee),p(ee))}})}),l&&x&&g&&(0,Q.jsx)(zy,{preview:l,workspace:e,isCommitting:d,sweepActive:h?.sweepActive??!1,onConfirm:si(async()=>{await m({...x,expectedWorkspaceVersion:l.workspaceVersion,previewToken:l.previewToken,reviewedAt:l.reviewedAt})&&P()})})]})}function uy(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 dy(e,t){return{...uy(t),text:e.queryText,queryClass:`keep`}}function fy(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=py(t);if(!i||gy(t)||r&&!t.wholeSite&&t.targetKeys.length+t.groupKeys.length+t.marketKeys.length===0)return null;let a=r?my(t,n):void 0;return{additions:[{input:i,...a?{audience:a}:{},...r&&!hy(t)&&t.contexts.length>0?{contexts:t.contexts}:{},...r&&t.queryClass!==`auto`&&t.queryClass!==`keep`?{queryClass:t.queryClass}:{}}],removals:[]}}function py(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 my(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 hy(e){return e.marketKeys.length>0&&e.targetKeys.length===0&&e.groupKeys.length===0}function gy(e){return e.source===`template`&&e.template.includes(`{market}`)&&(e.wholeSite||e.marketKeys.length===0)}function _y(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 vy(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 yy(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 by(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=>yy(e,t)))}function xy({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 Sy(e){return e.measurementScopeKey&&e.measurementScope!==`project`?`${e.measurementScope}:${e.measurementScopeKey}`:`project`}function Cy(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 wy(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=>yy(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 Ty({row:e,workspace:t,selection:n}){let r=Ey(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:wy(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 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=e.assignments.filter(e=>yy(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 Dy({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 Oy({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:qr(e.lastMeasuredAt),children:Er(e.lastMeasuredAt)}):null]}):(0,Q.jsx)(J,{tone:`caution`,children:`Awaiting check`})}function ky({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)(ws,{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)(Ry,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):n.kind===`edit`?(0,Q.jsxs)(ws,{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)(Ry,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):(0,Q.jsxs)(ws,{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)(Ay,{templates:t,advanced:e.mode===`advanced`,draft:r,onDraftChange:i}):null,r.source===`research`?(0,Q.jsx)(jy,{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)(jy,{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)(Ly,{workspace:e,draft:r,onDraftChange:i}):null]}),e.mode===`advanced`&&!hy(r)?(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Iy,{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)(Ry,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]})}function Ay({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":gy(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]}),gy(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 jy({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 My(e){return{providers:[...e.providers],models:{...e.models},location:e.location?.label??null}}function Ny(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 Py(e){return[...new Map(e.map(e=>[Ny(e),e])).values()]}function Fy(e){let t=e.providers.map(t=>{let n=e.models[t];return n&&n!==on(t)?`${Bo(t)} (${on(t)?Re(n):n})`:Bo(t)}).join(`, `);return`${e.location??`No location`} · ${t}`}function Iy({workspace:e,draft:t,onDraftChange:n}){let r=(0,Z.useMemo)(()=>Py([...e.defaultContexts.map(My),...t.contexts]),[t.contexts,e.defaultContexts]),i=t.contexts.length===1?Ny(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=>Ny(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:Ny(e),children:Fy(e)},Ny(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 Ly({workspace:e,draft:t,onDraftChange:n}){let{canWrite:r}=oi(),[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)($l,{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 Ry({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)(ds,{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 zy({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)(ws,{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:By(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)(Vy,{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)(Vy,{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)(ds,{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 By(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 Vy({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`:Uy(t,r,n)}),e===`Added`||e===`Reused`?(0,Q.jsx)(Hy,{row:r.find(e=>e.queryId===t.queryId),workspace:n}):null]},`${e}:${t.queryId}`))})]})}function Hy({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=>Fy(My(e))).join(`; `);return(0,Q.jsx)(`li`,{children:[r,i,a].filter(Boolean).join(` · `)},`${e.targetKey}:${n}`)})})]})}function Uy(e,t,n){let r=t.find(t=>t.queryId===e.queryId);if(!r)return`${e.assignmentCount} ${e.assignmentCount===1?`assignment`:`assignments`}`;let i=Py(r.assignments.flatMap(e=>e.contexts).map(My)),a=i.length===1?Fy(i[0]):i.length>1?`${i.length} contexts`:null;return[wy(r,n),a].filter(e=>e!==null).join(` · `)}function Wy({projectName:e,selection:t={measurementScope:`project`,queryClass:`all`},onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s}){let c=L(),[l,u]=(0,Z.useState)(null),d=H({...Fo({client:Y,path:{name:e}})}),f=H({...yi({client:Y,path:{name:e}}),staleTime:6e4}),p=oe({...oa(),onSuccess:e=>u(e),onError:async t=>{u(null),await c.invalidateQueries({queryKey:Si({client:Y,path:{name:e}})}),ci({title:`Could not review tracking changes`,detail:t instanceof Error?t.message:`Update the draft and review it again.`,tone:`negative`})}}),m=oe({...qi(),onSuccess:async t=>{u(null),i?.(void 0),await mi(c,e),ci({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 mi(c,e),ci({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)(ws,{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)(ws,{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)(ly,{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 Gy({projectName:e,onReviewDiscoveryProbe:t}){let n=L(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(`100`),l=H({...Pi({client:Y,path:{name:e},query:{limit:`10`}}),refetchInterval:e=>e.state.data?.some(e=>ry.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=H({...pa({client:Y,path:{name:e,id:r??``}}),enabled:!!r,refetchInterval:d&&ry.has(d.status)?3e3:!1}),p=f.data??null,m=oe({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),en(e,t)},onSuccess:async t=>{i(t.sessionId),o(``),await Qy(n,e,t.sessionId),ci({title:`Discovery started`,detail:`Run ${Zy(t.sessionId)} is testing questions your customers might ask.`,tone:`neutral`,dedupeKey:`discovery:start:${t.sessionId}`,dedupeMode:`replace`})},onError:e=>{ci({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 _(){try{let t=await l.refetch();if(t.error)throw t.error;let n=t.data?.length??0;ci({title:`Discovery sessions refreshed`,detail:`${n} recent session${n===1?``:`s`} loaded.`,tone:`positive`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}catch(t){ci({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 _(),children:[(0,Q.jsx)(v,{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)(ws,{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)(ds,{type:`button`,size:`sm`,disabled:m.isPending,onClick:()=>m.mutate(),children:[(0,Q.jsx)(M,{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:Zy(e.id)}),(0,Q.jsx)(J,{tone:qy(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 `,Zy(h.id)]}),(0,Q.jsx)(J,{tone:qy(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)(Ky,{label:`Questions tested`,value:h.probeCount??0}),(0,Q.jsx)(Ky,{label:`Cited queries`,value:h.citedCount??0,tone:`positive`}),(0,Q.jsx)(Ky,{label:`Worth tracking`,value:h.aspirationalCount??0,tone:`caution`}),(0,Q.jsx)(Ky,{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:Jy(e.bucket),children:Xy(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)(ds,{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 Ky({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 qy(e){return e===`completed`?`positive`:e===`failed`?`negative`:ry.has(e)?`caution`:`neutral`}function Jy(e){return e===`cited`?`positive`:e===`aspirational`?`caution`:e===`wasted-surface`?`negative`:`neutral`}var Yy={cited:`Cited queries`,aspirational:`Worth tracking`,"wasted-surface":`Skip`};function Xy(e){return e?Yy[e]:`Not classified`}function Zy(e){return e.length>8?e.slice(0,8):e}async function Qy(e,t,n){await Promise.all([li(e,`discovery`),e.invalidateQueries({queryKey:Eo({client:Y})})])}var $y=4e3,eb={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 tb(e){return`canonry:embed-query-draft:${e}`}function nb(e){try{return window.sessionStorage.getItem(tb(e))??``}catch{return``}}function rb(e,t){try{t?window.sessionStorage.setItem(tb(e),t):window.sessionStorage.removeItem(tb(e))}catch{}}function ib(e,t){return e.trim().replace(/\s+/g,` `).toLocaleLowerCase()===t.trim().replace(/\s+/g,` `).toLocaleLowerCase()}function ab({projectName:e,limit:t}){let n=L(),r=Fo({client:Y,path:{name:e}}),i=H(r),[a,o]=(0,Z.useState)(()=>nb(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 Le(()=>Ft({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:a}}));return n.diff.noOp?`unchanged`:(await Le(()=>zt({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:n.workspaceVersion,previewToken:n.previewToken,reviewedAt:n.reviewedAt}})),`saved`)}catch(e){if(e instanceof zn&&e.code===`EMBED_QUERY_LIMIT`)return`limit`;if(i===0&&e instanceof zn&&e.code===`QUERY_TRACKING_PREVIEW_STALE`)continue;throw e}}throw Error(`The query list kept changing.`)}async function v(r,i){if(m.some(e=>ib(e.queryText,r)))return u({kind:`error`,text:eb.duplicate}),!1;c(i),u(null);try{let i=await _({additions:[{input:{source:`manual`,text:r}}],removals:[]});return i===`unchanged`?(u({kind:`error`,text:eb.duplicate}),!1):i===`limit`?(u({kind:`error`,text:eb.limit(t)}),!1):(await mi(n,e),u({kind:`added`,query:r}),!0)}catch{return u({kind:`error`,text:eb.failed}),!1}finally{c(null)}}async function b(t){t.preventDefault();let n=a.trim();n&&s===null&&!g&&await v(n,`add`)&&(o(``),rb(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 mi(n,e),p.current=r,u({kind:`removed`,query:t.queryText})}catch{u({kind:`error`,text:eb.failed})}finally{c(null)}}}async function S(e){s===null&&await v(e,`undo`)&&d.current?.focus()}if(i.isLoading)return(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,role:`status`,children:eb.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:eb.loadFailed}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void i.refetch(),children:eb.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:eb.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:eb.count(m.length,t)}),` · `,h?eb.nextCheck:eb.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:eb.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:eb.placeholder,maxLength:$y,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),rb(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`?eb.adding:eb.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:[eb.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`?eb.adding:eb.undo})]}):l?.kind===`added`?(0,Q.jsx)(`span`,{className:`sr-only`,children:eb.added(l.query)}):null,h&&g&&!C?(0,Q.jsx)(`span`,{className:`block`,children:eb.limit(t)}):null]})]}),m.length===0?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:eb.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":`${eb.remove} ${e.queryText}`,disabled:s!==null,onClick:()=>void x(e,t),children:[(0,Q.jsx)(y,{"aria-hidden":`true`,size:13}),n?eb.removing:eb.remove]}):null]},e.queryId)})})]})}var ob=/^www\./i;function sb(e){if(!e)return null;try{return new URL(e).hostname}catch{return null}}function cb(e){return e.trim().toLowerCase().replace(ob,``)}function lb(e,t){if(!t)return!1;try{return cb(new URL(e).hostname)===cb(t)}catch{return!1}}function ub(e,t){if(!e)return``;if(!lb(e,t))return e;let n=new URL(e),r=`${n.pathname}${n.search}${n.hash}`;return r===``?`/`:r}function db(e){let t=sb(e);return t?cb(t):null}function fb(e,t,n){if(!e||n.length<2||lb(e,t))return null;let r;try{r=new URL(e)}catch{return null}let i=cb(r.hostname);if(!n.some(e=>cb(e)===i))return null;let a=`${r.pathname}${r.search}${r.hash}`;return{site:i,path:a===``?`/`:a}}function pb(e,t){return ub(e.url,t)||e.path||`/`}var mb=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)}})),hb=mb();function gb(){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 _b=gb;typeof Object.assign==`function`&&(_b=Object.assign);function vb(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 yb(e){return typeof e==`object`&&!!e}function bb(e){let t;for(t in e)return!1;return!0}function xb(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function Sb(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 Cb(e){return!(!yb(e)||e.attributes&&!Array.isArray(e.attributes))}function wb(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function Tb(){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 Eb(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}var Db=class extends Error{constructor(e){super(),this.name=`GraphError`,this.message=e}},Ob=class e extends Db{constructor(t){super(t),this.name=`InvalidArgumentsGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},$=class e extends Db{constructor(t){super(t),this.name=`NotFoundGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},kb=class e extends Db{constructor(t){super(t),this.name=`UsageGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}};function Ab(e,t){this.key=e,this.attributes=t,this.clear()}Ab.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 jb(e,t){this.key=e,this.attributes=t,this.clear()}jb.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function Mb(e,t){this.key=e,this.attributes=t,this.clear()}Mb.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function Nb(e,t,n,r,i){this.key=t,this.attributes=i,this.undirected=e,this.source=n,this.target=r}Nb.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)},Nb.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)},Nb.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]},Nb.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 Pb=0,Fb=1,Ib=2,Lb=3;function Rb(e,t,n,r,i,a,o){let s,c,l,u;if(r=``+r,n===Pb){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===Lb){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===Fb?c.source:c.target,l=i,u=a}return[s,l,u]}function zb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);return a.attributes[o]}}function Bb(e,t,n){e.prototype[t]=function(e,r){let[i]=Rb(this,t,n,e,r);return i.attributes}}function Vb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);return a.attributes.hasOwnProperty(o)}}function Hb(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Rb(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 Ub(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Rb(this,t,n,e,r,i,a);if(typeof c!=`function`)throw new Ob(`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 Wb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(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 Gb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);if(!yb(o))throw new Ob(`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 Kb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);if(!yb(o))throw new Ob(`Graph.${t}: provided attributes are not a plain object.`);return _b(a.attributes,o),this.emit(`nodeAttributesUpdated`,{key:a.key,type:`merge`,attributes:a.attributes,data:o}),this}}function qb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);if(typeof o!=`function`)throw new Ob(`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 Jb=[{name:e=>`get${e}Attribute`,attacher:zb},{name:e=>`get${e}Attributes`,attacher:Bb},{name:e=>`has${e}Attribute`,attacher:Vb},{name:e=>`set${e}Attribute`,attacher:Hb},{name:e=>`update${e}Attribute`,attacher:Ub},{name:e=>`remove${e}Attribute`,attacher:Wb},{name:e=>`replace${e}Attributes`,attacher:Gb},{name:e=>`merge${e}Attributes`,attacher:Kb},{name:e=>`update${e}Attributes`,attacher:qb}];function Yb(e){Jb.forEach(function({name:t,attacher:n}){n(e,t(`Node`),Pb),n(e,t(`Source`),Fb),n(e,t(`Target`),Ib),n(e,t(`Opposite`),Lb)})}function Xb(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 Zb(e,t,n){e.prototype[t]=function(e){let r;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new kb(`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=vb(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 kb(`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 Qb(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 $b(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new kb(`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=vb(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 kb(`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 ex(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new kb(`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=vb(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 kb(`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 Ob(`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 tx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 nx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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(!yb(r))throw new Ob(`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 rx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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(!yb(r))throw new Ob(`Graph.${t}: provided attributes are not a plain object.`);return _b(i.attributes,r),this.emit(`edgeAttributesUpdated`,{key:i.key,type:`merge`,attributes:i.attributes,data: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 kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 Ob(`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 ax=[{name:e=>`get${e}Attribute`,attacher:Xb},{name:e=>`get${e}Attributes`,attacher:Zb},{name:e=>`has${e}Attribute`,attacher:Qb},{name:e=>`set${e}Attribute`,attacher:$b},{name:e=>`update${e}Attribute`,attacher:ex},{name:e=>`remove${e}Attribute`,attacher:tx},{name:e=>`replace${e}Attributes`,attacher:nx},{name:e=>`merge${e}Attributes`,attacher:rx},{name:e=>`update${e}Attributes`,attacher:ix}];function ox(e){ax.forEach(function({name:t,attacher:n}){n(e,t(`Edge`),`mixed`),n(e,t(`DirectedEdge`),`directed`),n(e,t(`UndirectedEdge`),`undirected`)})}var sx=[{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 cx(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 lx(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 ux(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 dx(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 fx(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 px(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 mx(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 hx(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 gx(e,t){if(e.size===0)return Eb();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 _x(e,t,n,r,i,a){let o=t?lx:cx,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 vx(e,t,n,r){let i=[];return _x(!1,e,t,n,r,function(e){i.push(e)}),i}function yx(e,t,n){let r=Eb();return e!==`undirected`&&(t!==`out`&&n.in!==void 0&&(r=Tb(r,ux(n.in))),t!==`in`&&n.out!==void 0&&(r=Tb(r,ux(n.out,t?void 0:n.key)))),e!==`directed`&&n.undirected!==void 0&&(r=Tb(r,ux(n.undirected))),r}function bx(e,t,n,r,i,a,o){let s=n?fx:dx,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 xx(e,t,n,r,i){let a=[];return bx(!1,e,t,n,r,i,function(e){a.push(e)}),a}function Sx(e,t,n,r){let i=Eb();return e!==`undirected`&&(n.in!==void 0&&t!==`out`&&r in n.in&&(i=Tb(i,px(n.in,r))),n.out!==void 0&&t!==`in`&&r in n.out&&(t||n.key!==r)&&(i=Tb(i,px(n.out,r)))),e!==`directed`&&n.undirected!==void 0&&r in n.undirected&&(i=Tb(i,px(n.undirected,r))),i}function Cx(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 mx(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 vx(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 xx(r,this.multi,i,a,t)}throw new Ob(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function wx(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,hx(!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 _x(!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 bx(!1,r,this.multi,i,o,t,n)}throw new Ob(`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 Ob(`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 Ob(`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 Tx(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,hx(!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 _x(!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 bx(!0,r,this.multi,i,o,t,n)}throw new Ob(`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 Ex(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 Eb();if(!arguments.length)return gx(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 yx(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 Sx(r,i,n,t)}throw new Ob(`Graph.${a}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Dx(e){sx.forEach(t=>{Cx(e,t),wx(e,t),Tx(e,t),Ex(e,t)})}var Ox=[{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 kx(){this.A=null,this.B=null}kx.prototype.wrap=function(e){this.A===null?this.A=e:this.B===null&&(this.B=e)},kx.prototype.has=function(e){return this.A!==null&&e in this.A||this.B!==null&&e in this.B};function Ax(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 jx(e,t,n,r,i){if(t!==`mixed`){if(t===`undirected`)return Ax(e,null,r,r.undirected,i);if(typeof n==`string`)return Ax(e,null,r,r[n],i)}let a=new kx,o;if(t!==`undirected`){if(n!==`out`){if(o=Ax(e,null,r,r.in,i),e&&o)return o;a.wrap(r.in)}if(n!==`in`){if(o=Ax(e,a,r,r.out,i),e&&o)return o;a.wrap(r.out)}}if(t!==`directed`&&(o=Ax(e,a,r,r.undirected,i),e&&o))return o}function Mx(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 jx(!1,e,t,n,function(e){r.push(e)}),r}function Nx(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 Px(e,t,n){if(e!==`mixed`){if(e===`undirected`)return Nx(null,n,n.undirected);if(typeof t==`string`)return Nx(null,n,n[t])}let r=Eb(),i=new kx;return e!==`undirected`&&(t!==`out`&&(r=Tb(r,Nx(i,n,n.in))),t!==`in`&&(r=Tb(r,Nx(i,n,n.out)))),e!==`directed`&&(r=Tb(r,Nx(i,n,n.undirected))),r}function Fx(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 Mx(r===`mixed`?this.type:r,i,t)}}function Ix(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.`);jx(!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 Ob(`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 Lx(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 jx(!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 Rx(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 Eb();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 Px(r===`mixed`?this.type:r,i,t)}}function zx(e){Ox.forEach(t=>{Fx(e,t),Ix(e,t),Lx(e,t),Rx(e,t)})}function Bx(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 Vx(e,t){let n={key:e};return bb(t.attributes)||(n.attributes=_b({},t.attributes)),n}function Hx(e,t,n){let r={key:t,source:n.source.key,target:n.target.key};return bb(n.attributes)||(r.attributes=_b({},n.attributes)),e===`mixed`&&n.undirected&&(r.undirected=!0),r}function Ux(e){if(!yb(e))throw new Ob(`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 Ob(`Graph.import: serialized node is missing its key.`);if(`attributes`in e&&(!yb(e.attributes)||e.attributes===null))throw new Ob(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`)}function Wx(e){if(!yb(e))throw new Ob(`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 Ob(`Graph.import: serialized edge is missing its source.`);if(!(`target`in e))throw new Ob(`Graph.import: serialized edge is missing its target.`);if(`attributes`in e&&(!yb(e.attributes)||e.attributes===null))throw new Ob(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`);if(`undirected`in e&&typeof e.undirected!=`boolean`)throw new Ob(`Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.`)}var Gx=wb(),Kx=new Set([`directed`,`undirected`,`mixed`]),qx=new Set([`domain`,`_events`,`_eventsCount`,`_maxListeners`]),Jx=[{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`}],Yx={allowSelfLoops:!0,multi:!1,type:`mixed`};function Xx(e,t,n){if(n&&!yb(n))throw new Ob(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(t=``+t,n||={},e._nodes.has(t))throw new kb(`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 Zx(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 Qx(e,t,n,r,i,a,o,s){if(!r&&e.type===`undirected`)throw new kb(`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 kb(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(s&&!yb(s))throw new Ob(`Graph.${t}: invalid attributes. Expecting an object but got "${s}"`);if(a=``+a,o=``+o,s||={},!e.allowSelfLoops&&a===o)throw new kb(`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 kb(`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 kb(`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 Nb(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 $x(e,t,n,r,i,a,o,s,c){if(!r&&e.type===`undirected`)throw new kb(`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 kb(`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 Ob(`Graph.${t}: invalid updater function. Expecting a function but got "${s}"`)}else if(!yb(s))throw new Ob(`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 kb(`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 kb(`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 _b(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 kb(`Graph.${t}: the "${i}" edge already exists in the graph.`);let h=!1,g=!1;u||(u=Zx(e,a,{}),h=!0,a===o&&(d=u,g=!0)),d||(d=Zx(e,o,{}),g=!0),f=new Nb(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 eS(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 tS=class e extends hb.EventEmitter{constructor(e){if(super(),e=_b({},Yx,e),typeof e.multi!=`boolean`)throw new Ob(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${e.multi}".`);if(!Kx.has(e.type))throw new Ob(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${e.type}".`);if(typeof e.allowSelfLoops!=`boolean`)throw new Ob(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${e.allowSelfLoops}".`);let t=e.type===`mixed`?Ab:e.type===`directed`?jb:Mb;xb(this,`NodeDataClass`,t);let n=`geid_`+Gx()+`_`,r=0;xb(this,`_attributes`,{}),xb(this,`_nodes`,new Map),xb(this,`_edges`,new Map),xb(this,`_directedSize`,0),xb(this,`_undirectedSize`,0),xb(this,`_directedSelfLoopCount`,0),xb(this,`_undirectedSelfLoopCount`,0),xb(this,`_edgeKeyGenerator`,()=>{let e;do e=n+r++;while(this._edges.has(e));return e}),xb(this,`_options`,e),qx.forEach(e=>xb(this,e,this[e])),Sb(this,`order`,()=>this._nodes.size),Sb(this,`size`,()=>this._edges.size),Sb(this,`directedSize`,()=>this._directedSize),Sb(this,`undirectedSize`,()=>this._undirectedSize),Sb(this,`selfLoopCount`,()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),Sb(this,`directedSelfLoopCount`,()=>this._directedSelfLoopCount),Sb(this,`undirectedSelfLoopCount`,()=>this._undirectedSelfLoopCount),Sb(this,`multi`,this._options.multi),Sb(this,`type`,this._options.type),Sb(this,`allowSelfLoops`,this._options.allowSelfLoops),Sb(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 Ob(`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 Ob(`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 Ob(`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 kb(`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 kb(`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 kb(`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 Xx(this,e,t).key}mergeNode(e,t){if(t&&!yb(t))throw new Ob(`Graph.mergeNode: invalid attributes. Expecting an object but got "${t}"`);e=``+e,t||={};let n=this._nodes.get(e);return n?(t&&(_b(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 Ob(`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 eS(this,n),n=n.next;while(n)}for(let e in t.in){n=t.in[e];do eS(this,n),n=n.next;while(n)}}if(this.type!==`directed`)for(let e in t.undirected){n=t.undirected[e];do eS(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=vb(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 eS(this,t),this}dropDirectedEdge(e,t){if(arguments.length<2)throw new kb(`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 kb(`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=vb(this,e,t,`directed`);if(!n)throw new $(`Graph.dropDirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return eS(this,n),this}dropUndirectedEdge(e,t){if(arguments.length<2)throw new kb(`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 kb(`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=vb(this,e,t,`undirected`);if(!n)throw new $(`Graph.dropUndirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return eS(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 Ob(`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(!yb(e))throw new Ob(`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(!yb(e))throw new Ob(`Graph.mergeAttributes: provided attributes are not a plain object.`);return _b(this._attributes,e),this.emit(`attributesUpdated`,{type:`merge`,attributes:this._attributes,data:e}),this}updateAttributes(e){if(typeof e!=`function`)throw new Ob(`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 Ob(`Graph.updateEachNodeAttributes: expecting an updater function.`);if(t&&!Cb(t))throw new Ob(`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 Ob(`Graph.updateEachEdgeAttributes: expecting an updater function.`);if(t&&!Cb(t))throw new Ob(`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 Ob(`Graph.forEachAdjacencyEntry: expecting a callback.`);Bx(!1,!1,!1,this,e)}forEachAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new Ob(`Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.`);Bx(!1,!1,!0,this,e)}forEachAssymetricAdjacencyEntry(e){if(typeof e!=`function`)throw new Ob(`Graph.forEachAssymetricAdjacencyEntry: expecting a callback.`);Bx(!1,!0,!1,this,e)}forEachAssymetricAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new Ob(`Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.`);Bx(!1,!0,!0,this,e)}nodes(){return Array.from(this._nodes.keys())}forEachNode(e){if(typeof e!=`function`)throw new Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`Graph.reduceNodes: expecting a callback.`);if(arguments.length<2)throw new Ob(`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++]=Vx(r,n)});let n=Array(this._edges.size);return t=0,this._edges.forEach((e,r)=>{n[t++]=Hx(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(!yb(t))throw new Ob(`Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.`);if(t.attributes){if(!yb(t.attributes))throw new Ob(`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 Ob(`Graph.import: invalid nodes. Expecting an array.`);for(r=0,i=a.length;r<i;r++){o=a[r],Ux(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 Ob(`Graph.import: invalid edges. Expecting an array.`);for(r=0,i=a.length;r<i;r++){s=a[r],Wx(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(_b({},this._options,t));return n.replaceAttributes(_b({},this.getAttributes())),n}emptyCopy(e){let t=this.nullCopy(e);return this._nodes.forEach((e,n)=>{let r=_b({},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 kb(`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 kb(`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 kb(`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,Qx(t,`copy`,!1,i.undirected,i.key,i.source.key,i.target.key,_b({},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)&&!qx.has(e)&&typeof this[e]!=`function`&&typeof e!=`symbol`&&(r[e]=this[e]);return r.attributes=this._attributes,r.nodes=e,r.edges=t,xb(r,`constructor`,this.constructor),r}};typeof Symbol<`u`&&(tS.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=tS.prototype.inspect),Jx.forEach(e=>{[`add`,`merge`,`update`].forEach(t=>{let n=e.name(t),r=t===`add`?Qx:$x;e.generateKey?tS.prototype[n]=function(i,a,o){return r(this,n,!0,(e.type||this.type)===`undirected`,null,i,a,o,t===`update`)}:tS.prototype[n]=function(i,a,o,s){return r(this,n,!1,(e.type||this.type)===`undirected`,i,a,o,s,t===`update`)}})}),Yb(tS),ox(tS),Dx(tS),zx(tS);var nS=class extends tS{constructor(e){let t=_b({type:`directed`},e);if(`multi`in t&&t.multi!==!1)throw new Ob(`DirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`directed`)throw new Ob(`DirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},rS=class extends tS{constructor(e){let t=_b({type:`undirected`},e);if(`multi`in t&&t.multi!==!1)throw new Ob(`UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`undirected`)throw new Ob(`UndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},iS=class extends tS{constructor(e){let t=_b({multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ob(`MultiGraph.from: inconsistent indication that the graph should be simple in given options!`);super(t)}},aS=class extends tS{constructor(e){let t=_b({type:`directed`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ob(`MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`directed`)throw new Ob(`MultiDirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},oS=class extends tS{constructor(e){let t=_b({type:`undirected`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ob(`MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`undirected`)throw new Ob(`MultiUndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}};function sS(e){e.from=function(t,n){let r=new e(_b({},t.options,n));return r.import(t),r}}sS(tS),sS(nS),sS(rS),sS(iS),sS(aS),sS(oS),tS.Graph=tS,tS.DirectedGraph=nS,tS.UndirectedGraph=rS,tS.MultiGraph=iS,tS.MultiDirectedGraph=aS,tS.MultiUndirectedGraph=oS,tS.InvalidArgumentsGraphError=Ob,tS.NotFoundGraphError=$,tS.UsageGraphError=kb;var cS={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`}},lS={property:`--chart-neutral-text-dim`,fallback:`#71717a`},uS=2.5,dS=200,fS=3,pS=1.6;function mS(e){let t=dS/Math.max(dS,e);return Math.max(fS,9*t**.25)}function hS(e){return mS(e)*pS}var gS={eligible:cS.eligible,hidden:cS.hidden,resource:cS.resource,redirect:cS.redirect,failed:cS.failed,unchecked:cS.unchecked,dimmedNode:{property:`--chart-neutral-text-dim`,fallback:`#71717a`},edge:lS,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`}},_S=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,vS=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/;function yS(e){return _S.test(e)||vS.test(e)}var bS=50,xS=.75,SS=[{maxRatio:.2,budget:1/0},{maxRatio:.45,budget:60},{maxRatio:xS,budget:24}];function CS(e){for(let t of SS)if(e<=t.maxRatio)return t.budget;return 1}function wS(e){return Math.max(0,Math.min(1,(e.linkScoreNormalized??0)/100))}function TS(e){return e.healthState?e.healthState:hn(e)}function ES(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 DS(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 OS(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 kS(e){switch(e){case`eligible`:return`●`;case`hidden`:return`◆`;case`resource`:return`▪`;case`redirect`:return`↗`;case`failed`:return`×`;case`unchecked`:return`○`}}function AS(e,t){return!!t&&e.nodeKey===t}function jS(e,t=!1,n=1){let r=mS(n),i=uS+Math.sqrt(wS(e))*(r-uS);return t?Math.max(hS(n),i):i}function MS(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 NS(e){return .35+Math.min(1.65,Math.log2(Math.max(1,e)+1)*.28)}function PS(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)}function FS(e,t,n,r=null){let i=new aS({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)=>dt(e.nodeKey,t.nodeKey))){if(!PS(e))continue;let t=TS(e),o=MS(t,n),s=kS(t),c=AS(e,r);i.addNode(e.nodeKey,{x:e.x,y:e.y,size:jS(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)=>dt(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:NS(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 IS(e,t,n=bS){let r=t.trim().toLocaleLowerCase(),i=Math.max(0,Math.min(bS,Math.floor(n)));return[...e].sort((e,t)=>dt(e.path||e.url,t.path||t.url)||dt(e.nodeKey,t.nodeKey)).filter(e=>PS(e)?!r||`${e.path}\n${e.url}\n${e.nodeKey}`.toLocaleLowerCase().includes(r):!1).slice(0,i)}function LS(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)||dt(r.path,i.path)||dt(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>xS;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=CS(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()>xS,[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 RS={"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 zS(e){return(e&&RS[e])??RS[`no-crawl`]}var BS=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),gt({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}},VS=220;function HS(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?0:VS}function US(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function WS(e,t,n){let r=window.getComputedStyle(e).getPropertyValue(t).trim();if(r&&!r.includes(`var(`)&&yS(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(`)&&yS(a)?a:n}function GS(e){let t=t=>{let n=gS[t];return WS(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 KS(){if(typeof document>`u`)return!1;try{return!!document.createElement(`canvas`).getContext(`webgl2`)}catch{return!1}}function qS({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 JS({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 YS({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=HS();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>xS,t=CS(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(LS(n,b,()=>f.getCamera().getState().ratio,r,a));let t=f.getCamera().getState().ratio;S.current={overview:t>xS,budget:CS(t)},f.refresh()},[b,n,a,f,r,e]),null}function XS({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,x]=(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)(``),[ee,te]=(0,Z.useState)(!1),[ne,F]=(0,Z.useState)(0),[I,L]=(0,Z.useState)(``),[re,ie]=(0,Z.useState)(0),ae=(0,Z.useRef)(null),R=(0,Z.useDeferredValue)(N),z=c===void 0?k:c,B=(0,Z.useMemo)(()=>new Map(e.map(e=>[e.nodeKey,e])),[e]),V=(0,Z.useMemo)(()=>sb(a?B.get(a)?.url:null),[B,a]),oe=(0,Z.useCallback)(e=>pb(e,V),[V]),H=z?B.get(z)??null:null,se=j?B.get(j.nodeKey)??null:null,ce=(0,Z.useMemo)(()=>IS(e,R),[R,e]),le=e.some(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)),ue=(0,Z.useMemo)(()=>b?FS(e,t,b,a):null,[t,e,a,b]),de=(0,Z.useMemo)(()=>{if(!b||!ue)return null;let e=LS(ue.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}}},[ue,b]);(0,Z.useEffect)(()=>{let e=m.current;if(!e)return;let t=()=>x(GS(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`||!le?E(`checking`):E(KS()?`ready`:`unavailable`)},[le,n,e.length]),(0,Z.useEffect)(()=>{if(T!==`ready`){w(null);return}let e=!0;return Cr(()=>import(`./react-sigma_core.esm.min-B-tTeVwc.js`).then(t=>{e&&w(t)}),__vite__mapDeps([0,1,2]),import.meta.url).catch(()=>{e&&E(`unavailable`)}),()=>{e=!1}},[T]),(0,Z.useEffect)(()=>{F(0)},[R]);let fe=(0,Z.useCallback)(e=>{g.current=e,O(!!e)},[]),pe=(0,Z.useCallback)(e=>{M(e)},[]),me=(0,Z.useCallback)((e,t)=>{let n=B.get(e);n&&(c===void 0&&A(e),l?.(n),t&&g.current?.gotoNode(e),L(`Focused ${oe(n)}`))},[B,l,oe,c]),he=(0,Z.useCallback)(e=>{me(e,!1)},[me]);(0,Z.useEffect)(()=>{!D||!c||!B.has(c)?c||(ae.current=null):ae.current!==c&&(g.current?.gotoNode(c),ae.current=c)},[D,B,c]);let ge=e=>{me(e.nodeKey,!0),P(oe(e)),te(!1)},_e=()=>{window.setTimeout(()=>{document.activeElement!==h.current&&te(!1)},0)},ve=(0,Z.useMemo)(()=>s?t.length:t.filter(e=>e.isTemplate!==!0).length,[t,s]),ye=`Interactive site map showing ${US(e.length,`page`)} and ${US(ve,`internal link`)}`,be=e=>`${v}-${e.replaceAll(/[^\w-]/g,`-`)}`,xe=zS(r);if(n===`unavailable`)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??ye,className:Zt(`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:xe.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:xe.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??ye,className:Zt(`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(!le)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??ye,className:Zt(`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:xe.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:xe.detail}),d&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});let Se=ce.at(ne),Ce=(0,Q.jsx)(JS,{onRetry:()=>ie(e=>e+1)}),U=C?.SigmaContainer;return(0,Q.jsxs)(`section`,{ref:m,role:`group`,"aria-label":f??ye,"aria-describedby":y,className:Zt(`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)(S,{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":ee,"aria-activedescendant":ee&&Se?be(Se.nodeKey):void 0,value:N,placeholder:H?`Focused: ${oe(H)}`:`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:()=>te(!0),onBlur:_e,onChange:e=>{P(e.target.value),te(!0)},onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),te(!0),F(e=>Math.max(0,Math.min(ce.length-1,e+1)))):e.key===`ArrowUp`?(e.preventDefault(),F(e=>Math.max(0,e-1))):e.key===`Enter`&&ee&&Se?(e.preventDefault(),ge(Se)):e.key===`Escape`&&te(!1)}}),ee&&(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:ce.length>0?ce.map((e,t)=>{let n=TS(e);return(0,Q.jsxs)(`button`,{id:be(e.nodeKey),type:`button`,role:`option`,"aria-selected":t===ne,tabIndex:-1,className:Zt(`flex min-h-11 w-full items-center justify-between gap-3 px-3 py-2 text-left text-button-14 outline-none`,t===ne?`bg-surface-active text-primary`:`text-secondary hover:bg-surface-hover hover:text-primary`),onPointerDown:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>F(t),onClick:()=>ge(e),children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:oe(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(${cS[n].property})`},"aria-hidden":`true`,children:kS(n)}),(0,Q.jsx)(`span`,{title:OS(n),children:ES(n)})]})]},e.nodeKey)}):(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-secondary`,children:`No rendered pages match.`})}),ce.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:`${US(e.length,`page`)} on the map · ${US(ve,`link`)} shown`})]}),(0,Q.jsx)(`div`,{className:`relative min-h-0 flex-1 overflow-hidden`,children:T===`unavailable`?(0,Q.jsx)(qS,{onOpenInventory:d}):T===`checking`||!b||!ue||!de||!C||!U?(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)(BS,{fallback:Ce,resetToken:re,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`absolute inset-0`,children:(0,Q.jsx)(U,{graph:ue.graph,className:`relative size-full bg-bg [&_.sigma-container]:size-full`,style:{width:`100%`,height:`100%`,background:b.background},options:de.options,children:(0,Q.jsx)(YS,{setReducers:de.setReducers,reactSigma:C,graph:ue.graph,theme:b,selectedNodeKey:z,showTemplateLinks:s,onSelectNodeKey:he,onHoverNode:pe,onCameraReady:fe})})}),(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`})})]}),se&&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:oe(se)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13-strong text-heading`,children:ES(TS(se))}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-copy-13 text-secondary`,children:OS(TS(se))}),se.depth!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[US(se.depth,`click`),` from home`]}),se.auditScore!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 tabular-nums text-heading`,children:[`Score `,Math.round(se.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:[an.map(e=>(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,title:OS(e),children:[(0,Q.jsx)(`span`,{className:`w-3 text-center font-mono text-label-16-strong`,style:{color:`var(${cS[e].property})`},"aria-hidden":`true`,children:kS(e)}),DS(e)]},e)),(0,Q.jsx)(`span`,{className:`ml-auto`,children:`Bigger = more linked`}),ue&&(ue.omittedNodes>0||ue.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:I})]})}var ZS={"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 QS(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 $S(e,t){return`Worth ${U(e,et.percent)} of the ${t} score`}function eC(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function tC(e){return e>=70?`pass`:e>=40?`partial`:`fail`}function nC(e){return e===`pass`?`positive`:e===`partial`?`caution`:`negative`}function rC(e){return e===`pass`?`Pass`:e===`partial`?`Partial`:`Fail`}function iC({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)(aC,{audit:e}):(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`No findings are available for this page.`})]})}function aC({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:eC(e.auditScore),children:rC(tC(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:QS(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)(h,{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:nC(t.status),children:rC(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:$S(t.sharePct,`page`)}):null]})]})]}),ZS[t.id]&&(0,Q.jsx)(`div`,{className:`flex min-h-14 items-center`,children:(0,Q.jsx)(X,{text:ZS[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 oC=`Not recorded by this scan`,sC=`Not compared with the previous scan, because it scored different sites.`,cC=100,lC=12,uC=[];function dC(e){return Yl(e.url)}function fC(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function pC(e){return e>=70?`text-positive-400`:e>=40?`text-caution-400`:`text-negative-400`}function mC(e){return e===kn.pass?`positive`:e===kn.partial?`caution`:`negative`}var hC={[kn.pass]:`Pass`,[kn.partial]:`Partial`,[kn.fail]:`Fail`},gC=`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.`,_C=`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.`,vC={[kn.fail]:0,[kn.partial]:1,[kn.pass]:2};function yC(e){return e.pagesPartial+e.pagesFailing}function bC(e){return[...e].sort((e,t)=>vC[e.status]-vC[t.status]||yC(t)-yC(e)||e.avgScore-t.avgScore)}function xC(e){return e>=70?`Pass`:e>=40?`Partial`:`Fail`}function SC(e){return Yr(Wr(String(e)))}function CC(e){return Hr(Wr(String(e)))}function wC({projectName:e,projectId:t,runId:n,integrated:i=!1}){let{isAdmin:a}=oi(),o=Dn(gr[`site-audit`])&&!a,[s,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=n===void 0?f:n,[g,_]=(0,Z.useState)(!1),y=(0,Z.useRef)(null),b=H(So({client:Y,path:{name:e},...m?{query:{runId:m}}:{}})),S=H({...Ci({client:Y,path:{name:e},query:{limit:30}}),enabled:!i}),C=H({...Co({client:Y,path:{name:e},query:{surface:`site-health`}}),enabled:i}),w=H(Ao({client:Y,path:{name:e},query:{limit:cC,sort:`score-asc`,...m?{runId:m}:{}}})),T=H({...Ni({client:Y,path:{name:e},query:{kind:gr[`site-audit`],limit:10}}),enabled:!i,refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.some(e=>e.status===`queued`||e.status===`running`)?3e3:1e4}),E=Ec(),O=(0,Z.useSyncExternalStore)(Ms,Qs,Qs),k=Object.values(O.runs).find(e=>e.kind===gr[`site-audit`]&&e.projectId===t),A=T.data??[],j=A.find(e=>e.status===`queued`||e.status===`running`),N=A.at(-1),P=E.isPending||!!k||!!j,ee=E.isPending?`starting`:j?.status??k?.lastAnnouncedStatus,te=(0,Z.useCallback)(async()=>{i&&C.refetch();let e=await Promise.all([b.refetch(),w.refetch(),...i?[]:[S.refetch()]]),t=e.find(e=>e.error);if(t?.error)throw t.error;return e[0]},[i,w.refetch,b.refetch,S.refetch,C.refetch]);(0,Z.useEffect)(()=>{i||m||!N||N.status!==`completed`&&N.status!==`partial`||b.data?.runId!==N.id&&y.current!==N.id&&(y.current=N.id,te().catch(t=>{ci({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`})}))},[m,i,N?.id,N?.status,e,te,b.data?.runId]);let ne=async()=>{_(!0);try{let t=await te();ci({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){ci({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{_(!1)}},F=()=>{(!Dn(gr[`site-audit`])||a)&&E.mutate({projectName:e,projectId:t})},I=ee===`running`?`Scan running`:ee===`queued`?`Scan queued`:`Starting scan`,L=b.data,re=w.data?.pages??uC,ie=(L?.pagesErrored??0)>0,ae=s&&ie,R=Ql({rows:(0,Z.useMemo)(()=>ae?re.filter(e=>e.status===`error`):re,[re,ae]),getSearchText:dC}),z=L?L.pagesAudited>re.length:!1;if((0,Z.useEffect)(()=>{l(!1),d(null)},[m,i]),b.isLoading)return(0,Q.jsxs)(`div`,{className:`flex min-h-40 items-center justify-center gap-2 text-label-14 text-secondary ${i?``:`mt-6`}`,role:`status`,children:[(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading score…`]});if(b.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 ${i?``:`mt-6`}`,role:`alert`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,Q.jsx)(D,{className:`mt-0.5 size-4 shrink-0 text-negative`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{children:[i?(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 ne(),disabled:g,children:[(0,Q.jsx)(v,{className:`size-4 ${g?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),g?`Trying again…`:`Try again`]})]});if(!L||!L.hasData)return i?(0,Q.jsxs)(`section`,{className:`material-base px-5 py-7 text-center`,children:[(0,Q.jsx)(x,{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:o?tc:`Run a new Agent Readiness audit scan to calculate page-level findings.`})]}):(0,Q.jsxs)(ws,{className:`surface-card mt-6 p-8 text-center`,children:[(0,Q.jsx)(x,{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()&&!o&&(0,Q.jsx)(`div`,{className:`mt-5 flex items-center justify-center gap-3`,children:(0,Q.jsxs)(ds,{type:`button`,onClick:F,disabled:P,children:[P?(0,Q.jsx)(c,{className:`mr-1.5 h-4 w-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(M,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?I:`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 B=L.deltaScore==null?null:`${L.deltaScore>=0?`+`:``}${L.deltaScore} vs previous`,V=L.trend===`up`?`positive`:L.trend===`down`?`negative`:`neutral`,oe=B?(0,Q.jsx)(J,{tone:V,children:B}):L.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:sC})]}):null,se=S.data?.points??[],le=se.map(e=>({runId:e.runId,date:e.auditedAt,score:e.aggregateScore})),ue=n===void 0&&f!==null,pe=re.filter(e=>e.status===`success`),me=L.factors.filter(e=>yC(e)>0).length,he=L.runStatus===`partial`,ge=L.crossCuttingIssues.some(e=>e.topRecommendations.length>0);function xe(e){let t=[];for(let n of pe){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:i?``:`mt-6`,children:[i?(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:he?`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":he?`Score so far ${L.aggregateScore} out of 100, from a scan that did not cover the whole site`:`Agent Readiness score ${L.aggregateScore} out of 100`,className:`inline-flex items-baseline gap-1 font-mono tabular-nums ${pC(L.aggregateScore)}`,children:[(0,Q.jsx)(`span`,{className:`text-heading-32`,children:L.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-14 text-muted`,children:`/100`})]}),(0,Q.jsx)(J,{tone:fC(L.aggregateScore),children:xC(L.aggregateScore)}),he?(0,Q.jsx)(J,{tone:`caution`,children:`Part of the site`}):null,oe]}),(L.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)(h,{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:(L.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 ${pC(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:[L.pagesAudited,` page`,L.pagesAudited===1?``:`s`,` scored`]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-faint`,children:`·`}),(0,Q.jsxs)(`span`,{children:[me,` check`,me===1?``:`s`,` with pages below pass`]}),L.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:[L.pagesErrored,` crawl error`,L.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:ue?`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 ${pC(L.aggregateScore)}`,children:L.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-18 text-muted`,children:`/ 100`}),(0,Q.jsx)(J,{tone:fC(L.aggregateScore),children:xC(L.aggregateScore)}),oe,P?(0,Q.jsx)(J,{tone:`neutral`,children:I}):null]}),(0,Q.jsxs)(`p`,{className:`supporting-copy mt-2 tabular-nums`,children:[L.pagesDiscovered,` URL`,L.pagesDiscovered===1?``:`s`,` in sitemap · `,L.pagesAudited,` audited · `,L.pagesSkipped,` skipped · `,L.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:L.sitemapUrl??`#`,target:`_blank`,rel:`noreferrer`,className:`max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong`,children:L.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>`."})]}),L.auditedAt?(0,Q.jsxs)(`p`,{className:`mt-0.5 text-copy-13 text-faint`,children:[`Scanned `,new Date(L.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&&se.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`}),[...se].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 ne(),disabled:g,children:[(0,Q.jsx)(v,{className:`mr-1.5 h-4 w-4 ${g?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),g?`Refreshing…`:`Refresh`]}),!K()&&!o&&(0,Q.jsxs)(ds,{type:`button`,size:`sm`,onClick:F,disabled:P,children:[P?(0,Q.jsx)(c,{className:`mr-1.5 h-4 w-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(M,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?I:`Re-run scan`]})]})]}),i?(0,Q.jsx)(TC,{trend:C.data}):null,!i&&le.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(...le.map(e=>e.score)),` to `,Math.max(...le.map(e=>e.score)),` across `,le.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)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:le,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:SC,minTickGap:24}),(0,Q.jsx)(ve,{domain:[0,100],ticks:[0,25,50,75,100],tick:Xr,tickLine:!1,axisLine:!1,width:32}),(0,Q.jsx)(_e,{...ei,cursor:{stroke:ti,strokeWidth:1},labelFormatter:CC,formatter:e=>[`${e}/100`,`Agent Readiness score`]}),(0,Q.jsx)(ye,{type:`monotone`,dataKey:`score`,name:`score`,stroke:Zr.positive,strokeWidth:2.5,dot:{r:2.5,fill:Zr.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,(0,Q.jsxs)(`section`,{className:i?`pt-5`:`page-section-divider`,children:[i?(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:gC})]}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:ge?`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:_C})]})]}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`evidence-table ${i?`min-w-[42rem]`:``}`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i?`Check`:`Factor`}),i?null:(0,Q.jsx)(`th`,{className:`text-right`,children:`Share`}),(0,Q.jsx)(`th`,{className:`text-right`,children:i?`Score`:`Avg`}),(0,Q.jsx)(`th`,{children:i?`Worst page`:`Status`}),(0,Q.jsx)(`th`,{children:i?`Pages affected`:`Pass / Partial / Fail`})]})}),(0,Q.jsx)(`tbody`,{children:(i?bC(L.factors):L.factors).map(e=>{let t=u===e.id,n=L.crossCuttingIssues.find(t=>t.factorId===e.id),a=t?xe(e.id):[],o=yC(e),s=e.pagesPassing+o,l=!!n?.topRecommendations.length,f=l&&o>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:()=>d(t?null:e.id),children:[t?(0,Q.jsx)(r,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}),e.name]}),ZS[e.id]&&(0,Q.jsx)(X,{text:ZS[e.id],placement:`bottom`})]})}),i?null:(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-muted`,children:typeof e.sharePct==`number`?U(e.sharePct,et.percent):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:U(null)}),(0,Q.jsx)(`span`,{className:`sr-only`,children:oC})]})}),(0,Q.jsxs)(`td`,{className:`text-right font-mono tabular-nums text-strong`,children:[e.avgScore,i?(0,Q.jsx)(`span`,{className:`text-muted`,children:`/100`}):null]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:mC(e.status),children:hC[e.status]})}),i?(0,Q.jsxs)(`td`,{className:`tabular-nums ${o>0?`text-strong`:`text-muted`}`,children:[o,` of `,s]}):(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:i?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:[l&&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))}),i&&typeof e.sharePct==`number`?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:$S(e.sharePct,`site`)}):null]}):o===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Every audited page passes this check.`}):null,o>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 (`,o,`)`]}),i&&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)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading affected pages…`]}):i&&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)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(v,{className:`size-4`,"aria-hidden":`true`}),w.isFetching?`Retrying affected pages…`:`Retry affected pages`]})]}):a.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5`,children:a.slice(0,lC).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 ${pC(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.`}),a.length>lC?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`+ `,a.length-lC,` more below pass`]}):null,z&&(!i||!w.isLoading&&!w.error)?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Showing the worst `,re.length,` audited pages.`]}):null]}):null]})})}):null]},e.id)})})]})})]}),!i&&L.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:L.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:fC(e.avgScore),children:xC(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 (`,U(e.affectedPct,et.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,i?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`})]}),ie?(0,Q.jsxs)(`div`,{className:`segmented`,role:`group`,"aria-label":`Filter pages`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{l(!1),R.setPage(1)},"aria-pressed":!ae,className:`segmented-option min-h-11 tabular-nums ${ae?``:`segmented-option-active`}`,children:[`All `,L.pagesAudited]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{l(!0),R.setPage(1)},"aria-pressed":ae,className:`segmented-option min-h-11 tabular-nums ${ae?`segmented-option-active text-negative`:``}`,children:[`Errors `,L.pagesErrored]})]}):null]}),re.length>0?(0,Q.jsx)($l,{value:R.query,onChange:R.setQuery,label:`Filter audited page URLs`,placeholder:`Filter page URL or query parameters`,className:`mt-3 max-w-md`}):null,R.totalRows===0?(0,Q.jsx)(`p`,{className:`supporting-copy mt-3`,children:R.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:R.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)(D,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`err`]}):(0,Q.jsx)(`span`,{className:pC(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:fC(e.overallScore),children:xC(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)(Zl,{value:e.url,headLength:54,tailLength:20,title:e.status===`error`?e.error??e.url:e.url})})})]},e.url))})]})}),(0,Q.jsx)(eu,{page:R.page,pageSize:R.pageSize,visibleRows:R.rows.length,totalRows:R.totalRows,onPageChange:R.setPage,itemLabel:R.hasQuery?`matches`:`rows`}),z?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-faint`,children:[`Showing the worst `,re.length,` of `,L.pagesAudited,` audited pages.`]}):null]})]})]})}function TC({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===or.score&&e.value!==null?`/100`:void 0,change:Ru(e.change,e.unit),series:Bu(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`&&ju(e))?null:(0,Q.jsx)(`section`,{"aria-label":`Agent Readiness over time`,className:`border-b border-default py-5`,children:(0,Q.jsx)(Ku,{name:`Agent Readiness figures`,groups:[{key:`site-health`,label:`Every scan`,basis:zu(r.figures),figures:i}],selected:[t],onSelect:n,cadence:`scan`,instants:!0,span:Vu(o,s)})})}var EC=[{id:`map`,label:`Map`},{id:`inventory`,label:`Pages`},{id:`technical`,label:`Score`}],DC={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.`},OC=[{id:`all`,label:`All pages`,healthState:void 0},{id:`hidden`,label:`Hidden pages`,healthState:ln.hidden}];function kC(e,t,n){return AC(ub(e,n)||t)}function AC(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 jC(e){return e?e.urlVersions+(e.urlVersionsNotFetched??0):null}function MC(e,t=!1){let n=`${ZC(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 NC={[ir.metaRobotsNoindex]:`Hidden by meta robots tag`,[ir.xRobotsNoindex]:`Hidden by X-Robots-Tag header`,[ir.robotsDisallow]:`Blocked by robots.txt`,[ir.redirectTerminal]:`Redirects to another page`,[ir.canonicalToOther]:`Points to another page as canonical`,[ir.notHtmlOrUnavailable]:`Not an HTML page, so it was not scored`},PC=new Map(Object.entries(NC));function FC(e){return PC.get(e)??e}var IC=20,LC=200,RC=100,zC=100,BC=50,VC=Bn,HC=Qt,UC=new Intl.NumberFormat,WC=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}),GC={eligible:`positive`,hidden:`caution`,resource:`neutral`,redirect:`neutral`,failed:`negative`,unchecked:`neutral`};function KC(e){if(!e)return`Date unavailable`;let t=new Date(e);return Number.isNaN(t.getTime())?`Date unavailable`:WC.format(t)}function qC(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function JC(e){let t=TS(e);return{label:ES(t),tone:GC[t]}}function YC(e){return e==null?`Not scored`:U(e,et.percent)}function XC(e){return e.auditScore==null?`Not checked`:`${Math.round(e.auditScore)}/100`}function ZC(e){return e==null?`Not available`:UC.format(e)}var QC={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.`},$C=new Set([`clicksFromHome`,`linkImportance`,`internalLinks`,`pagesFound`,`pagesChecked`]);function ew(e,t){let n=QC[e];return $C.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 tw(e,t){return`${UC.format(e)} ${t}${e===1?``:`s`}`}function nw(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 rw(e){return e===`completed`?`positive`:e===`partial`||e===`queued`||e===`running`?`caution`:e===`failed`||e===`cancelled`?`negative`:`neutral`}function iw(e){return e?.hasData?e.runStatus===vt.partial?`Score so far ${e.aggregateScore}/100`:e.runStatus===vt.completed?`Score ${e.aggregateScore}/100`:null:null}var aw=`Latest scan`,ow=`Shows the most complete scan from the latest day with results. Choose a dated entry to view another scan.`;function sw(e){let t=KC(e.finishedAt??e.startedAt??e.createdAt),n=e.hasCrawlData?``:` · Score only`;return`${t} · ${qC(e.status)}${n}`}var cw=new Map(Object.entries({complete:`This scan finished on its own.`,unknown:`This scan stopped before it checked every page it found.`,"max-pages":`This scan stopped at the page limit, so some pages were not checked.`,"max-edges":`This scan stopped at the link limit, so some links are missing.`,"max-fetches":`This scan stopped after checking as many pages as it could.`,"max-duration":`This scan ran out of time, so some pages were not checked.`,"max-bytes":`This scan stopped at the data limit, so some pages were not checked.`,"max-page-bytes":`This scan skipped a page that was too large to read.`,"max-depth":`This scan stopped at the depth limit, so deeper pages were not checked.`,"max-links-per-page":`This scan stopped reading links on pages that had too many.`,"max-query-variants":`This scan stopped at the limit for pages that differ only by a query string.`,"max-sitemap-fanout":`This scan stopped at the sitemap limit, so some sitemaps were not read.`,"max-sitemap-urls":`This scan stopped at the sitemap page limit, so some pages were not found.`,"root-host-redirect":`The site moved to another address during this scan.`})),lw=gc,uw=[{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)`}],dw={"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 fw(e){return e?dw[e]??null:null}function pw(e){return e?cw.get(e)??`This scan stopped early: ${e}.`:`This scan stopped before it checked every page it found.`}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 ${tw(e.totalEdgeCount,`link`)} shown.`;let t=`${UC.format(e.contentEdgeCount)} link${e.contentEdgeCount===1?``:`s`} in your page text`,n=UC.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?`, ${UC.format(r)} unchecked`:``;return e===`complete`?t?{label:`Broken links: ${UC.format(t)} found${i}`,tone:`negative`}:r>0?{label:`Broken links: none found, ${UC.format(r)} unchecked`,tone:`caution`}:{label:`Broken links: none found`,tone:`positive`}:e===`partial`?{label:`Broken links: ${UC.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:ZC(e.total),hiddenNote:null,filtered:!1}:{filtered:!0,value:e.truncated?`${ZC(e.visible)}+`:ZC(e.visible),hiddenNote:e.hidden===0?null:e.truncated?`At least ${ZC(e.hidden)} menu and footer hidden`:`${ZC(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:ew(`clicksFromHome`,!1)}),(0,Q.jsx)(Tw,{label:`Links in`,value:t.value,hiddenNote:t.hiddenNote,help:ew(`linksIn`,t.filtered)}),(0,Q.jsx)(Tw,{label:`Links out`,value:n.value,hiddenNote:n.hiddenNote,help:ew(`linksOut`,n.filtered)}),(0,Q.jsx)(Tw,{label:`Link importance`,value:YC(e.linkScoreNormalized),help:ew(`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 ${ZC(t)} menu and footer links hidden.`:`${tw(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:ew(t,!1)})]})}function kw({url:e,rootHost:t,siteHosts:n,pageSite:r}){let i=db(e);if(n.length<2||i===null||!n.includes(i))return(0,Q.jsx)(Q.Fragment,{children:ub(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=db(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,` (`,ZC(t.length),`)`]}),n&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`First `,zC]})]}),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:ZC(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=fb(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:a,outboundTruncated:o,audit:s,auditLoading:l,auditError:u,onRetryAudit:d,rootHost:f,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=JC(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:a,showTemplateLinks:_,known:w}),O=ww({total:e.outboundUniqueEdges,visible:C.length,hidden:E,truncated:o,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:f,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 ${ub(x,f)}, not scored`}),b.map(e=>(0,Q.jsx)(`li`,{children:FC(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)(p,{className:`size-3.5`,"aria-hidden":`true`})]})})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(iC,{audit:s,isLoading:l,error:u,onRetry:d})}),(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)(c,{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:a,rootHost:f,hiddenTemplateCount:T,siteHosts:v,pageUrl:e.url}),(0,Q.jsx)(Aw,{direction:`outbound`,edges:C,truncated:o,rootHost:f,hiddenTemplateCount:E,siteHosts:v,pageUrl:e.url})]})})]})]})}function Pw({pages:e,total:t,skippedUrlVersions:n,rootHost:r,selectedNodeKey:i,onSelect:a,hasNextPage:o,isFetchingNextPage:s,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]),x=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 ${ZC(e.length)} of ${ZC(t)} pages.`:`Showing ${ZC(e.length)} of ${ZC(t)} hidden pages.`}),n!=null&&n>0&&(0,Q.jsx)(X,{...MC(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=OC.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:OC.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsxs)(`label`,{className:Zt(`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)(S,{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:OS(`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=JC(e),n=fb(e.url,r,v),o=n?AC(n.path):kC(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:OS(TS(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:ZC(e.inboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:ZC(e.outboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:YC(e.linkScoreNormalized)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:XC(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.`:x?`No matches in the ${ZC(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:s,onClick:l,children:[s&&(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),s?`Loading more pages`:`Load more pages`]})})]})}function Fw({projectName:e,runId:t,site:n,section:i,onSelect:a}){let[o,s]=(0,Z.useState)(!1),c=i.pageCount-+!!i.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:[c?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${o?`Collapse`:`Expand`} ${i.path}`,"aria-expanded":o,onClick:()=>s(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:o?(0,Q.jsx)(r,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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:()=>a(i.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:i.path}),(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:ZC(i.pageCount)})]}),o&&(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:i.path,onSelect:a})})]})}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:ZC(1)})]})})}function Lw({site:e,children:t}){let[n,i]=(0,Z.useState)(!1),a=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:[a?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${n?`Collapse`:`Expand`} ${e.host}`,"aria-expanded":n,onClick:()=>i(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)(r,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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}),a?(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:ZC(e.pages)}):(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12 text-secondary`,title:e.error??void 0,children:`Not reached`})]}),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 s={client:Y,path:{name:e},query:{runId:t,parentPath:r,limit:RC,...n?{site:n}:{}}},l=ie({...ca(s),initialPageParam:s,getNextPageParam:e=>e.nextCursor?{path:s.path,query:{...s.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)(c,{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)(c,{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),r=[`Find pages`,n===1&&t!==null?`Check pages · ${ZC(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":r[n],children:[(0,Q.jsx)(`div`,{className:`grid grid-cols-[1fr_2fr_1fr] gap-1.5`,"aria-hidden":`true`,children:r.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:r.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)(b,{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?ZC(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?ZC(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?ZC(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?ZC(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({phase:e,progress:t,onRunAgain:n}){let r=e===`cancelled`,i=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:r?`Scan cancelled`:`Scan failed`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:r?`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.`}),i&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:i}),n&&(0,Q.jsx)(q,{type:`button`,className:`mt-4`,onClick:n,children:`Run scan again`})]})}function Zw({projectName:e,projectId:t,initialRunId:n,onReleaseInitialRun:i}){let a=(0,Z.useId)(),[o,s]=(0,Z.useState)(`map`),l=(0,Z.useRef)([]),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=e=>{u.current?.open&&e.target instanceof Node&&!u.current.contains(e.target)&&(u.current.open=!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[]);let[d,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),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(`all`),[N,P]=(0,Z.useState)(`all`),[ee,te]=(0,Z.useState)(null),[ne,F]=(0,Z.useState)(!1),I=K(),{isAdmin:L}=oi(),re=ot(),ae=(re||Dn(gr[`site-audit`]))&&!L,R=Ec(),z=!I&&!ae,B=H({...Ai({client:Y,path:{name:e}}),enabled:z,staleTime:di});(0,Z.useEffect)(()=>{let e=h.current;e!==n&&(h.current=n,f(t=>n??(t===e?null:t)),_(null))},[n]);let V=H({...Oo({client:Y,path:{name:e},query:{limit:IC}}),refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.scans.some(e=>e.status===`queued`||e.status===`running`)?3e3:15e3}),oe=V.data?.scans??[],se=oe.find(e=>e.status===`queued`||e.status===`running`),ce=oe.find(e=>e.status===`completed`||e.status===`partial`),le=R.data?.runId??null,ue=le&&le!==p&&oe.some(e=>e.runId===le&&(e.status===`completed`||e.status===`partial`))?le:null,de=d??ue??V.data?.preferredRunId??ce?.runId??se?.runId??null,fe=se?.runId===de?se:null,pe=de?oe.find(e=>e.runId===de):void 0,me=!!(n&&de===n),he=fe?.runId??(me?de:null),ge=H({...Oa({client:Y,path:{name:e,runId:he??``}}),enabled:!!he,refetchInterval:e=>Ww(e.state.data?.phase)?3e3:!1,refetchIntervalInBackground:!0});(0,Z.useEffect)(()=>{me&&ge.isError&&qw(ge.error)===`NOT_FOUND`&&(f(null),_(null),i?.())},[ge.error,ge.isError,me,i]);let _e=Gw(ge.data?.phase),ve=Kw(ge.data?.phase)?null:fe,ye=!!(he&&ge.isPending),be=!!(me&&!pe&&ge.isError),xe=!!(ve||_e||ye||be),Se=ge.data?.phase===`failed`||ge.data?.phase===`cancelled`?ge.data.phase:me&&(pe?.status===`failed`||pe?.status===`cancelled`)?pe.status:null,Ce=H({...Ma({client:Y,path:{name:e},...de?{query:{runId:de}}:{}}),enabled:!xe}),U=Ce.data,we=de??U?.runId??null,Te=!!(we&&U?.hasCrawlData&&U.detailsAvailable),Ee=we?{runId:we}:{},De=H({...Ba({client:Y,path:{name:e},query:{...Ee,maxNodes:VC,maxEdges:HC}}),enabled:Te&&!xe}),Oe=OC.find(e=>e.id===A)?.healthState,ke=U?.sites??[],Ae=ke.map(e=>e.host),W=ke.length>1&&Ae.includes(N)?N:`all`,je={client:Y,path:{name:e},query:{...Ee,...Oe?{healthState:Oe}:{},...W===`all`?{}:{site:W},urlVersions:`exclude`,limit:LC,sort:`path`}},Me=ie({...ao(je),enabled:Te,initialPageParam:je,getNextPageParam:e=>e.nextCursor?{path:je.path,query:{...je.query,cursor:e.nextCursor}}:void 0}),Ne=Te&&(U?.deadLinks.state===`complete`||U?.deadLinks.state===`partial`),Pe=H({...Ha({client:Y,path:{name:e},query:{...Ee,limit:BC}}),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||!xn(ze),Ve=(0,Z.useMemo)(()=>ne||Be?Ie:Ie.filter(e=>!e.isTemplate),[Ie,ne,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(B.data),Ke=(ee??B.data?.siteAuditDomains??[]).filter(e=>Ge.owned.includes(e)),qe=(0,Z.useMemo)(()=>Ue.find(e=>e.nodeKey===g)??null,[Ue,g]),G=!!(Te&&g&&!qe),Je=H({...Qa({client:Y,path:{name:e},query:{...Ee,...Oe?{healthState:Oe}:{},nodeKey:g??void 0,limit:1}}),enabled:G}),Ye=qe??Je.data?.pages[0]??null,Xe=!!(g&&Oe&&G&&Je.isSuccess&&Je.data.healthStateFilter===`applied`&&Je.data.pages.length===0);(0,Z.useEffect)(()=>{Xe&&_(null)},[Xe]);let Ze=(0,Z.useMemo)(()=>Xe?null:Fe.find(e=>e.nodeKey===g)??Ye,[Fe,Ye,g,Xe]),Qe=Ze?.nodeKey??null;Ws(e,{view:`site-health`,page:{...we?{runId:we}:{},...Qe?{nodeKey:Qe}:{}}});let $e=Ze?Ye?`ready`:Je.isError?`error`:G&&Je.isLoading?`loading`:`ready`:`idle`,et=H({...wa({client:Y,path:{name:e},query:{...Ee,nodeKey:Qe??void 0,limit:zC}}),enabled:Te&&!!Qe}),tt=H({...La({client:Y,path:{name:e},query:{...Ee,nodeKey:Qe??void 0}}),enabled:Te&&!!Qe}),nt=(0,Z.useMemo)(()=>{let e=oe.filter(e=>e.status===`completed`||e.status===`partial`),t=d?oe.find(e=>e.runId===d):void 0;return t&&!e.some(e=>e.runId===t.runId)?[t,...e]:e},[oe,d]),rt=nt.length>0,it=oe[0]?.status??null,at=we?pe:void 0,st=ve?ve.status:_e?ge.data?.status??null:Se??U?.runStatus??at?.status??null,ct=st===`running`?`Scan running`:st===`queued`?`Scan queued`:st===`partial`?`Partial scan`:st===`completed`?`Complete`:st===`failed`?`Scan failed`:st===`cancelled`?`Scan cancelled`:`No scan`,lt=!!we&&(st===vt.completed||st===vt.partial),ut=H({...So({client:Y,path:{name:e},...we?{query:{runId:we}}:{}}),enabled:lt}),dt=lt?iw(ut.data):null,ft=Pe.data,pt=ft&&`found`in ft?ft:U?.deadLinks&&`found`in U.deadLinks?U.deadLinks:void 0,mt=Cw(ft?.state??U?.deadLinks?.state??`unavailable`,pt?.found,pt?.unverified),ht=nw(U?.requestedRootUrl??null,U?.rootUrl??null),gt=sb(U?.rootUrl??null),_t=De.data?.rootNodeKey??null,yt=H({...Qa({client:Y,path:{name:e},query:{...Ee,nodeKey:_t??void 0,limit:1}}),enabled:!!(Te&&_t)}),bt=(0,Z.useMemo)(()=>Fe.find(e=>e.nodeKey===_t)??yt.data?.pages[0]??null,[Fe,_t,yt.data]),xt=se&&se.runId!==de?se:null,St=R.isPending||!!ve||!!xt||_e||ye,Ct=o===`technical`?`map`:o,wt=e=>{f(e||null),m(le),_(null)},Tt=()=>{(!re&&!Dn(gr[`site-audit`])||L)&&(u.current&&(u.current.open=!1),f(null),_(null),n&&i?.(),R.mutate({projectName:e,projectId:t,projectLabel:B.data?.displayName||e,body:{checkDeadLinks:v,...b?{includeGeo:!0}:{},...S?{}:{includeAgentSkills:!1},...w===null?{}:{maxPages:w},...O===null?{}:{maxDepth:O},...Ge.owned.length>0?{sites:Ke}:{}}}),te(null))},Et=(e,t)=>{let n=e=>!t||db(e)===t,r=Fe.find(t=>(t.path===e||t.path.startsWith(`${e}/`))&&n(t.url));r&&_(r.nodeKey)},Dt=e=>s(e),Ot=(e,t)=>{let n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%EC.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+EC.length)%EC.length:e.key===`Home`?n=0:e.key===`End`&&(n=EC.length-1),n!=null&&(e.preventDefault(),Dt(EC[n].id),l.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:`Audit scan`}),(0,Q.jsx)(X,{text:DC[o]}),(0,Q.jsx)(J,{tone:rw(st),children:ct}),dt&&(0,Q.jsx)(`span`,{className:`text-label-14-strong tabular-nums text-heading`,children:dt}),at&&(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:KC(at.finishedAt??at.startedAt)})]})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start gap-2`,children:[rt&&(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:a,children:`Scan history`}),(0,Q.jsx)(X,{text:ow,placement:`bottom`})]}),(0,Q.jsxs)(`select`,{id:a,"aria-label":`View an Agent Readiness audit scan`,value:d??ue??``,onChange:e=>wt(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:aw}),nt.map(e=>(0,Q.jsx)(`option`,{value:e.runId,children:sw(e)},e.runId))]})]}),!I&&!ae&&(0,Q.jsxs)(`div`,{className:Zt(`flex items-end gap-2`,rt&&`pt-5`),children:[(0,Q.jsxs)(`details`,{ref:u,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)(E,{className:`size-4`,"aria-hidden":`true`}),`Scan settings`,(0,Q.jsx)(r,{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:St,onChange:t=>te(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:St,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:ZS[`geographic-signals`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Geographic signals`,checked:b,disabled:St,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:ZS[`agent-skill-exposure`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Agent integrations`,checked:S,disabled:St,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:St,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(B.data)}),[...hc(B.data)?[hc(B.data)]:[],...lw].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:O===null?``:String(O),disabled:St,onChange:e=>k(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:uw.map(e=>(0,Q.jsx)(`option`,{value:e.value===null?``:String(e.value),children:e.label},String(e.value)))})]})]})]}),(0,Q.jsxs)(ds,{onClick:Tt,disabled:St,children:[St?(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(M,{className:`size-4`,"aria-hidden":`true`}),se?.status===`running`?`Scan running`:se?.status===`queued`?`Scan queued`:`Run scan`]})]})]})]}),ae&&(0,Q.jsx)(Bs,{projectName:e,kind:gr[`site-audit`],loadSchedule:!re}),U?.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:ew(`pagesFound`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.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:ew(`pagesChecked`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.counts.pagesFetched)})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`div`,{className:`text-label-12 text-muted`,title:OS(`eligible`),children:`Indexable`}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.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:ew(`internalLinks`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.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:EC.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`site-health-${e.id}-tab`,"aria-selected":o===e.id,"aria-controls":`site-health-${e.id}-panel`,tabIndex:o===e.id?0:-1,ref:e=>{l.current[t]=e},onClick:()=>Dt(e.id),onKeyDown:e=>Ot(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 ${o===e.id?`border-strong text-heading`:`border-transparent text-secondary hover:border-base hover:text-primary`}`,children:e.label},e.id))}),U?.hasCrawlData&&o!==`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:mt.tone,children:mt.label})]})]}),!d&&se&&!ve&&(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.`}),ht&&(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:ht.requested}),` and continued at`,` `,(0,Q.jsx)(`span`,{className:`font-mono text-primary`,children:ht.effective}),`.`,` `,`The map and inventory use the new address.`]}),U?.hasCrawlData&&!U.complete&&(0,Q.jsxs)(`div`,{className:`rounded-md border border-caution bg-caution-soft px-4 py-3 text-label-14 text-caution`,role:`status`,children:[pw(U.termination),` `,!I&&!ae?fw(U.termination):null]}),!se&&it===`failed`&&!d&&(0,Q.jsxs)(`div`,{className:`flex gap-3 rounded-md border border-negative bg-negative-soft px-4 py-3 text-label-14 text-negative`,role:`alert`,children:[(0,Q.jsx)(D,{className:`mt-0.5 size-4 shrink-0`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:U?.hasCrawlData?`The latest scan failed. The previous completed results remain available.`:`The latest scan failed, and there are no earlier results to show.`})]}),Se?(0,Q.jsx)(Jw,{view:Ct,children:(0,Q.jsx)(Xw,{phase:Se,progress:ge.data,onRunAgain:ae?void 0:Tt})}):xe?(0,Q.jsx)(Jw,{view:Ct,children:(0,Q.jsx)(Yw,{status:ge.data?.phase??(ve?.status===`running`?`running`:`queued`),progress:ge.data,progressError:ge.isError,onRetryProgress:()=>{ge.refetch()}})}):o===`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)(wC,{projectName:e,projectId:t,runId:we,integrated:!0})}):Ce.isLoading?(0,Q.jsx)(Jw,{view:o,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)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading Agent Readiness…`]})}):Ce.error?(0,Q.jsx)(Jw,{view:o,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 Ce.refetch(),children:`Try again`})]})}):U?.hasCrawlData?U.detailsAvailable?o===`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)(c,{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:jC(Me.data?.pages[0]?.inventorySummary),rootHost:gt,filterUnavailable:Me.data?.pages[0]?.healthStateFilter===`unavailable-legacy-scan`,selectedNodeKey:Qe,onSelect:_,hasNextPage:!!Me.hasNextPage,isFetchingNextPage:Me.isFetchingNextPage,onLoadMore:()=>void Me.fetchNextPage(),filter:A,onFilterChange:j,sites:ke,siteFilter:W,onSiteFilterChange:P}),(0,Q.jsx)(Nw,{page:Ze,isLoading:et.isLoading&&!!Ze,error:et.error,inbound:et.data?.inbound??[],outbound:et.data?.outbound??[],inboundTruncated:et.data?.inboundTruncated??!1,outboundTruncated:et.data?.outboundTruncated??!1,audit:tt.data,auditLoading:tt.isLoading&&!!Ze,auditError:tt.error,onRetryAudit:()=>{tt.refetch()},rootHost:gt,reasonSource:Ye,reasonsState:$e,onRetryReasons:()=>{Je.refetch()},showTemplateLinks:ne||Be,siteHosts:Ae})]}):(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 `,ZC(De.data.nodes.length),` of `,ZC(De.data.totalNodes),` pages`,` and `,ZC(De.data.edges.length),` of `,ZC(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:ne,contentEdgeCount:Re,templateEdgeCount:Le,totalEdgeCount:Ie.length}),(0,Q.jsx)(X,{text:Sw(ze,{staleLayout:He&&!Be})})]}),(0,Q.jsxs)(`label`,{className:Zt(`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:ne&&!Be,disabled:Be,onChange:e=>F(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:ke.length>1?`Sites and folders in this scan`:`Folders in this scan`})]}),(0,Q.jsx)(`div`,{className:`max-h-[468px] overflow-auto`,children:we&&ke.length>1?(0,Q.jsx)(`ul`,{className:`divide-y divide-default`,children:ke.map((t,n)=>(0,Q.jsx)(Lw,{site:t,children:(0,Q.jsx)(Rw,{projectName:e,runId:we,site:t.host,parentPath:`/`,onSelect:Et,rootPage:n===0?bt:null,onSelectRootPage:_})},t.host))}):we&&(0,Q.jsx)(Rw,{projectName:e,runId:we,parentPath:`/`,onSelect:Et,rootPage:bt,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:()=>s(`inventory`),children:`Open page inventory`})]})}):(0,Q.jsx)(XS,{nodes:De.data?.nodes??[],edges:Ie,showTemplateLinks:ne||Be,layoutState:De.data?.layout.state??`unavailable`,layoutUnavailableReason:De.data?.layout.state===`unavailable`?De.data.layout.reason:null,rootNodeKey:De.data?.rootNodeKey??null,selectedNodeKey:Qe,onSelectNode:e=>_(e.nodeKey),onOpenInventory:()=>s(`inventory`),ariaLabel:`Interactive site map showing ${tw(De.data?.nodes.length??0,`page`)} and ${tw(Ve.length,`internal link`)}`})})]})]}),(0,Q.jsx)(Nw,{page:Ze,isLoading:et.isLoading&&!!Ze,error:et.error,inbound:et.data?.inbound??[],outbound:et.data?.outbound??[],inboundTruncated:et.data?.inboundTruncated??!1,outboundTruncated:et.data?.outboundTruncated??!1,audit:tt.data,auditLoading:tt.isLoading&&!!Ze,auditError:tt.error,onRetryAudit:()=>{tt.refetch()},rootHost:gt,reasonSource:Ye,reasonsState:$e,onRetryReasons:()=>{Je.refetch()},showTemplateLinks:ne||Be,siteHosts:Ae})]}):(0,Q.jsx)(Jw,{view:o,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:o,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:ae?tc:U?.legacyAuditAvailable?`The existing score is preserved. Run a new scan to build the page and internal-link map.`:I?`An Agent Readiness audit scan has not been run for this project.`:`Run a scan to discover pages, site sections, and internal links.`}),U?.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:()=>s(`technical`),children:`View score`})})]})})]})}function Qw({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=H({...Mo({client:Y,path:{name:e},query:{limit:30}}),enabled:n===`health`}),l=H({...Ni({client:Y,path:{name:e},query:{kind:gr[`answer-visibility`],limit:100}}),enabled:n===`compare`}),u=(l.data??[]).filter(e=>(e.status===vt.completed||e.status===vt.partial)&&e.trigger!==Ae.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=H({...Na({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)(_l,{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)(Uc,{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)(ws,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`No coverage history yet`}),(0,Q.jsx)(`p`,{children:Te()?Is:`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:U(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:kr.label}):U(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)(ws,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`Two completed checks are required`}),(0,Q.jsx)(`p`,{children:Te()?Is:`Run another AI Visibility check before comparing historical evidence.`})]}):null,h.data&&_.length===0?(0,Q.jsxs)(ws,{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 $w={state:`not-connected`,selection:null,snapshotCount:0,evidence:`No stored evidence yet.`,lastSnapshotAt:null},eT={contract:null,assessment:null,googleAds:$w,gtm:$w,snapshots:[]};function tT(e){return e.contractSelectionRequired?`contract-selection-required`:e.assessmentState===`loading`?`assessment-loading`:e.assessmentState===`unavailable`?`assessment-unavailable`:oT(e)?`static-mismatch`:e.assessment?.status??(e.contract?`configured`:`not-configured`)}function nT(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 rT(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 iT(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 aT(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`&&sT(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 oT(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome===`fail`)}function sT(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome!==`pass`)}function cT(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 lT(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 uT(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 dT(e){return e.length<=12?e:`…${e.slice(-10)}`}function fT(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 pT(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 mT={"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 hT(e){return e.outcome===`pass`?{label:mT[e.code],tone:`positive`,outcome:`Pass`}:e.outcome===`fail`?{label:mT[e.code],tone:`negative`,outcome:`Fail`}:{label:mT[e.code],tone:`caution`,outcome:`Unknown`}}function gT(e){return e.runtime.productionHosts.length>0?e.runtime.productionHosts.join(`, `):`the declared production site`}function _T(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 vT(e){return e.provider===`google-ads`?`Google Ads`:`Tag Manager`}function yT({label:e,connection:t,changeSelectionLabel:n,onChangeSelection:r,actionPending:i}){let a=cT(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 ${qr(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)(ds,{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 bT=`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.`,xT=`Available once Google Ads and Tag Manager are connected.`;function ST({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:rT(e)},{title:`Tag Manager`,state:e.gtm.state,ready:s,summary:e.gtm.selection,changeLabel:`Change Tag Manager container`,onChange:r,action:l?d:iT(e)}],p=o&&s&&!u?aT(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:bT})]}),p&&t?(0,Q.jsx)(ds,{type:`button`,disabled:i,onClick:()=>t(p.id),children:i?`Working…`:p.label}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:xT})]}),(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`}:cT(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)(ds,{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)(ds,{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 CT({workspace:e=eT,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=tT(e),m=nT(p),h=aT(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)(ST,{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 `,qr(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:[vT(e),` `,e.kind,`, captured `,qr(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)(ds,{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)(ds,{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:fT(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:pT(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:dT(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:dT(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:dT(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:dT(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=hT(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=lT(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:uT(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:[yT({label:`Google Ads`,connection:e.googleAds,...e.googleAds.state===`connected`||e.googleAds.state===`stale`?{changeSelectionLabel:`Change Google Ads account`,onChangeSelection:u}:{},actionPending:n}),yT({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:qr(e.capturedAt)}),(0,Q.jsx)(`td`,{className:`text-label-12-mono text-muted`,children:dT(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=hT(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 `,gT(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:dT(e.contract.gtm.tagId)}),` fires with `,_T(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:dT(e.contract.googleAds.conversionActionId)}),`. Do not change the account or publish a Tag Manager version just to verify it.`]})]})]}):null]})}var wT=3e4,TT={name:``,eventName:``,conversionActionId:``,conversionId:``,conversionLabel:``,campaignIds:``,tagId:``,triggerIds:``,variableIds:``,productionHosts:``,requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},ET=`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`,DT=`text-label-14-strong text-secondary`;function OT(e,t,n,r){return n?{snapshotCount:e,snapshotState:`unavailable`,snapshotError:Ss(r)}:t?{snapshotCount:e,snapshotState:`loading`}:{snapshotCount:e}}function kT(e){return[...new Set(e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function AT(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 jT(e,t,n){let r=[`Container ${e}`,`account ${t}`];return n&&r.push(`workspace ${n}`),r.join(` · `)}function MT(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:jT(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 NT(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:kT(e.campaignIds),requireBiddableGoal:e.requireBiddableGoal,requirePrimaryAction:e.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:e.tagId.trim(),triggerIds:kT(e.triggerIds),variableIds:kT(e.variableIds)},runtime:{verificationRequired:e.verificationRequired,requireTransactionId:e.requireTransactionId,requireValue:e.requireValue,requireCurrency:e.requireCurrency,productionHosts:kT(e.productionHosts)}}}function PT(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 FT(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 IT(e,t,n){return e?`no longer accessible`:n?`access not verified`:t?`not in the current result`:`checking access`}function LT({id:e,label:t,value:n,onChange:r,children:i,disabled:a=!1}){return(0,Q.jsxs)(`label`,{htmlFor:e,className:DT,children:[t,(0,Q.jsx)(`select`,{id:e,className:ET,value:n,onChange:e=>r(e.target.value),disabled:a,children:i})]})}function RT({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 zT({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(Ss(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)(ds,{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)(ds,{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 BT({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:DT,children:t});return i?(0,Q.jsxs)(`div`,{children:[m,(0,Q.jsx)(`select`,{id:e,className:ET,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:ET,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:ET,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:ET,value:c,onChange:e=>l(e.target.value)}):(0,Q.jsxs)(`select`,{id:e,required:!0,className:ET,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 VT({projectId:e,projectName:t}){let n=oi(),[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)(TT),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null),P=H({...Da({client:Y,path:{name:t}}),staleTime:wT}),ee=H({...wo({client:Y,path:{name:t}}),staleTime:wT}),te=H({...No({client:Y,path:{name:t}}),staleTime:wT}),ne=H({...bi({client:Y,path:{name:t}}),staleTime:wT}),F=ne.data,I=H({...Ga({client:Y,path:{name:t},query:{limit:5}}),staleTime:wT}),L=H({...Ta({client:Y,path:{name:t},query:{limit:5}}),staleTime:wT}),re=te.data??[],ie=(j?re.find(e=>e.id===j)??null:null)??(re.length===1?re[0]??null:null),ae=re.length>1&&!ie,R=H({...aa({client:Y,path:{name:t,contractId:ie?.id??``}}),enabled:!!ie,staleTime:wT}),z=H({...no({client:Y,path:{name:t}}),enabled:d===`google-ads`&&P.data?.connected===!0,staleTime:0}),B=H({...Va({client:Y,path:{name:t}}),enabled:d===`gtm`&&ee.data?.connected===!0,staleTime:0}),V=H({...Ua({client:Y,path:{name:t,accountId:x}}),enabled:d===`gtm`&&!!x,staleTime:0}),se=H({...$a({client:Y,path:{name:t,accountId:x,containerId:C}}),enabled:d===`gtm`&&!!x&&!!C,staleTime:0}),ce=oe(Yi({client:Y})),le=oe(ta({client:Y})),ue=oe(Mi({client:Y})),de=oe(Wi({client:Y})),fe=oe(Zi({client:Y})),pe=oe(ki({client:Y})),me=oe(eo({client:Y})),he=oe(fo({client:Y})),ge=oe(Xa({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||!ee.isSuccess)return;let e=ee.data.selection;S(e?.accountId??``),w(e?.containerId??``),E(e?.workspaceId??``),g(!0)},[h,ee.data,ee.isSuccess,d]),(0,Z.useEffect)(()=>{j&&te.data&&(te.data.some(e=>e.id===j)||M(null))},[te.data,j]);let _e=(0,Z.useMemo)(()=>{let e=I.data?.snapshots??[],t=L.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=R.data?.googleAdsSnapshot,a=R.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:R.data?.assessment.contract??ie,assessment:R.data?.assessment??null,contractSelectionRequired:ae,assessmentState:ie?R.isError?`unavailable`:R.isLoading?`loading`:void 0:void 0,assessmentError:R.isError?Ss(R.error):null,googleAds:AT(P.data,OT(I.data?.total??0,I.isLoading,I.isError,I.error),P.isError),gtm:MT(ee.data,OT(L.data?.total??0,L.isLoading,L.isError,L.error),ee.isError),snapshots:n,assessmentEvidenceSnapshots:r}},[ie,ae,I.data,I.error,I.isError,I.isLoading,P.data,P.isError,L.data,L.error,L.isError,L.isLoading,ee.data,ee.isError,R.data,R.error,R.isError,R.isLoading]),ve=(0,Z.useSyncExternalStore)(Ms,Qs,Qs),ye=Object.values(ve.runs).some(t=>t.projectId===e&&(t.kind===gr[`google-ads-sync`]||t.kind===gr[`gtm-sync`])),be=ce.isPending||le.isPending||ue.isPending||de.isPending||fe.isPending||pe.isPending||me.isPending||he.isPending||ge.isPending||ye;async function xe(){await Promise.all([P.refetch(),ee.refetch(),te.refetch(),I.refetch(),L.refetch(),ne.refetch(),ie?R.refetch():Promise.resolve()])}async function Se(e){await xe();for(let t=0;t<10&&!e();t+=1)await new Promise(e=>setTimeout(e,1500)),await xe()}function Ce(){let e=document.activeElement;N.current=e instanceof HTMLElement?e:null}function U(e){typeof window<`u`&&typeof window.requestAnimationFrame==`function`?window.requestAnimationFrame(e):globalThis.setTimeout(e,0)}function we(e){e&&(!e.matches(`a[href], button, input, select, textarea, summary, [contenteditable="true"]`)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=-1),e.focus({preventScroll:!0}))}function Te(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`}),we(document.getElementById(t)??n)}function Ee(e,t){Ce(),U(()=>Te(e,t))}function De(){let e=N.current;N.current=null,e&&U(()=>{e.isConnected&&e.focus({preventScroll:!0})})}function Oe(){i(null),c(!1),De()}function ke(){i(null),f(null),De()}function Ae(){i(null),O(!1),De()}function W(){i(null),f(null),c(!0),Ee(`google-ads-connect-panel`,`google-ads-connect-title`)}function je(){i(null),v(``),b(``),m(!1),f(`google-ads`),c(!1),Ee(`google-ads-selection-panel`,`google-ads-selection-title`)}function Me(){i(null),S(``),w(``),E(``),g(!1),f(`gtm`),c(!1),Ee(`gtm-selection-panel`,`gtm-selection-title`)}function Ne(){i(null),O(!0),Ee(`conversion-integrity-contract-form`,`conversion-integrity-contract-form-title`)}function Pe(e,n){Ks({id:e.id,projectId:e.projectId,kind:e.kind,projectLabel:t,sourceAction:n}),ci({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 Fe(){jc(n),i(null);try{let e=await ce.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.`),PT(e.authorizationUrl,()=>{xe(),o(null),De()})}catch(e){i(Ss(e))}}async function Ie(){jc(n),i(null);try{let e=await le.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.`),PT(e.authorizationUrl,()=>{xe(),o(null),De()})}catch(e){i(Ss(e))}}async function Le(){if(jc(n),!_)i(`Select a Google Ads customer before saving.`);else{i(null);try{await ue.mutateAsync({path:{name:t},body:{customerId:_,...y.trim()?{loginCustomerId:y.trim()}:{}}}),f(null),De(),await Se(()=>P.data?.selectedCustomer!=null)}catch(e){i(Ss(e))}}}async function Re(){if(jc(n),!x||!C)i(`Select a Tag Manager account and container before saving.`);else{i(null);try{await de.mutateAsync({path:{name:t},body:{accountId:x,containerId:C,...T?{workspaceId:T}:{}}}),f(null),De(),await Se(()=>ee.data?.status===`connected`)}catch(e){i(Ss(e))}}}async function ze(){jc(n),i(null),await me.mutateAsync({path:{name:t}}),f(null),c(!1),v(``),b(``),m(!1),o(null),await xe(),ci({title:`Google Ads disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`google-ads-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,U(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Be(){jc(n),i(null),await he.mutateAsync({path:{name:t}}),f(null),S(``),w(``),E(``),g(!1),o(null),await xe(),ci({title:`Tag Manager disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`gtm-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,U(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Ve(){jc(n),i(null);try{Pe(await fe.mutateAsync({path:{name:t}}),`google-ads-sync`)}catch(e){i(Ss(e))}}async function He(){jc(n),i(null);try{Pe(await pe.mutateAsync({path:{name:t}}),`gtm-sync`)}catch(e){i(Ss(e))}}async function Ue(){jc(n),i(null);try{let e=await Promise.allSettled([fe.mutateAsync({path:{name:t}}),pe.mutateAsync({path:{name:t}})]),[n,r]=e;n.status===`fulfilled`&&Pe(n.value,`google-ads-sync`),r.status===`fulfilled`&&Pe(r.value,`gtm-sync`);let i=e.find(e=>e.status===`rejected`);if(i?.status===`rejected`)throw i.reason}catch(e){i(Ss(e))}}async function We(){jc(n);let e=P.data?.connection?.selection.customerId,r=ee.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 ge.mutateAsync({path:{name:t},body:NT(k,e,{accountId:r.accountId,containerId:r.containerId})});A(TT),O(!1),De(),(await te.refetch()).data?.some(e=>e.id===n.id)&&M(n.id)}catch(e){i(Ss(e))}}}function Ge(e){switch(e){case`connect-google-ads`:W();return;case`connect-gtm`:Ce(),Ie();return;case`select-google-ads`:je();return;case`select-gtm`:Me();return;case`sync-google-ads`:Ve();return;case`sync-gtm`:He();return;case`sync-static-evidence`:Ue();return;case`declare-contract`:Ne();return;case`review-findings`:Ee(`conversion-integrity-findings`,`conversion-integrity-findings`);return;case`review-runtime-verification`:Ee(`conversion-integrity-runtime-guidance`,`conversion-integrity-runtime-title`);return;case`retry-connection-status`:xe();return;case`select-contract`:Ee(`conversion-integrity-contract-select`,`conversion-integrity-contract-select`);return;case`retry-integrity`:R.refetch();return;case`waiting-for-integrity`:return}}let Ke=z.data?.customers??[],qe=B.data?.accounts??[],G=V.data?.containers??[],Je=se.data?.workspaces??[],Ye=!!_&&!Ke.some(e=>e.customerId===_),Xe=!!x&&!qe.some(e=>e.id===x),Ze=!!C&&!G.some(e=>e.id===C),Qe=!!T&&!Je.some(e=>e.id===T),$e=Ye&&z.isSuccess&&z.data.truncated===!1,et=Xe&&B.isSuccess&&B.data.truncated===!1,tt=Ze&&V.isSuccess&&V.data.truncated===!1,nt=Qe&&se.isSuccess&&se.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=IT($e,z.data,z.isError),ot=IT(et,B.data,B.isError),st=IT(tt,V.data,V.isError),ct=IT(nt,se.data,se.isError),lt=z.isError?Ss(z.error):null,ut=B.isError?Ss(B.error):V.isError?Ss(V.error):se.isError?Ss(se.error):null,dt=d===`google-ads`?lt:d===`gtm`?ut:null,ft=FT(`customer`,z.data,Ke.length),pt=FT(`account`,B.data,qe.length),mt=FT(`container`,V.data,G.length),ht=FT(`draft workspace`,se.data,Je.length),gt=B.isError||V.isError||se.isError&&!!T,_t=s||d!==null||D;function vt(){z.refetch()}function yt(){B.isError?B.refetch():V.isError?V.refetch():se.isError&&se.refetch()}return P.isLoading||ee.isLoading||te.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…`})]}):te.isError&&!te.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: `,Ss(te.error)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void te.refetch(),children:`Retry contracts`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(CT,{workspace:_e,onPrimaryAction:Ge,actionPending:be,actionError:_t?null:r,contracts:re,selectedContractId:ie?.id??null,onSelectContract:e=>M(e||null),contractError:te.isError?Ss(te.error):null,onRetryContracts:()=>void te.refetch(),onRetryEvidence:()=>{Promise.all([I.refetch(),L.refetch()])},onChangeGoogleAdsSelection:je,onChangeGtmSelection:Me,onAddContract:()=>Ge(`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:si(async e=>{e.preventDefault(),await Fe()}),children:[(0,Q.jsxs)(`label`,{htmlFor:`google-ads-developer-token`,className:DT,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:ET,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)(ds,{type:`submit`,disabled:ce.isPending,children:ce.isPending?`Starting…`:`Continue to Google`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:Oe,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)(LT,{id:`google-ads-customer`,label:`Customer account`,value:_,onChange:e=>{m(!0),v(e);let t=Ke.find(t=>t.customerId===e);b(t?.parentCustomerId??``)},disabled:z.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:z.isLoading?`Loading accessible customers…`:`Select a customer`}),Ye?(0,Q.jsxs)(`option`,{value:_,disabled:$e,children:[`Saved customer `,_,` (`,at,`)`]}):null,Ke.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:DT,children:[`Manager account ID (optional)`,(0,Q.jsx)(`input`,{id:`google-ads-login-customer`,className:ET,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 ${z.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)(ds,{type:`button`,disabled:ue.isPending||z.isLoading||z.isError||$e||!_,onClick:si(Le),children:ue.isPending?`Saving…`:`Save customer selection`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]}),P.data?.connected?(0,Q.jsx)(zT,{providerLabel:`Google Ads`,disabled:be,onDisconnect:ze}):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:B.isError?`Retry account list`:V.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)(LT,{id:`gtm-account`,label:`Account`,value:x,onChange:e=>{g(!0),e!==x&&(w(``),E(``)),S(e)},disabled:B.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:B.isLoading?`Loading accounts…`:`Select an account`}),Xe?(0,Q.jsxs)(`option`,{value:x,disabled:et,children:[`Saved account `,x,` (`,ot,`)`]}):null,qe.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(LT,{id:`gtm-container`,label:`Container`,value:C,onChange:e=>{g(!0),e!==C&&E(``),w(e)},disabled:!x||V.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:V.isLoading?`Loading containers…`:`Select a container`}),Ze?(0,Q.jsxs)(`option`,{value:C,disabled:tt,children:[`Saved container `,C,` (`,st,`)`]}):null,G.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(LT,{id:`gtm-workspace`,label:`Draft workspace (optional)`,value:T,onChange:e=>{g(!0),E(e)},disabled:!C||se.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:se.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:B.data?.truncated?`text-caution`:`text-secondary`,children:pt}):null,mt?(0,Q.jsx)(`p`,{role:`status`,className:V.data?.truncated?`text-caution`:`text-secondary`,children:mt}):null,ht?(0,Q.jsx)(`p`,{role:`status`,className:se.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)(ds,{type:`button`,disabled:de.isPending||B.isLoading||V.isLoading||se.isLoading&&!!T||gt||rt||!x||!C,onClick:si(Re),children:de.isPending?`Saving…`:`Save container selection`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]}),ee.data?.connected?(0,Q.jsx)(zT,{providerLabel:`Tag Manager`,disabled:be,onDisconnect:Be}):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:si(async e=>{e.preventDefault(),await We()}),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:DT,children:[`Conversion name`,(0,Q.jsx)(`input`,{id:`contract-name`,required:!0,maxLength:120,className:ET,value:k.name,onChange:e=>A(t=>({...t,name:e.target.value})),placeholder:`Booking completed`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-event-name`,className:DT,children:[`Website event`,(0,Q.jsx)(`input`,{id:`contract-event-name`,required:!0,className:ET,value:k.eventName,onChange:e=>A(t=>({...t,eventName:e.target.value})),placeholder:`booking_complete`})]}),(0,Q.jsx)(BT,{id:`contract-conversion-action`,label:`Google Ads conversion action`,options:F?.googleAds.conversionActions??[],synced:F?.googleAds.syncedAt!=null,loading:ne.isLoading,failed:ne.isError,onRetry:()=>void ne.refetch(),emptyHint:`Run a Google Ads sync to list conversion actions.`,value:k.conversionActionId,onChange:e=>A(t=>({...t,conversionActionId:e}))}),(0,Q.jsx)(BT,{id:`contract-gtm-tag`,label:`Tag Manager tag`,options:F?.gtm.tags??[],synced:F?.gtm.syncedAt!=null,loading:ne.isLoading,failed:ne.isError,onRetry:()=>void ne.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:DT,children:[`Google conversion ID (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-id`,className:ET,value:k.conversionId,onChange:e=>A(t=>({...t,conversionId:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-conversion-label`,className:DT,children:[`Google conversion label (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-label`,className:ET,value:k.conversionLabel,onChange:e=>A(t=>({...t,conversionLabel:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-trigger-ids`,className:DT,children:[`Trigger IDs`,(0,Q.jsx)(`input`,{id:`contract-trigger-ids`,className:ET,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:DT,children:[`Variable IDs`,(0,Q.jsx)(`input`,{id:`contract-variable-ids`,className:ET,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:DT,children:[`Campaign IDs`,(0,Q.jsx)(`input`,{id:`contract-campaign-ids`,className:ET,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:DT,children:[`Production hosts`,(0,Q.jsx)(`input`,{id:`contract-production-hosts`,className:ET,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)(RT,{id:`contract-primary-action`,checked:k.requirePrimaryAction,onChange:e=>A(t=>({...t,requirePrimaryAction:e})),children:`Google Ads action is primary`}),(0,Q.jsx)(RT,{id:`contract-biddable-goal`,checked:k.requireBiddableGoal,onChange:e=>A(t=>({...t,requireBiddableGoal:e})),children:`Google Ads goal is biddable`}),(0,Q.jsx)(RT,{id:`contract-runtime-verification`,checked:k.verificationRequired,onChange:e=>A(t=>({...t,verificationRequired:e})),children:`Runtime proof is required`}),(0,Q.jsx)(RT,{id:`contract-transaction-id`,checked:k.requireTransactionId,onChange:e=>A(t=>({...t,requireTransactionId:e})),children:`Transaction ID is required`}),(0,Q.jsx)(RT,{id:`contract-value`,checked:k.requireValue,onChange:e=>A(t=>({...t,requireValue:e})),children:`Conversion value is required`}),(0,Q.jsx)(RT,{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)(ds,{type:`submit`,disabled:ge.isPending,children:ge.isPending?`Saving…`:`Save conversion contract`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:Ae,children:`Cancel`})]})]})]}):null]})}var HT=6e4,UT=[`7d`,`14d`,`30d`],WT=`not available`,GT=`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%.`,KT=`No Google Ads snapshot stored yet`,qT=`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.`,JT=`No closed days yet`,YT=`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.`,XT={"insufficient-history":`Period change is hidden: the stored snapshot does not cover a prior period of equal length yet.`},ZT=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),QT=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),$T=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function eE(e,t){return e===null||!Number.isFinite(e)?WT:t===null?$T.format(e/1e6):cl(e,t)}function tE(e){return e===null||!Number.isFinite(e)?WT:U(e)}function nE(e,t){return e===null||!Number.isFinite(e)?`${WT} vs prior ${t}d`:e===0?`no change vs prior ${t}d`:`${e>0?`↑`:`↓`} ${U(Math.abs(e))} vs prior ${t}d`}function rE(e){return e===`enabled`?`positive`:e===`paused`?`caution`:`neutral`}function iE(e){return e===`enabled`?`Enabled`:e===`paused`?`Paused`:e===`removed`?`Removed`:`Unknown`}function aE(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 oE({projectName:e}){let[t,n]=(0,Z.useState)(`14d`),[r,i]=(0,Z.useState)(()=>new Set([`costMicros`,`conversions`])),a=H({...mo({client:Y,path:{name:e},query:{window:t}}),staleTime:HT}),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:GT})]}),o?.source?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[Jr(o.startDate),` to `,Jr(o.endDate),` · `,o.days,` closed `,o.days===1?`day`:`days`]}):null]}),(0,Q.jsx)(wu,{windows:UT,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: `,Ss(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?JT:KT}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e?YT:qT})]})]})}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:eE(c.costMicros,m),change:d?.change.costMicros??null,direction:`none`,seriesKey:`costMicros`},{key:`conversions`,comparable:!0,label:`Conversions`,value:QT.format(c.conversions),change:d?.change.conversions??null,direction:`up-good`,seriesKey:`conversions`},{key:`cost-per-conversion`,label:`Cost / conv.`,value:g?`no conversions`:eE(c.costPerConversionMicros,m),change:null,comparable:!1,direction:`down-good`,seriesKey:null},{key:`conversion-rate`,comparable:!0,label:`Conv. rate`,value:tE(c.conversionRate),change:d?.change.conversionRate??null,direction:`up-good`,seriesKey:null}],v=[{key:`clicks`,label:`Clicks`,value:ZT.format(c.clicks),seriesKey:`clicks`},{key:`impressions`,label:`Impressions`,value:ZT.format(c.impressions),seriesKey:`impressions`},{key:`ctr`,label:`CTR`,value:tE(c.ctr),seriesKey:`ctr`},{key:`cpc`,label:`CPC`,value:eE(c.cpcMicros,m),seriesKey:null}],y={costMicros:{label:`Spend`,color:Rr[1],axisId:`spend`,formatValue:e=>eE(e,m)},conversions:{label:`Conversions`,color:Rr[0],axisId:`conversions`,formatValue:e=>QT.format(e)},clicks:{label:`Clicks`,color:Rr[2],axisId:`clicks`,formatValue:e=>ZT.format(e)},impressions:{label:`Impressions`,color:Rr[3],axisId:`impressions`,formatValue:e=>ZT.format(e)},ctr:{label:`CTR`,color:Rr[4],axisId:`ctr`,formatValue:e=>tE(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 `,ZT.format(h.queried),` of`,` `,ZT.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:XT[`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 ${aE(e.change,e.direction)}`,children:nE(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)(Br,{data:l,xKey:`date`,series:b,xTickFormatter:Vr,labelFormatter:Jr}),(0,Q.jsx)(`ul`,{className:`sr-only`,children:l.map(e=>(0,Q.jsxs)(`li`,{children:[Jr(e.date),`:`,` `,b.map(t=>{let n=e[t.dataKey];return`${t.label} ${n===null?WT: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:rE(e.status),children:iE(e.status)})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:ZT.format(e.totals.impressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:ZT.format(e.totals.clicks)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:eE(e.totals.costMicros,m)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:QT.format(e.totals.conversions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:tE(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:eE(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:Hr(Wr(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:Jr(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:Jr(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 sE={proposed:{label:`New`,tone:`caution`},confirmed:{label:`Included`,tone:`positive`},excluded:{label:`Excluded`,tone:`neutral`}};function cE(e){return e.trim().toLocaleLowerCase()}function lE(e,t){return!t||`${e.name} ${(e.urls??[e.url]).join(` `)}`.toLocaleLowerCase().includes(t)}function uE({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 dE({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)(mE,{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 fE({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=cE(r),m=t.filter(e=>lE(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=sE[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)(uE,{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 pE(e){return e.activeStep===`import`?(0,Q.jsx)(dE,{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)(fE,{...e})}function mE({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(`
6
+ `).map(e=>e.trim()).filter(Boolean).map(e=>({kind:Ce.domain,value:e,includeSubdomains:!0}))}:{}},c=$t.safeParse(s);if(!c.success)ne(c.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(` `));else{ne(null);try{await F.mutateAsync({path:{name:e,id:r},body:c.data}),await o.fetchQuery(po({client:Y,path:{name:e}})),a(r)}catch(e){ne(Ss(e))}}},ge=(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(),he()},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:Hm,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&&re.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:Hm,required:!0,value:g?p:``,"aria-describedby":ue?de:void 0,onChange:e=>{let n=t.scopes.find(t=>`${t.kind}:${t.key??``}`===e.target.value);m(e.target.value),me(c(h,n))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose a scope`}),re.map(e=>(0,Q.jsx)(`option`,{value:`${e.kind}:${e.key??``}`,children:e.label},`${e.kind}:${e.key}`))]})]}),ue&&(0,Q.jsx)(`p`,{id:de,className:`text-copy-13 text-secondary`,children:ue})]}),(0,Q.jsxs)(`div`,{className:`min-w-0 space-y-1.5`,children:[h&&I.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:Hm,required:!0,value:h?d:``,"aria-describedby":n&&!h?fe:void 0,onChange:e=>{let n=t.connections.find(t=>t.id===e.target.value);f(e.target.value),me(c(n,g))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose a source`}),I.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),n&&!h&&(0,Q.jsx)(`p`,{id:fe,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`}),se.length?(0,Q.jsx)(`div`,{className:`grid gap-x-6 sm:grid-cols-2`,children:se.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:ie.includes(e),onChange:t=>{let n=t.currentTarget.checked;S(t=>n?[...t,e]:t.filter(t=>t!==e))}}),Nm[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.`}),ce&&!n?.rankings&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Set up market rankings with the CLI or API.`}),H&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Market rankings use their own profile.`})]})}),z&&(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:H?`Choose one of this project’s own domains.`:R||ie.includes(G[`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:Hm,value:e.value,placeholder:`example.com`,"aria-label":`Target ${t+1}`,onChange:e=>ge(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:Hm,"aria-label":`Target ${t+1} kind`,value:e.kind,onChange:e=>ge(t,{kind:e.target.value,includeSubdomains:e.target.value===Ce.domain}),children:[(0,Q.jsx)(`option`,{value:Ce.domain,children:`Domain + subdomains`}),(0,Q.jsx)(`option`,{value:Ce.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>=(H?1:20),onClick:()=>w(e=>[...e,{kind:Ce.domain,value:``,includeSubdomains:!0}]),children:`Add target`})]}),ae&&(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:`${Hm} 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.`})]}),V&&(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:`${Hm} 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":pe,children:[(0,Q.jsx)(`legend`,{className:`text-heading-14 text-heading`,children:`Search settings`}),(0,Q.jsx)(`p`,{id:pe,className:`text-copy-13 text-secondary`,children:H?`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 ${B?`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:Hm,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:Hm,required:!0,minLength:2,maxLength:10,value:M,onChange:e=>N(e.target.value)})]}),B&&(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:R?`Result limit`:`Ranked searches per target`}),(0,Q.jsx)(`input`,{className:Hm,type:`number`,min:1,max:1e3,step:1,required:!0,value:P,onChange:e=>ee(e.target.value)}),R&&(0,Q.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:ae?`Each gap comparison uses this limit separately for shared and missing searches.`:`Maximum rows per target.`})]})]})]})}),te&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-secondary`,children:te}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(q,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:F.isPending||!g?.supported||!h||!ie.length,children:F.isPending?`Saving…`:`Save profile`}),(0,Q.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:i,children:`Cancel`})]})]})}var fg=[{value:`7`,label:`7d`},{value:`30`,label:`30d`},{value:`90`,label:`90d`},{value:`180`,label:`180d`}],pg=[{value:`1`,label:`1h`},{value:`24`,label:`24h`},{value:`168`,label:`7d`},{value:`720`,label:`30d`}],mg=20,hg=12,gg=20,_g=50,vg=3,yg=`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`,bg=`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,xg=`inline-flex w-fit cursor-pointer list-none items-center gap-1 rounded text-label-14 text-secondary hover:text-heading ${bg} [&::-webkit-details-marker]:hidden`,Sg=`inline-flex items-center gap-1.5 rounded text-left ${bg}`,Cg={ai:`AI referral`,search:`Search`,social:`Social`,paid:`Paid`,referral:`Referral`,direct:`Direct`},wg={cloudflare:`Cloudflare`,vercel:`Vercel`,"cloud-run":`Cloud Run`,wordpress:`WordPress`},Tg={[Ie.matched]:`Matched`,[Ie.unmatched]:`No URL match`,[Ie.ambiguous]:`Ambiguous URL match`,[Ie[`unknown-host`]]:`Host not recorded`,[Ie.redacted]:`URL redacted`,[Ie[`not-configured`]]:`No Property plan`},Eg={[En.verified]:`text-positive`,[En.likely_real]:`text-heading`,[En.unknown]:`text-secondary`},Dg=`This project's traffic source logs no IP address, so one person can't be told from another. AI-referred visits are still counted.`,Og=`Each row is everyone on one browser version, so its visits are not one person's.`,kg=(e,t)=>`${e.toLocaleString()} ${t}${e===1?``:`s`}`,Ag=e=>e.entryName??Cg[e.entryClass],jg=e=>{if(!e.entryName)return e.paid&&e.entryClass!==`paid`?`Paid`:null;let t=e.paid&&e.entryClass!==`paid`?`${Cg[e.entryClass]}, paid`:Cg[e.entryClass];return t===Ag(e)?null:t},Mg=e=>Mr(e,e),Ng=e=>e&&e.toUpperCase()!==`GET`?e.toUpperCase():null;function Pg(){let e=R({strict:!1}),t=ae(),n=B({select:e=>e.location.pathname});return{search:e,update:e=>{t({to:n,search:t=>({...t,...e}),replace:!0})}}}function Fg({projectName:e}){let{account:t}=oi(),{search:n,update:r}=Pg();if(K()||t?.role===wt.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&&(Et(`other`),r({journeyView:e.value===`visitors`?void 0:e.value}))},className:`-mb-px border-b-2 pb-2 text-label-14 transition-colors ${bg} ${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)(Vg,{projectName:e},`visitors:${e}`):(0,Q.jsx)(Xg,{projectName:e},`agents:${e}`)]})}function Ig({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 ${bg} ${e.value===t?`bg-surface-active text-heading`:`text-secondary hover:text-heading`}`,children:e.label},e.value))})}function Lg({summary:e,children:t}){let[n,i]=(0,Z.useState)(!1);return(0,Q.jsxs)(`details`,{open:n,onToggle:e=>i(e.currentTarget.open),className:`text-copy-14 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:xg,children:[n?(0,Q.jsx)(r,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`size-3.5`,"aria-hidden":`true`}),e]}),(0,Q.jsx)(`div`,{className:`mt-3`,children:t})]})}function Rg({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,`. `,Ss(t)]}),(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:n,children:`Retry`})]})}function zg({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 Bg({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)(D,{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 `,wg[t.sourceType]??t.sourceType,`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:t.reason}),(0,Q.jsx)(V,{to:`/traffic/$projectName/$sourceId`,params:{projectName:e,sourceId:t.sourceId},className:`rounded text-link underline-offset-4 hover:underline ${bg}`,children:`Review source`})]},t.sourceId))})}function Vg({projectName:e}){let{search:t,update:n}=Pg(),r=fg.some(e=>e.value===t.journeyDays)?t.journeyDays:`30`,i=t.journeyEngine??``,a=t.journeyReturned===`true`||t.journeyReturned===`false`?t.journeyReturned:``,o=t.journeyMatching===ct.ua?ct.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=H({...wi({client:Y,path:{name:e},query:u}),staleTime:3e4}),f={...u,engine:i||void 0,returned:a||void 0,keyBasis:o||ct[`ip-ua`],limit:mg,offset:s},p=H({...la({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)(Rg,{what:`the visitor summary`,error:d.error,retry:()=>{d.refetch()}}):(0,Q.jsx)(Hg,{summary:d.data}),(0,Q.jsx)(Ig,{label:`First AI visit within`,options:fg,value:r,onChange:e=>{Et(`window`),l(new Date().toISOString()),n({journeyDays:e===`30`?void 0:e,journeyOffset:void 0,journeyVisitor:void 0})}})]}),m&&(0,Q.jsx)(Bg,{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)(Rg,{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:Dg}),(0,Q.jsx)(q,{className:`mt-3`,size:`sm`,variant:`outline`,onClick:()=>{Et(`other`),n({journeyMatching:ct.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)(V,{to:`/projects/$projectName/traffic`,params:{projectName:e},className:`mt-2 inline-block text-link hover:underline`,children:`Review traffic sources`})]}):m?(0,Q.jsx)(Wg,{projectName:e,data:m,engines:d.data?.byEngine.map(e=>e.engine)??[],engine:i,returned:a,matching:o,openKey:h,onToggle:e=>{e&&qe(`journeys.visitor_open`),n({journeyVisitor:e??void 0})},onFilter:e=>{Et(`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)(Lg,{summary:`About this data`,children:(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[d.data&&(0,Q.jsx)(Jg,{summary:d.data}),m&&(0,Q.jsx)(Yg,{data:m})]})})]})}function Hg({summary:e}){let t=(0,Q.jsx)(zg,{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)(zg,{label:`Visitors and returns`,help:Dg,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:U(e.returnRate,et.fraction),i=e.keyBasis.ua>0?`${kg(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)(zg,{label:`AI-referred visitors`,help:i,children:e.aiVisitors.toLocaleString()}),(0,Q.jsxs)(zg,{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)(zg,{label:`Median time to return`,children:e.medianDaysToReturn===null?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not available`}):Ht(e.medianDaysToReturn)}),(0,Q.jsx)(zg,{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:[Cg[e],` `,(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:t.toLocaleString()})]},e))})})]})}function Ug({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=`${Ag(e)}${e.paid?` (paid)`:``}`,n=r.at(-1);n?.label===t?n.visits++:r.push({label:t,visits:1})}let i=r.slice(0,vg),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 Wg({projectName:e,data:t,engines:n,engine:i,returned:o,matching:s,openKey:c,onToggle:l,onFilter:u,onPage:d}){let f=!!(i||o||s),p=s===ct.ua,m=t.totalVisitors===0?0:t.offset+1,g=t.offset+t.visitors.length,_=c!==null&&!t.visitors.some(e=>e.visitorKey===c);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:[m.toLocaleString(),` to `,g.toLocaleString(),` of `,kg(t.totalVisitors,p?`browser group`:`visitor`)]}),(0,Q.jsxs)(`details`,{className:`text-label-14`,open:f||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 ${bg} [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(a,{className:`size-3`,"aria-hidden":`true`}),`Filter`,f&&(0,Q.jsx)(`span`,{className:`text-heading`,children:[i,o===`true`?`Came back`:o===`false`?`No return yet`:``,p?`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:yg,value:i,onChange:e=>u({journeyEngine:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`All engines`}),i&&!n.includes(i)&&(0,Q.jsx)(`option`,{value:i,children:i}),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:yg,value:o,onChange:e=>u({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:yg,value:s,onChange:e=>u({journeyMatching:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`Network and browser`}),(0,Q.jsx)(`option`,{value:ct.ua,children:`Browser only (groups)`})]})]}),f&&(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>u({journeyEngine:void 0,journeyReturned:void 0,journeyMatching:void 0}),children:`Clear filters`})]})]})]}),p&&(0,Q.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,Q.jsx)(D,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),Og]}),c&&_&&(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:()=>l(null),children:`Close`})]}),(0,Q.jsx)(Gg,{projectName:e,visitorKey:c,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 i=n.visitorKey===c,a=n.visits.find(e=>e.entryClass===`ai`),o=`journey-visitor-${n.visitorKey}`;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:i?`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":i,"aria-controls":i?o:void 0,"aria-label":`${n.firstAiEngine} visitor, first AI visit ${Mr(n.firstAiAt)}`,onClick:()=>l(i?null:n.visitorKey),className:`${Sg} whitespace-nowrap`,children:[i?(0,Q.jsx)(r,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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:Er(n.firstAiAt)})]})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 align-top`,children:a?(0,Q.jsx)(`span`,{className:`block max-w-[18rem] truncate text-label-13-mono text-heading`,title:a.landingPath,children:ol(a.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)(Ug,{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:Er(n.lastSeenAt)})})]}),i&&(0,Q.jsx)(`tr`,{id:o,children:(0,Q.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-8`,children:(0,Q.jsx)(Gg,{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:()=>d(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:()=>d(t.offset+t.limit),children:`Next visitors`})]})]})}function Gg({projectName:e,visitorKey:t,partialSources:n}){let[r,i]=(0,Z.useState)(0),[a,o]=(0,Z.useState)(Pe.pages),[s,c]=(0,Z.useState)(null),l=H({...ko({client:Y,path:{name:e,visitorKey:t},query:{limit:hg,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)(Rg,{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:kg(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===ct.ua?`Matched by browser only`:`Matched by network and browser`,(0,Q.jsx)(X,{placement:`bottom`,text:d.keyBasis===ct.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)(D,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`text-heading`,children:[`Some requests are missing on `,kg(d.cappedDays,`day`),`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:`At most ${300 .toLocaleString()} requests per visitor are kept each day.`})]}),(0,Q.jsx)(Kg,{visits:u.visits,openId:s,events:u.events,loading:l.isFetching,onToggle:e=>{e&&qe(`journeys.visit_open`),c(e)},onToggleEvents:()=>o(a===Pe.pages?Pe.all:Pe.pages)}),m&&(0,Q.jsxs)(`p`,{className:`text-label-13 text-secondary`,children:[`Later visits are not recorded by `,wg[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)(Lg,{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:qr(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 Kg({visits:e,openId:t,events:n,loading:i,onToggle:a,onToggleEvents:o}){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 s=e.id===t,c=jg(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":s,onClick:()=>a(s?null:e.id),className:`${Sg} text-label-14 text-heading`,children:[s?(0,Q.jsx)(r,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,Q.jsx)(`time`,{dateTime:e.startedAt,children:Mr(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:Ag(e)}),c&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` · `,c]})]}),(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:ol(e.landingPath)})}),(0,Q.jsx)(`td`,{className:`py-2 text-right align-top text-label-14 tabular-nums text-heading`,children:e.pageCount.toLocaleString()})]}),s&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`pb-3 pl-6`,children:(0,Q.jsx)(qg,{visit:e,events:n,loading:i,onToggleEvents:o})})})]},e.id)})})]})}function qg({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===Pe.pages?`No pages recorded for this visit.`:`No requests recorded for this visit.`}):(0,Q.jsx)(`ol`,{"aria-label":`${Ag(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:Mg(e.ts)}),(0,Q.jsxs)(`span`,{className:`min-w-0 break-all text-label-13-mono text-heading`,children:[Ng(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[Ng(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 ${bg}`,children:t===Pe.pages?`Show all ${kg(e.requestCount,`request`)}`:`Show fewer requests`})]})}function Jg({summary:e}){return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[kg(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: `,kg(e.keyBasis.ipUa,`visitor`),` by network and browser, `,kg(e.keyBasis.ua,`visitor`),` by browser only. Visitor figures count only the first: one browser version can be many people.`]})]})}function Yg({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 `,Mr(e.windowStart),` to `,Mr(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:[wg[e.sourceType]??e.sourceType,`:`]}),` `,e.reason]},e.sourceId))]})}function Xg({projectName:e}){let{search:t,update:n}=Pg(),i=pg.some(e=>e.value===t.agentHours)?t.agentHours:`24`,[o,s]=(0,Z.useState)(()=>new Date().toISOString()),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(``),[m,g]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(0),[x,S]=(0,Z.useState)(null),[C,w]=(0,Z.useState)({properties:[],sources:[]}),T=(0,Z.useRef)(null),E={since:new Date(Date.parse(o)-Number(i)*36e5).toISOString(),until:o,sourceId:c||void 0,agentId:u?.id,trust:f||void 0,targetKey:m||void 0},D=H({...oo({client:Y,path:{name:e},query:{...E,limit:gg,offset:y}}),staleTime:3e4}),O=D.data;(0,Z.useEffect)(()=>{O&&w({properties:O.properties,sources:O.coverage.sources})},[O]);let k=O?.properties??C.properties,A=O?.coverage.sources??C.sources,j=k.find(e=>e.key===m),M=A.find(e=>e.sourceId===c),N=()=>{b(0),S(null)},P=!!(c||f||m||u);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:[O?(0,Q.jsx)(Zg,{context:O}):(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 ${bg} [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(a,{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:yg,value:c,onChange:e=>{Et(`other`),l(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All sources`}),A.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:yg,value:f,onChange:e=>{Et(`other`),p(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All trust levels`}),Object.values(En).filter(e=>e!==En.likely_fake).map(e=>(0,Q.jsx)(`option`,{value:e,children:rl[e]},e))]})]}),k.length>0&&(0,Q.jsxs)(`details`,{ref:T,className:`relative`,children:[(0,Q.jsxs)(`summary`,{className:`${yg} inline-flex cursor-pointer list-none items-center py-1.5 [&::-webkit-details-marker]:hidden`,children:[`Property: `,j?.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:_,onChange:e=>v(e.target.value),placeholder:`Find a property`,className:`${yg} 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`},...k.filter(e=>e.label.toLowerCase().includes(_.toLowerCase()))].map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":m===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 ${bg}`,onClick:()=>{Et(`other`),g(e.key),N(),T.current&&(T.current.open=!1,T.current.querySelector(`summary`)?.focus())},children:e.label},e.key))})]})]}),P&&(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>{Et(`other`),l(``),p(``),g(``),d(null),N()},children:`Clear filters`})]})]}),(0,Q.jsx)(Ig,{label:`Period`,options:pg,value:i,onChange:e=>{Et(`window`),s(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:[c&&(0,Q.jsxs)(`span`,{children:[`Source: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:M?.label??c})]}),f&&(0,Q.jsxs)(`span`,{children:[`Trust: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:rl[f]})]}),m&&(0,Q.jsxs)(`span`,{children:[`Property: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:j?.label??m})]}),u&&(0,Q.jsxs)(`span`,{children:[`Agent: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:u.label})]})]}),D.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-6 text-copy-14 text-secondary`,children:`Loading agent requests…`}):D.isError?(0,Q.jsx)(Rg,{what:`agent requests`,error:D.error,retry:()=>{D.refetch()}}):O?(0,Q.jsxs)(Q.Fragment,{children:[O.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:O.journeys.map(t=>{let n=x===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 ${Mr(t.startedAt)}`,onClick:()=>{n||qe(`journeys.agent_open`),S(n?null:t.id)},className:`${Sg} text-label-14-strong text-heading`,children:[n?(0,Q.jsx)(r,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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 ${Eg[e]}`,children:rl[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:Mr(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:kg(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)(Qg,{projectName:e,journey:t,selection:{...E,since:O.windowStart,until:O.windowEnd},onSelectAgent:()=>{Et(`other`),d({id:t.agentId,label:t.product}),N()}})})})]},t.id)})})]})}),(O.totalJourneys>O.limit||O.offset>0)&&(0,Q.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:O.offset===0||D.isFetching,onClick:()=>{b(Math.max(0,O.offset-O.limit)),S(null)},children:`Previous`}),(0,Q.jsx)(q,{variant:`outline`,size:`sm`,disabled:O.offset+O.limit>=O.totalJourneys||D.isFetching,onClick:()=>{b(O.offset+O.limit),S(null)},children:`Next agent visits`})]}),(0,Q.jsx)(Lg,{summary:`About this data`,children:(0,Q.jsx)(e_,{context:O})})]}):null]})}function Zg({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)(zg,{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)(zg,{label:`Requests`,children:e.observedRequests.toLocaleString()}),t!==null&&t>0&&(0,Q.jsx)(zg,{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)(D,{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)(D,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Some requests are missing: a source reached its daily limit.`]})]})}function Qg({projectName:e,journey:t,selection:n,onSelectAgent:r}){let[i,a]=(0,Z.useState)(0),o=H({...Ra({client:Y,path:{name:e,journeyId:t.id},query:{...n,limit:_g,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)($g,{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)(Rg,{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:[Ng(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[Ng(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:Tg[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 $g({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:Eg[t],children:rl[t]}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`: `,[...n].map(t=>nl(t,e)).join(` · `)]})]},t))})}function e_({context:e}){return(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[Mr(e.windowStart),` to `,Mr(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 t_={"non-brand":`Non-brand`,branded:`Branded`,unknown:`Unclassified`},n_={"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":kr.label};function r_({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?`—`:U(e.rate,et.fraction),(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` · `,t_[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:n_[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 i_({projectName:e,revision:t}){let n=(0,Z.useId)(),[r,i]=(0,Z.useState)(`non-brand`),a=jo({client:Y,path:{name:e},query:{queryClass:`all`,limit:1}}),o=H({...a,queryKey:[{...a.queryKey[0],tags:[t??`no-sweep`]}],staleTime:di}),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: `,Ss(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 `,t_[l.queryClass].toLowerCase(),` queries in this check.`]}):l&&(f=(0,Q.jsxs)(`table`,{className:`engine-comparison`,"aria-label":`By engine, ${t_[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)(Zc,{provider:e.provider})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(r_,{value:e.mentionCoverage,queryClass:l.queryClass})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(r_,{value:e.citationCoverage,queryClass:l.queryClass})})]},e.provider))})]})):f=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Te()?Is:`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:[t_[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 `,Mr(d),s?.selection.measurement.state===`partial`?` · incomplete`:``]}):null,c.length>1?(0,Q.jsx)(As,{label:`Query type`,className:`flex-wrap`,options:c.map(e=>({value:e.queryClass,label:t_[e.queryClass]})),value:l.queryClass,onChange:i}):null]})]}),(0,Q.jsx)(`div`,{className:`av-card-body`,children:f})]})}var a_={[vt.queued]:{word:`queued`,tone:`text-secondary`},[vt.running]:{word:`running`,tone:`text-info-300`},[vt.completed]:{word:`completed`,tone:`text-secondary`},[vt.partial]:{word:`partial`,tone:`text-caution-400`},[vt.failed]:{word:`failed`,tone:`text-negative-400`},[vt.cancelled]:{word:`cancelled`,tone:`text-secondary`}};function o_({runs:e,projectName:t,collapsed:n=!1}){let i=(0,Z.useId)(),a=(0,Z.useId)(),o=new Set(e.map(e=>e.location??``)).size>1,s=e.some(e=>e.kind!==gr[`answer-visibility`]),c=e.map(e=>`${e.startedAt}: ${e.summary}.${e.statusDetail?` ${e.statusDetail}`:``}`);return(0,Q.jsx)(`section`,{className:`overview-brief`,"aria-labelledby":i,children:(0,Q.jsxs)(`details`,{className:`av-history`,open:!n||void 0,children:[(0,Q.jsxs)(`summary`,{className:`av-card-head`,"aria-labelledby":i,"aria-describedby":e.length>0?a:void 0,children:[(0,Q.jsx)(`h2`,{id:i,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:a,className:`av-card-meta`,children:[e.length,` recent`]}):null,(0,Q.jsx)(r,{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":i,children:[(0,Q.jsx)(`thead`,{className:`sr-only`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Started`}),s?(0,Q.jsx)(`th`,{scope:`col`,children:`Type`}):null,(0,Q.jsx)(`th`,{scope:`col`,children:`Trigger`}),o?(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=a_[e.status],r=e.status===vt.partial||e.status===vt.failed;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label tabular-nums`,children:(0,Q.jsx)(Es,{run:e,projectName:t,className:`av-link`,label:e.opensSeoWorkspace?`View SEO refresh from ${e.startedAt}`:`View the ${e.startedAt} check`,children:e.startedAt})}),s?(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}),o?(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)(Tl,{items:c})]})})}var s_=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],c_=`Measured answers`,l_=`Close answers`,u_={"non-brand":`Non-brand queries`,branded:`Branded queries`,unknown:`Unclassified queries`},d_={"non-brand":`non-brand queries`,branded:`branded queries`,unknown:`unclassified queries`},f_={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.`},p_={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.`},m_=`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.`,h_=`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 g_(e){return e.kind===`project`?`Whole site`:e.kind===`group`?`${e.label} · Group`:e.kind===`market`?`${e.label} · Market`:e.label}function __(e){return e.reason===`identity-ambiguous`?wr.ambiguous:e.reason===`not-applicable`?`Not applicable`:`Not measured`}function v_({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:[__(e),(0,Q.jsx)(X,{text:Pr})]});if(e.rate===null)return(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:__(e)});let n=Fr(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:U(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 y_({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 b_(e,t){if(!e||e.state===`unavailable`)return null;let n=e[t];if(n.state===`unavailable`)switch(n.reason){case Ne[`previous-unavailable`]:return{text:f_.previousUnavailable,tone:`text-secondary`};case Ne[`current-unavailable`]:case Ne[`not-applicable`]:return null}let{direction:r,magnitude:i}=dn(n.delta);switch(r){case`up`:return{text:f_.up(i),tone:`text-positive`};case`down`:return{text:f_.down(i),tone:`text-negative`};case`none`:return{text:f_.none,tone:`text-secondary`}}}function x_(e,t){let n=Wr(e);return t!==null&&Ur(n)===Ur(Wr(t))?Qr(n):Hr(n)}function S_(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 C_(e,t){if(!e)return null;if(e.state===`unavailable`){let n=e.previousRun?x_(e.previousRun.createdAt,t):null;switch(e.reason){case Fe[`no-selected-run`]:return null;case Fe[`no-previous-run`]:return f_.noPreviousRun;case Fe[`definition-changed`]:return f_.definitionChanged(n);case Fe[`model-changed`]:return f_.modelChanged(n);case Fe[`legacy-unknown`]:return f_.legacyUnknown;case Fe[`partial-run`]:return f_.partialRun;case Fe[`scoped-run`]:return f_.scopedRun}}return f_.comparedWith(x_(e.previousRun.createdAt,t))}function w_(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 T_({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=Fr(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:[__(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:U(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 E_={otherQueries:`Other queries`},D_={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 O_(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(` · `)||E_.otherQueries;return r.sort((e,t)=>e.marketLabel.localeCompare(t.marketLabel)||e.query.localeCompare(t.query))}var k_={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 A_({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?k_.savedCite(r.citedAnswers,r.answers,r.citedTargetKeys.map(i).join(`, `)):k_.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:k_.partlySaved(r.answers)}):null,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:a})]})}function j_({value:e,signal:t,singleAnswer:n,row:r,targetLabels:a}){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)(b,{size:16,"aria-hidden":`true`}):(0,Q.jsx)(i,{size:16,"aria-hidden":`true`}),t?`Yes`:`No`]})}let o=t===`cited`&&r?.uncheckedSources?r: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)(v_,{value:e,signal:t}),o?(0,Q.jsx)(A_,{row:o,targetLabels:a??new Map,showCount:e.rate===null}):null]}),o?(0,Q.jsx)(X,{text:k_.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 M_({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 N_({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)(Rs,{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)(M_,{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:Bo(e.provider)}),(!e.model||e.model!==on(e.provider))&&(0,Q.jsx)(`span`,{className:`block break-words text-label-14 text-secondary`,title:e.model??void 0,children:e.model?on(e.provider)?Re(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)(M_,{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)(j_,{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)(j_,{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} · ${Bo(e.provider)}`,onClick:t=>a(e,t.currentTarget),children:[e.answerCount===1?`View answer`:`View answers`,(0,Q.jsx)(h,{size:16,"aria-hidden":`true`})]})})]},JSON.stringify([e.provider,e.model,e.location])))]})}var P_=`Cited counts only answers whose sources could be checked.`,F_=[{key:`mentioned`,label:`Mentioned`,color:Rr[1],dashed:!1},{key:`cited`,label:`Cited`,color:Zr.positive,dashed:!0}],I_=`var(--chart-tooltip-bg)`;function L_({population:e}){let t=(0,Z.useId)(),[n,r]=(0,Z.useState)({mentioned:!0,cited:!0}),i=F_.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)?[P_]:[],...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`}),F_.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?I_: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":`${u_[e.queryClass]} mention and citation trend`,children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`createdAt`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:e=>new Date(Number(e)).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),minTickGap:24}),(0,Q.jsx)(ve,{domain:[0,1],tick:Xr,tickLine:!1,axisLine:!1,width:48,tickFormatter:e=>U(Number(e))}),(0,Q.jsx)(_e,{...ei,formatter:e=>typeof e==`number`?U(e):`Not measured`,labelFormatter:e=>new Date(Number(e)).toLocaleDateString()}),c.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[n.mentioned?(0,Q.jsx)(ye,{type:`linear`,dataKey:`mentioned-${e}`,name:`Mentioned`,stroke:Rr[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Rr[1]}}):null,n.cited?(0,Q.jsx)(ye,{type:`linear`,dataKey:`cited-${e}`,name:`Cited`,stroke:Zr.positive,strokeWidth:2,strokeDasharray:`6 4`,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:I_,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":`${u_[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)(v_,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(v_,{value:e.citationCoverage,signal:`cited`})}),(0,Q.jsx)(`td`,{children:e.continuity.state.replaceAll(`-`,` `)})]},e.runId))})]})]})]})}function R_(e,t){return t?e?.populations.find(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===t)):void 0}function z_(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=R_(r,t)??R_(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 B_={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: ${Bo(e)}`,model:e=>`Model: ${e.includes(`/`)?Re(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(` `)},V_={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},H_=`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 U_(e,t){return e&&t?B_.dateRange(e.slice(0,4)===t.slice(0,4)?ni(e):Jr(e),Jr(t)):e?B_.dateFrom(Jr(e)):t?B_.dateThrough(Jr(t)):null}function W_(e,t){let n=[];e.provider&&n.push({key:`engine`,label:B_.engine(e.provider),patch:{measurementProvider:void 0}}),e.model&&n.push({key:`model`,label:B_.model(e.model),patch:{measurementModel:void 0}}),e.location&&n.push({key:`location`,label:e.location===`none`?B_.noLocation:B_.location(e.location),patch:{measurementLocation:void 0}});let r=U_(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?B_.resultsFrom(Hr(Wr(r.createdAt))):B_.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function G_(e,t,n){return t===``||e.some(e=>e.value===t)?e:[...e,{value:t,label:n}]}function K_({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=z_(e,t.queryKey,t.answer),_=t.queryClass===`all`?g.queryClass:t.queryClass,v=W_(t,e),y=t.measurementScope===`property`?t.measurementScopeKey:void 0,b=y?i?.({id:y,label:pl(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:h_,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:h_,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:B_.queryType}),(0,Q.jsxs)(`select`,{"aria-label":B_.queryType,className:H_,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:Hr(Wr(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:B_.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":B_.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:B_.manageQueries}):null]})]}),(0,Q.jsxs)(`div`,{id:f,role:`group`,"aria-label":B_.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,G_([{value:``,label:`All engines`},...p.providers.map(e=>({value:e,label:Bo(e)}))],x,Bo(x))),O(`Requested search location`,`measurementLocation`,C,G_([{value:``,label:`All requested locations`},...p.locations.flatMap(e=>e.kind===`exact`?[{value:e.value,label:e.value}]:e.kind===`none`?[{value:`none`,label:B_.noLocation}]:[])],C,C===`none`?B_.noLocation:C)),O(`AI model`,`measurementModel`,S,G_([{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(`/`)?Re(e):e}))],S,S.includes(`/`)?Re(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,G_([{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({...V_}),D()},children:B_.clearFilters})})]}),E?(0,Q.jsx)(`p`,{role:`status`,className:`border-b border-default py-3 text-copy-14 text-secondary`,children:B_.trackingChanged(a?Qr(Wr(a)):null,h.completedAt?Qr(Wr(h.completedAt)):null,o??null)}):null]})}function q_({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=z_(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="${c_}"]`);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=g_(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=O_(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=d_[t.queryClass],_=C_(t.comparison,S_(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.`:f_.explanation;return(0,Q.jsxs)(`section`,{"aria-label":u_[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:u_[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:w_(t.summary,_)}),(0,Q.jsx)(X,{text:v})]})]}),(0,Q.jsxs)(`dl`,{className:`report-headline mt-3`,"data-columns":m?3:2,"aria-label":`${u_[t.queryClass]} headline results`,children:[(0,Q.jsx)(T_,{label:m?`Answers mentioning a property`:`Mentioned answers`,help:x.mode===`advanced`?p_.advancedMention:p_.simpleMention,value:t.summary.mentionCoverage,signal:`mentioned`,unit:`answers`,classNoun:g,change:b_(t.comparison,`mentionCoverage`)}),(0,Q.jsx)(T_,{label:m?`Answers citing a property`:`Cited answers`,help:x.mode===`advanced`?p_.advancedCitation:p_.simpleCitation,value:t.summary.citationCoverage,signal:`cited`,unit:`answers`,classNoun:g,change:b_(t.comparison,`citationCoverage`)}),m?(0,Q.jsx)(T_,{label:`Properties mentioned`,help:p_.propertyReach,value:t.summary.propertyReach,signal:`mentioned`,unit:`properties`,classNoun:g,change:b_(t.comparison,`propertyReach`)}):null]}),(0,Q.jsx)(Fs,{queryClass:x.queryClass,manage:!0}),(0,Q.jsx)(L_,{population:t}),m&&(t.breakdown.groups.length>0||t.breakdown.properties.length>0)?(0,Q.jsx)(J_,{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":`${u_[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:k_.outcomes(t.summary.notMeasuredUnchecked)}):null,t.summary.notMeasuredNoSources?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:k_.outcomesNoSources(t.summary.notMeasuredNoSources)}):null]}),(0,Q.jsx)(X,{text:m_})]})]}):null,(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"data-query-results":t.queryClass,"aria-label":`${u_[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 ${u_[t.queryClass]}`,placeholder:`Search queries`,className:`${h_} 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":`${u_[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)(N_,{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":c_,"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:l_})]}),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:Bo(e.provider)}),e.model&&e.model!==on(e.provider)?(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.model,children:on(e.provider)?Re(e.model):e.model}):null,(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.location===null?B_.noLocation:B_.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`?wr.ambiguous:`Mention not checked`:e.mentioned?`Mentioned`:`Not mentioned`}),(0,Q.jsx)(J,{tone:`neutral`,children:e.cited===null?e.citationUnavailableReason===`citation-not-measured`?kr.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":`${u_[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)(v_,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(v_,{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 J_({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=Ql({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:`${h_} 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)(v_,{value:e.mentionCoverage,signal:`mentioned`}),(0,Q.jsx)(y_,{value:e.mentionCoverage})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(v_,{value:e.citationCoverage,signal:`cited`}),(0,Q.jsx)(y_,{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)(eu,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function Y_(e,t,{enabled:n}){return H({...jo({client:Y,path:{name:e},query:fc(t)}),enabled:n,staleTime:pi,retry:!1,placeholderData:re})}function X_(e,t){return t&&e.selection.mode===`simple`&&e.selection.measurement.state===`not-measured`}function Z_({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=L(),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=H({...jo({client:Y,path:{name:e},query:{...fc(t),cursor:a,search:s||void 0}}),staleTime:pi,retry:!1,placeholderData:re}),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=H({...jo({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&&!R_(p.data,t.queryKey)&&!g.data)return;let r=z_(p.data,t.queryKey,t.answer,g.data);if(!a&&!s){let{queryKey:n}=jo({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&&X_(p.data,i))return(0,Q.jsx)(Q.Fragment,{children:r});if(p.error){let e=Tn(On(p.error)),t=e?.reason===st[`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?D_.retiredMarket:e?D_.retiredScope:Se(p.error)}),t?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementMarketKey:void 0})},children:D_.showAllMarkets}):e?(0,Q.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementScope:`project`,measurementScopeKey:void 0})},children:D_.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)(q_,{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?Se(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 Q_({projectName:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,fallback:s,showUnmeasuredFallback:c=!1}){let l=Y_(e,t,{enabled:!0}),u=l.error?void 0:l.data,d=!l.isPlaceholderData&&u?.selection.availability.state===`available`?u.selection.run.id:null;Vc(d,null);let f=!(!u||u.selection.availability.state!==`available`||X_(u,c));return(0,Q.jsxs)(Q.Fragment,{children:[f?(0,Q.jsx)(K_,{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)(qs,{})}):null,(0,Q.jsx)(Z_,{projectName:e,selection:t,onSelectionChange:n,fallback:s,showUnmeasuredFallback:c},`${e}:${JSON.stringify({...t,queryKey:void 0,answer:void 0})}`)]})}var $_=[{value:`byProvider`,label:`By engine`},{value:`overall`,label:`All engines`}],ev=[{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.`}],tv=[{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.`}],nv=Rr[2],rv=Rr[4],iv=`var(--chart-tooltip-bg)`,av={up:`text-positive-400`,down:`text-negative-400`,none:`text-muted`};function ov({direction:e,magnitude:t}){switch(e){case`up`:return`up ${t} points`;case`down`:return`down ${t} points`;case`none`:return`no change`}}function sv(e){return e.direction===`none`?`no change over the period`:`${ov(e)} over the period`}function cv(e){return e===`__cited__`||e===`__mentioned__`||e===`__mentionShare__`}function lv(e){return e===`__cited__`?`Cited`:e===`__mentioned__`?`Mentioned`:e===`__mentionShare__`?`Mention share`:Bo(e)}function uv(e,t){return e===`__cited__`?Zr.positive:e===`__mentioned__`?Rr[1]:e===`__mentionShare__`?nv:Lr(ys(e),t)}function dv(e){return e===`non-brand`?`non-brand answers`:`all answers`}function fv(e){return e===`cited`?`Cited`:e===`mentionShare`?`Mention share`:`Mentioned`}function pv(e,t){return e===`mentionShare`?`Mention share in ${dv(t)}`:fv(e)}function mv(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 hv={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 gv(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 _v(e,t,n){let r=e.byProvider[t];return r?gv(r,n):null}function vv(e){return e.rate===null?hv.point:`${e.count} of ${e.total}`}function yv(e,t){let n=fv(t).toLowerCase();return e.rate===null?`${n} ${hv.point}`:`${U(e.rate)} ${n}, ${e.count} of ${e.total} answers`}function bv(e,t){if(t===`mentionShare`){let{projectMentionSnapshots:t,competitorMentionSnapshots:n}=e.mentionShare;return`${t} of ${t+n} tracked-brand mentions`}let n=gv(e,t);return n.rate===null?hv.point:`${n.count} of ${n.total} answers`}function xv(e,t){if(t===void 0)return null;let n=String(t);return e.find(e=>e.startDate===n)??null}function Sv(e){let t=ss(e);return t===null?[]:Object.entries(t).sort(([e],[t])=>ys(e).localeCompare(ys(t))).map(([e,t])=>`${Bo(e)}: ${us(t)}`)}function Cv(e,t){return new Date(e).toDateString()===new Date(t).toDateString()}function wv(e){return`${e} ${e===1?`query`:`queries`}`}function Tv(e){let{added:t,removed:n}=e;return[...t.length>0?[`${wv(t.length)} added`]:[],...n.length>0?[`${t.length>0?n.length:wv(n.length)} removed`]:[]].join(`, `)}function Ev(e,t){let n=Wo(e),r=rs(e),i=vs(e,t);if(!n||!r||!i)return null;let a=Ko(i.moves),o=Cv(n.start,n.end),s=e=>Mr(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 Dv(e,t,n){let r=Ev(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?`, `:``,Tv(e),` `,(0,Q.jsx)(`strong`,{children:as(Wr(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 Ov=`Queries changed`;function kv(e){let t=Ko(e.moves);return t?`${Ov}: ${t} between the first and latest points, so the change compares different queries.`:`${Ov}: the first and latest points have answers for ${e.firstCount} and ${e.latestCount} queries, so the change compares different queries.`}function Av(e){return e.replace(/ /g,`\xA0`)}function jv({state:e,from:t=!1}){return(0,Q.jsx)(`span`,{className:t?`av-model av-model-from`:`av-model`,children:us(e)})}function Mv(e,t){return e.reroute?`Same preset, answered with a different model.`:is(e.provider,e.to)?e.served?`Preset picks its own model. Answered with ${us(e.served.to)} (was ${us(e.served.from)}).`:t&&t.length>0?`Preset picks its own model. Answered with ${t.map(e=>e.includes(`/`)?Re(e):e).join(`, `)}.`:`Preset picks its own model.`:null}function Nv({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=>as(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:Tv(e)}),toHelp:null}))});let p=[...new Set(n.map(e=>e.provider))].sort((e,t)=>Bo(e).localeCompare(Bo(t)));for(let e of p){let t=r[e]?.latestServedModelIds??null,a=n.filter(t=>t.provider===e);f.push({key:e,label:Bo(e),rows:a.map((n,r)=>{let a=d.get(e)===n?i.get(e).text:null,o=[Mv(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)(jv,{state:n.from,from:!0}),to:(0,Q.jsx)(jv,{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?rs(l):null;for(let[e,t]of Object.entries(l?ss(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 `,Bo(e),` models: `,ps(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)??[],Bo(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: `,Qo(t)]}):`Changed before this date range: ${Qo(t)}`);for(let e of a)h.push(`${Bo(e.provider)}: most recent ${e.shown} of ${e.total} changes`);for(let e of o)h.push(`${Bo(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:[Bo(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])=>Bo(e).localeCompare(Bo(t)))){let n=t.latestServedModelIds??[],r=n.length>0?n.map(e=>e.includes(`/`)?Re(e):e).join(`, `):us(t.latestObservation.state);h.push((0,Q.jsxs)(Q.Fragment,{children:[Bo(e),` last answered with `,(0,Q.jsx)(`strong`,{children:r}),` on `,(0,Q.jsx)(`strong`,{children:u(Wr(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=>Mr(e,e));y+=` ${t} = the ${Qo(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=xs(r[0],c,e,o);s&&(y+=` Check before: ${u(s)}.`)}let b=Zo({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 ${Av(u(t.at))}`:Av(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)(Tl,{items:h})]}):(0,Q.jsx)(`ul`,{className:`av-details-list`,children:h.map((e,t)=>(0,Q.jsx)(`li`,{children:e},t))})})]})}function Pv({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:Bo(e)}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`selected `,(0,Q.jsx)(jv,{state:t.configured}),` · answered `,(0,Q.jsx)(jv,{state:t.served})]}),(0,Q.jsx)(`span`,{className:`av-status text-caution-400`,children:`substituted`})]},e))})}function Fv({active:e,label:t,payload:n,metric:r,mode:i,buckets:a,basketChanges:o}){if(!e)return null;let s=xv(a,t);if(!s)return null;let c=Wo(s),l=c!==null&&Cv(c.start,c.end)?c.start:null,u=fs(s,o),d=Sv(s),f=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`trend-tooltip-label`,children:gs(s)}),u.map(e=>(0,Q.jsxs)(`p`,{className:`trend-tooltip-detail trend-tooltip-note`,children:[Tv(e),` `,Mr(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:nv},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-tooltip-name`,children:pv(`mentionShare`,s.mentionShare.scope)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:U(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`?ms:os}];return(0,Q.jsxs)(`div`,{className:`trend-tooltip`,children:[f,m.map((e,t)=>{let n=String(e.dataKey??e.name??``),a=(i===`byProvider`?_v(s,n,r):null)??gv(s,r),o=e.color??uv(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:lv(n)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:a.rate===null?hv.value:U(a.rate)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-count`,children:vv(a)})]})},`${n}-${t}`)}),p]})}function Iv({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:[pv(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=dv(e.mentionShare.scope);i=n>0?`${U(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=_v(e,n,t);return r?`${Bo(n)} ${yv(r,t)}`:`${Bo(n)} no data`}).join(`; `):yv(gv(e,t),t);let a=Sv(e);return a.length>0&&(i+=`; models: ${a.join(`; `)}`),(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:gs(e)}),(0,Q.jsx)(`td`,{children:i})]},e.startDate)})})]})})}function Lv({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)(()=>ls(t,n),[t,n]),b=H({queryKey:[`analytics-metrics`,e,c,y,r,h],queryFn:()=>Ee(e,c,h),staleTime:di}),x=b.data??null,S=b.error,C=u===`mentionShare`?`overall`:g,w=(0,Z.useMemo)(()=>x?hs(x,u,C):null,[x,u,C]),T=x?Go(x):null,E=(0,Z.useMemo)(()=>Yo(T??{}),[T]),D=(0,Z.useMemo)(()=>Lo(T??{}),[T]),O=(0,Z.useMemo)(()=>Object.entries(T??{}).filter(([,e])=>e.anchorUnavailable).map(([e])=>e).sort(),[T]),k=(0,Z.useMemo)(()=>x?Ho(x):{},[x]),A=(0,Z.useMemo)(()=>x?Jo(Vo(x)):[],[x]),j=(0,Z.useMemo)(()=>x?Io(x):[],[x]),M=(0,Z.useMemo)(()=>x?zo(x):[],[x]),N=(0,Z.useMemo)(()=>es(T??{},k),[T,k]),P=(0,Z.useMemo)(()=>x?qo(x):{},[x]),ee=(0,Z.useMemo)(()=>Nt(P,{engineName:Bo}),[P]),te=(0,Z.useMemo)(()=>{let e=new Map;for(let[t,n]of Object.entries(P).sort(([e],[t])=>e.localeCompare(t))){let r=Nt({[t]:n},{engineName:Bo});r?.kind===`no-known-change`&&e.set(t,{text:`${r.text} ${r.detail}`,modelIds:n.modelIds??[]})}return e},[P]),ne=(0,Z.useMemo)(()=>{let e=new Map(i.map(e=>[Ye(e),e]));return t=>e.get(Ye(t))??t},[i]),F=u!==`mentionShare`&&C===`byProvider`,I=x?.buckets??[],L=I[I.length-1]?.mentionShare.scope??x?.mentionShareScope??`pooled`,re=pv(u,L),ie=F?Gr.textDim:u===`cited`?Zr.positive:u===`mentionShare`?nv:Rr[1],ae=(0,Z.useMemo)(()=>{let e=new Map(I.map(e=>[e.startDate,ns(e)]));return t=>e.get(String(t))??``},[I]),R=u===`mentionShare`?I.filter(e=>typeof e.mentionShare.rate==`number`&&Number.isFinite(e.mentionShare.rate)):u===`cited`?I.filter(e=>e.citationRate!==null):I,z=R.at(-1),B=(x?Ro(x,u):[]).at(-1)??null,V=x?bs(x,u):null,oe=cs(R,j),se=Uo(oe,u,L,a),le=B!==null&&V!==null?dn(V.delta):null,ue=le!==null&&!se,pe=t.length,me=[];if(B!==null&&z&&me.push((0,Q.jsxs)(Q.Fragment,{children:[`Latest point: `,(0,Q.jsx)(`strong`,{children:bv(z,u)})]})),z&&V!==null&&oe&&!se&&me.push(Dv(oe,z,j)),z&&R.length===1){let e=Ev(z,j);e&&!Uo(vs(z,j),u,L,a)&&me.push(e)}if(le!==null&&R[0]){let e=rs(R[0]);e&&me.push((0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:e}),` point`]}))}if(F&&B!==null){let e=u===`cited`&&z&&z.citationNotMeasured>0?`all answers with sources`:`all answers`;me.push((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:U(B)}),` pools `,e,`; not an average of engines`]}))}let he=[...new Set([...E.buckets.map(e=>e.bucketStartDate),...I.filter(e=>fs(e,j).length>0).map(e=>e.startDate)])].sort(),ge=B!==null&&z&&(0,Q.jsxs)(`div`,{className:`visibility-trend-current`,children:[(0,Q.jsx)(`span`,{className:`visibility-trend-current-dot`,style:{backgroundColor:ie},"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-label`,children:[re,!m&&u!==`mentionShare`?` · ${h} queries`:``]}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-value`,children:[U(B),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`}),le!==null&&(0,Q.jsx)(`span`,{className:`visibility-trend-current-delta ${ue?`text-muted`:av[le.direction]}`,children:ov(le)}),ue&&oe?(0,Q.jsx)(X,{tone:`caution`,label:`Queries changed`,text:kv(oe)}):null]}),Ce=(0,Q.jsxs)(`div`,{className:`visibility-trend-controls`,children:[(0,Q.jsx)(As,{options:tv,value:u,onChange:d,label:`Metric`,className:`visibility-trend-metric-control`}),u!==`mentionShare`&&(0,Q.jsx)(As,{options:$_,value:g,onChange:_,label:`Series`}),(0,Q.jsx)(As,{options:s_,value:c,onChange:l,label:`Time window`,className:`sm:ml-auto`})]}),we;if(S)we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative-400`,children:Se(S)});else if(b.isLoading&&!x)we=(0,Q.jsx)(`div`,{className:`visibility-trend-chart animate-pulse rounded-md bg-bg-elevated/40`,"aria-hidden":`true`});else if(u===`mentionShare`&&pe===0)we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Add tracked competitors to measure mention share over time.`});else if(!x||!w)we=null;else{let{rows:e,series:t,hasData:n}=w;if(!n)we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:u===`mentionShare`?`No answer-text brand mentions for you or tracked competitors in ${dv(L)} in this window yet.`:h===`all`?Te()?Is:`Run a check to start tracking citations and mentions over time.`:`No ${h} answers in this window.`});else if(u===`cited`&&!ts(x))we=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:hv.window});else if(F&&t.length===0)we=(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=`${re} rate${h===`all`?``:` in ${h} answers`} across ${e.length} ${e.length===1?`check`:`checks`}. Latest ${U(B)}${le===null?``:`, ${sv(le)}${ue?`, not the same queries`:``}`}.`;we=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`sr-only`,children:n}),(0,Q.jsx)(Iv,{buckets:I,metric:u,mode:C,series:t,mentionShareScope:L}),F&&t.length>0&&(0,Q.jsx)(`ul`,{className:`trend-legend`,"aria-label":`Engines`,children:t.map((e,t)=>{let n=_s(x,e,u);return(0,Q.jsxs)(`li`,{className:`trend-legend-item`,children:[(0,Q.jsx)(`span`,{className:`trend-legend-swatch`,style:{backgroundColor:uv(e,t)},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-legend-name`,children:lv(e)}),n===null?u===`cited`&&Xo(x,e)&&(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:hv.value}):(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:U(n)})]},e)})}),(0,Q.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"aria-label":`${re} trend chart over ${e.length} ${e.length===1?`point`:`points`}`,children:(0,Q.jsx)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:e,margin:{top:8,right:20,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:ae,minTickGap:24}),(0,Q.jsx)(ve,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:e=>U(e,et.percent),tick:Xr,tickLine:!1,axisLine:!1,width:48}),(0,Q.jsx)(_e,{cursor:{stroke:ti,strokeWidth:1},content:(0,Q.jsx)(Fv,{metric:u,mode:C,buckets:I,basketChanges:j})}),he.map(e=>(0,Q.jsx)(xe,{x:e,stroke:rv,strokeDasharray:`4 4`,strokeWidth:1.5,ifOverflow:`extendDomain`},`setup-change-${e}`)),t.map((e,t)=>(0,Q.jsx)(ye,{type:`monotone`,dataKey:e,name:e,stroke:uv(e,t),strokeDasharray:e===`__mentionShare__`?`5 4`:void 0,strokeWidth:cv(e)?2.5:2,dot:e===`__mentionShare__`?{r:2.75,fill:`var(--chart-tooltip-bg)`,stroke:uv(e,t),strokeWidth:1.5}:{r:2.5,fill:uv(e,t),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:iv},connectNulls:e!==$o,isAnimationActive:!1},e))]})})}),he.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:mv(L)})]}),z?(0,Q.jsx)(`p`,{className:`av-card-meta`,children:gs(z)}):null]}),(0,Q.jsxs)(`div`,{className:`visibility-trend-body`,children:[ee?.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:ee.text}),m&&(0,Q.jsx)(`div`,{className:`mb-3`,children:(0,Q.jsx)(As,{options:ev,value:f,onChange:p,label:`Query type`})}),ge,Ce,we]}),(0,Q.jsx)(Tl,{items:me})]}),x&&!S?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Nv,{buckets:I,queryChanges:M,modelRows:N,served:k,pointerNotices:te,truncated:D,incompleteHistory:O,queryName:ne,sweepTimes:o}),(0,Q.jsx)(Pv,{substitutions:A})]}):null]})}var Rv=new Set([vr.queued,vr.running]),zv={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 Bv({projectName:e,onReviewForTracking:t,scopeOptions:n,planRevision:r,selectedScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c=[],viewerResearchConfig:l=null}){let u=L(),{account:d,canWrite:f}=oi(),p=d?.role===`viewer`&&l!==null,m=!f,h=ot(),[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=H({...Ai({client:Y,path:{name:e}}),staleTime:6e4}),k=H({...da({client:Y}),enabled:!m&&!h,staleTime:6e4}),A={client:Y,path:{name:e},query:{limit:20}},j=ie({...Ii(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=>Rv.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()],ee=N?.access?.canRun??(f||p),te=N?.access?N.access.dailyRunLimit:p?l.viewerDailyRunLimit:null;(0,Z.useEffect)(()=>{!b&&P[0]&&x(P[0].id)},[P,b]);let ne=P.find(e=>e.id===b)??null,F=H({...ha({client:Y,path:{name:e,runId:b??``}}),enabled:!M&&!!b,refetchInterval:ne&&Rv.has(ne.status)?3e3:!1}),I=M||F.isError?null:F.data??null,re=O.data?.locations??[],ae=(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=js(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)&&!Vn(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=>Gs(e,Ns)&&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=>Vn(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(Vn).flatMap(n=>{let r=on(n);if(!r)return[];let i=t.get(n),a=s.get(n),c=i??(o?{...o,name:n,displayName:Bo(n,[...e,...s.values()]),modelConfigurable:!1,defaultModel:r,knownModels:o.knownModels.filter(e=>e.id===r)}:a);return c?[{name:n,displayName:Bo(n,[...e,...s.values()]),configured:!0,defaultModel:r,catalog:c}]:[]});return[...i,...c,...a]},[N?.providers,m,O.data?.providers,k.data]),R=!(m?j.isPending:k.isPending)&&ae.length===0,z=ae.find(e=>e.name===g)??null;(0,Z.useEffect)(()=>{if(!g&&O.data&&!O.isError&&!k.isError){let e=ae.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,ae,O.data,O.isError,k.isError]);let B=z?.catalog.modelConfigurable??!1,V=m?z?.catalog.defaultModel:(z?O.data?.providerModels[z.name]:``)||z?.catalog.defaultModel,se=(B?v.trim():``)||V,ce=z?[...new Map([{id:z.catalog.defaultModel,displayName:Re(z.catalog.defaultModel)},...v.trim()?[{id:v.trim(),displayName:Re(v.trim())}]:[],...z.catalog.knownModels].map(e=>[e.id,e])).values()]:[],le=oe({...Po(),onSuccess:async e=>{w.current=null,D(e=>e+1),C(e.runs),x(e.runs[0]?.id??null),await ny(u),ci({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=>{ci({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)(ws,{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)(Uv,{projectName:e,canWrite:f,researchAllowed:ee&&!M,limitedAccess:m,isEmbed:K(),scopeOptions:n??[],planRevision:r??i?.planRevision??null,initialScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c,locations:re,defaultLocation:O.data?.defaultLocation??null,providerOptions:ae,provider:g,onProviderChange:e=>{_(e),y(``)},resolvedModel:se,visibilityModel:V,configurableModel:B,model:v,onModelChange:y,modelOptions:ce,settingsReady:m?!j.isPending&&!M:!k.isPending&&!k.isError&&!k.isFetching,projectReady:!O.isPending&&!O.isError&&!O.isFetching,isPending:le.isPending,errorMessage:le.isError?`The request could not be confirmed.`:void 0,onSubmit:(t,n)=>{!ee||M||K()||T.current||(w.current?.fingerprint!==n&&(w.current={fingerprint:n,key:crypto.randomUUID()}),T.current=!0,le.mutate({client:Y,path:{name:e},body:{...t,idempotencyKey:w.current.key}}))}},`${e}:${E}`),te!==null&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Up to `,te,` 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)&&R&&(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)(ws,{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:zv.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:zv.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:Qv(e.createdAt)})}),(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`span`,{className:`block`,title:e.provider,children:Bo(e.provider,k.data?.providerCatalog)}),(e.requestedModel??e.resolvedModel)!==on(e.provider)&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.requestedModel??e.resolvedModel,children:Re(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:ey(e.status),children:e.status})})]},e.id))})]})}),j.isFetchNextPageError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:zv.historyMoreError}),j.hasNextPage&&(0,Q.jsx)(q,{className:`mt-3`,variant:`outline`,disabled:j.isFetching,onClick:()=>{j.fetchNextPage()},children:j.isFetchingNextPage?zv.historyLoading:zv.historyMore})]})]}),!M&&F.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:()=>{F.refetch()},children:`Retry results`})]}):!M&&(I||b)?(0,Q.jsx)(Jv,{detail:I,engineLabel:I?Bo(I.provider,k.data?.providerCatalog):void 0,isLoading:F.isFetching,onReviewForTracking:h?void 0:t}):null]})}var Vv=`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`,Hv=`__none__`;function Uv(e){let{projectName:t,locations:n,provider:r,resolvedModel:i,planRevision:a}=e,o=e.providerOptions.map(e=>({...e,knownModels:e.catalog.knownModels})),s=on(r),c=[r?Bo(r,o):`Choose an engine`,i&&i!==s?Re(i):i?null:`Choose a model`].filter(Boolean).join(` · `),l=L(),[u,d]=(0,Z.useState)(`once`),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(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)([]),[j,N]=(0,Z.useState)(null),[P,ee]=(0,Z.useState)(!1),[te,ne]=(0,Z.useState)(!1),[F,I]=(0,Z.useState)(``),[re,ie]=(0,Z.useState)(``),ae=(0,Z.useRef)(null),R=(0,Z.useRef)(!1),z=(0,Z.useRef)(null),B=e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`;(0,Z.useEffect)(()=>{_(B),O(null)},[B]);let V=e.scopeOptions.filter(e=>e.kind===`market`||e.kind===`property`),H=u===`markets`?`market`:`property`,se=V.filter(e=>e.kind===H),ce=t=>({kind:t.kind,key:t.id,label:t.label,planRevision:a??e.initialScope?.planRevision??0}),le=e=>e===Hv?null:n.find(t=>t.label===e),ue=y??e.defaultLocation??Hv,de=V.find(e=>`${e.kind}:${e.id}`===g),fe=de?ce(de):null,pe=u===`once`?[{scope:fe,location:le(ue)}]:u===`locations`?x.map(e=>({scope:null,location:le(e)})):x.map(e=>se.find(t=>`${t.kind}:${t.id}`===e)).map(e=>e?{scope:ce(e),location:le(T[`${e.kind}:${e.id}`]??Hv)}:null),me=[...new Map([...k,...e.templates].map(e=>[e.id,e])).values()],he=D?me.find(e=>e.id===D.id):null,ge=D!==null&&he?.version!==D.version,_e=u===`once`?f:m,ve=_e.split(/\r?\n/).filter(e=>e.trim()),ye=bt(ve),be=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))],xe=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,``)),Se=[];ve.length||Se.push(u===`once`?`Enter at least one query.`:`Enter at least one query pattern.`),ve.some(e=>e.length>4e3)&&Se.push(`Keep each query under 4,001 characters.`),u!==`once`&&xe&&Se.push(`Use the name buttons to insert a supported variable. Remove unknown or incomplete braces.`),pe.length||Se.push(u===`locations`?`Select at least one location.`:`Select at least one destination.`),pe.some(e=>!e||e.location===void 0)&&Se.push(`A selected destination or location is no longer available. Update your selection.`);let Ce=u===`once`&&g!==`project`||u===`markets`||u===`properties`;Ce&&(e.scopePending||e.scopeError||!a||pe.some(e=>!e?.scope))&&Se.push(`Load the current published markets and properties before running scoped research.`);let U=(u===`once`?ye.length:ve.length)*pe.length;if(pe.length>20&&Se.push(`Select at most 20 destinations.`),U>50&&Se.push(`${U} queries selected. Reduce the selection to 50 or fewer.`),ge&&Se.push(`This saved pattern changed. Select its current version from Saved patterns.`),u!==`once`&&!xe){for(let e of pe)if(e&&e.location!==void 0)try{W(D??{pattern:m,variables:be},e.scope,e.location)}catch{Se.push(`Choose a location for {location}, or use only variables available for ${u===`markets`?`markets`:u===`properties`?`properties`:`locations`}.`);break}}let we=JSON.stringify({mode:u,source:_e,contexts:pe,provider:r,resolvedModel:i,template:D,...Ce?{planRevision:a}:{}}),Te=j!==null&&j.signature!==we,Ee=u===`once`?ye.map((e,t)=>({id:String(t),query:e,scope:fe,location:pe[0]?.location??null})):j?.rows??[],De=qv(Ee),Oe=[];u!==`once`&&j&&(Te&&Oe.push(`Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup.`),Ee.some(e=>!e.query.trim()||e.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(e.query))&&Oe.push(`Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables.`),Ee.some(e=>e.location&&!n.some(t=>JSON.stringify(t)===JSON.stringify(e.location)))&&Oe.push(`A preview location changed. Regenerate the preview.`),De.some(e=>bt(e.queries).length!==e.queries.length)&&Oe.push(`Remove duplicate queries within each destination and location.`),De.length>20&&Oe.push(`The preview exceeds 20 runs.`));let ke=e.researchAllowed&&!e.isEmbed&&!e.isPending&&e.settingsReady&&e.projectReady&&!!(r&&i)&&!Se.length&&!Oe.length&&(u===`once`||j!==null),Ae=()=>({runs:De.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}:{}}))}),je=()=>{if(ee(!0),Se.length)return;let e=pe.flatMap((e,t)=>ve.map((n,r)=>({id:`${t}:${r}`,scope:e.scope,location:e.location,...D?{template:{templateId:D.id,templateVersion:D.version,bindingLocation:e.location}}:{},query:W({pattern:n,variables:[...new Set([...n.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))]},e.scope,e.location).output})));N({signature:we,rows:e})},Me=e=>{d(e),S([]),O(null),w(``),ee(!1)},Ne=e=>{if(ie(``),u===`once`)try{p(W(e,fe,le(ue)).output)}catch{ie(`Select a matching market, property, or location before using this pattern.`);return}else h(e.pattern);O(e)},Pe=e=>{let t=z.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)})},Fe=oe({...lo(),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),ne(!1),I(``),ie(``),ae.current=null,await l.invalidateQueries({queryKey:Ja({client:Y,path:{name:t}})}),ci({title:`Pattern saved`,detail:`Available in Saved patterns. Tracking was not changed.`,tone:`positive`})},onError:()=>ie(`Could not save the pattern. Your text is preserved. Retry to save the same pattern.`),onSettled:()=>{R.current=!1}}),Ie=()=>{if(!e.canWrite||e.isEmbed||R.current)return;let n=u===`once`?f:m,r=u===`once`?[]:be;if(!F.trim()||!n.trim()||n.length>4e3||u!==`once`&&xe){ie(`Enter a name and a valid pattern of 1 to 4,000 characters.`);return}let i={name:F.trim(),pattern:n,variables:r},a=JSON.stringify(i);ae.current?.fingerprint!==a&&(ae.current={fingerprint:a,id:crypto.randomUUID()}),R.current=!0,Fe.mutate({client:Y,path:{name:t,templateId:ae.current.id},body:i})},Le=[...new Set([...P||_e.trim()?Se:[],...Oe])],ze=me.filter(e=>{let t=u===`once`?pr(fe,le(ue)):pr(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)(ws,{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||Fe.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:Vv,value:u,disabled:e.isPending,onChange:e=>Me(e.target.value),children:[(0,Q.jsx)(`option`,{value:`once`,children:`Run once`}),(0,Q.jsx)(`option`,{value:`markets`,disabled:!V.some(e=>e.kind===`market`),children:`Repeat across markets`}),(0,Q.jsx)(`option`,{value:`properties`,disabled:!V.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:[(V.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:Vv,value:g,onChange:e=>{_(e.target.value),O(null)},children:[(0,Q.jsx)(`option`,{value:`project`,children:`Whole site`}),g!==`project`&&!de&&(0,Q.jsx)(`option`,{value:g,disabled:!0,children:`Selected destination unavailable`}),V.map(e=>(0,Q.jsxs)(`option`,{value:`${e.kind}:${e.id}`,children:[e.label,` (`,e.kind,`)`]},`${e.kind}:${e.id}`))]})]}),(0,Q.jsx)(Wv,{label:`Answer engine location`,value:ue,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:Vv,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})):se.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)(Wv,{label:`Answer engine location for ${e.label}`,value:T[e.key]??Hv,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:z,className:`${Vv} min-h-32`,"aria-describedby":`research-query-guidance research-query-count`,value:_e,placeholder:u===`once`?zv.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:()=>Pe(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:[U,` / `,50,` queries`,u===`once`?``:` across ${pe.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.`}),ze.length?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:ze.map(e=>(0,Q.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>Ne(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:()=>ne(!te),children:te?`Cancel save`:`Save as a pattern`}),te&&(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:Vv,value:F,maxLength:120,onChange:e=>I(e.target.value)})]}),(0,Q.jsx)(q,{size:`sm`,disabled:Fe.isPending||!F.trim()||!_e.trim(),onClick:Ie,children:Fe.isPending?`Saving…`:`Save pattern`})]})]}),re&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:re})]})]}),(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:Vv,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:Bo(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:Vv,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?` · ${Re(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:Vv,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))})]})]})]}),Le.length>0&&(0,Q.jsx)(Kv,{errors:Le}),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:je,children:[(0,Q.jsx)(v,{size:14}),j?zv.refreshPreview:`Preview queries`]}),j&&(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:[Ee.length,` query executions in `,De.length,` saved runs · `,c,`. Edit any query or location below.`]}),(0,Q.jsx)(Gv,{rows:Ee,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:!ke,onClick:()=>{if(ke){let n=Ae();e.onSubmit(n,JSON.stringify({projectName:t,...n}))}},children:[(0,Q.jsx)(M,{size:14}),e.isPending?`Starting…`:zv.runAction]}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[u===`once`?`${ye.length} queries`:`${Ee.length} reviewed queries`,` · `,c]})]})]})]})}function Wv({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:Vv,value:t,onChange:e=>r(e.target.value),children:[(0,Q.jsx)(`option`,{value:Hv,children:`No location context`}),n.map(e=>(0,Q.jsx)(`option`,{value:e.label,children:e.label},e.label))]})]})}function Gv({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:`${Vv} 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)(Wv,{label:`Location for query ${r+1}`,value:e.location?.label??Hv,locations:t,onChange:r=>n(e.id,{location:t.find(e=>e.label===r)??null})})]},e.id))})}function Kv({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 qv(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 Jv({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)(ws,{id:e?`research-run-${e.id}`:void 0,className:`surface-card min-w-0`,role:`region`,"aria-label":zv.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 ${$v(e.id)}`:zv.resultsEmpty})}),e&&(0,Q.jsx)(J,{tone:ey(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??Bo(e.provider)})]}),(e.requestedModel??e.resolvedModel)!==on(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:Re(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:zv.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:zv.methodologySummary}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-prose text-copy-14`,children:zv.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`?zv.brandedQuery:e.queryClass===`non-brand`?zv.discoveryQuery:zv.unclassifiedQuery})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:ty(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===tn.failed?`negative`:`caution`,children:e.answerMentioned===null?e.status===tn.failed?`Unavailable`:`Pending`:e.answerMentioned?`Matched`:`No match`})}),(0,Q.jsx)(`td`,{children:e.citationMeasured===!1&&e.status===tn.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===tn.failed?`negative`:`caution`,children:e.citationState===null?e.status===tn.failed?`Unavailable`:`Pending`:e.citationState===`cited`?`Cited`:`Not cited`})})]},e.id))})]})}),(0,Q.jsx)(Yv,{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 Yv({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)(ds,{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===tn.failed?`This query did not return an answer.`:e.status===tn[`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)(Zv,{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 Xv={"explicit-citation":`Cited in the answer`,"answer-support":`Used for the answer`,"search-result":`Search result`,"page-read":`Page read`};function Zv({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:at(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:ut(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:Xv[e.relationship]}),(0,Q.jsx)(Cc,{url:e.url,title:e.title??e.url})]},`${e.url}-${t}`))})]})}function Qv(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 $v(e){return e.length>8?e.slice(0,8):e}function ey(e){return e===vr.completed?`positive`:e===vr.partial||e===vr[`waiting-upstream`]?`caution`:e===vr.failed?`negative`:`neutral`}function ty(e){return e===tn.completed?`positive`:e===tn.failed?`negative`:e===tn[`waiting-upstream`]?`caution`:`neutral`}async function ny(e){await li(e,`researchRuns`)}var ry=new Set([`queued`,`seeding`,`probing`]);function iy({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}=oi(),[d,f]=(0,Z.useState)(`tracked`),[p,m]=(0,Z.useState)(`find`),[h,g]=(0,Z.useState)(null),_=u?.role===`viewer`?yn():null,v=ul(u?.role,_),y=dl(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)(_l,{id:x,label:`Query workspace`,value:y,onChange:S,className:`flex border-b border-default`,tabClassName:ay,activeTabClassName:oy,inactiveTabClassName:sy,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)(Wy,{projectName:e,selection:a,onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,pendingTrackingSource:h,onPendingTrackingSourceHandled:()=>g(null),publishGuard:l}):(0,Q.jsx)(cy,{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 ay=`-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`,oy=`border-mono-400 text-heading`,sy=`border-transparent text-muted hover:border-strong hover:text-strong`;function cy({projectName:e,selection:t,mode:n,onModeChange:r,onReviewSavedSource:i,viewerResearchConfig:a}){let{canWrite:o}=oi(),s=(0,Z.useId)(),c=!o||n===`test`,l=H({...Fo({client:Y,path:{name:e}}),enabled:c,staleTime:6e4}),u=H({...yi({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)(_l,{id:s,label:`Research workspace`,value:n,onChange:r,className:`flex border-b border-default`,tabClassName:ay,activeTabClassName:oy,inactiveTabClassName:sy,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)(Gy,{projectName:e,onReviewDiscoveryProbe:e=>i({source:`discovery`,discoveryProbeId:e})}):(0,Q.jsx)(Bv,{...p,onReviewForTracking:({researchRunQueryId:e,scope:t})=>i({source:`research`,researchRunQueryId:e},t??null)})})]}):(0,Q.jsx)(Bv,{...p,viewerResearchConfig:a})}function ly({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),[v,b]=(0,Z.useState)(()=>uy(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=fl(e,t),O=(0,Z.useMemo)(()=>by(e.tracked,t,e.mode),[t,e.mode,e.tracked]),k=O.some(e=>e.provenance!==null),A=Ql({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}:${Sy(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`?_y(t):void 0,scopeLabel:vy(t,e)}),b(dy(i,t)),S(null))},[t,r,D,e]),(0,Z.useEffect)(()=>{if(D||!a)return;let e=uy(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({...uy(t),source:e}),S(null),i?.(void 0)}function M(n){E.current=`${n.queryId}:${Sy(t)}`,_({kind:`edit`,row:n,audience:e.mode===`advanced`?_y(t):void 0,scopeLabel:vy(t,e)}),b(dy(n,t)),S(null),i?.(n.queryId)}function N(n){E.current=`${n.queryId}:${Sy(t)}`,_({kind:`remove`,row:n,audience:e.mode===`advanced`?_y(t):void 0,scopeLabel:vy(t,e)}),S(null),i?.(n.queryId)}function P(){T.current=!0,_(null),b(uy(t)),S(null),i?.(void 0)}let ee=g?fy(g,v,e):null,te=g!==null&&g.kind===`add`&&e.mode===`advanced`&&!hy(v),ne=ee!==null&&(!te||v.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)(xy,{selection:t,onSelectionChange:n}):null,(0,Q.jsx)($l,{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)(ds,{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)(Ty,{row:n,workspace:e,selection:t})}):null,e.mode===`advanced`?(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(Dy,{row:n})}):null,k?(0,Q.jsx)(`td`,{className:`whitespace-nowrap text-secondary`,children:Cy(n)}):null,(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(Oy,{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)(ds,{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)(ds,{type:`button`,variant:`ghost`,size:`sm`,disabled:d,"aria-label":`Remove ${n.queryText}`,onClick:()=>N(n),children:[(0,Q.jsx)(y,{"aria-hidden":`true`,size:13}),` Remove`]})]})})]},n.queryId))})]})}),(0,Q.jsx)(eu,{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)(ky,{workspace:e,templates:c,action:g,draft:v,onDraftChange:e=>{b(e),S(null)},onClose:P,canReview:ne,isPreviewing:u,editorHeadingRef:C,onReview:()=>{ee&&(S(ee),p(ee))}})}),l&&x&&g&&(0,Q.jsx)(zy,{preview:l,workspace:e,isCommitting:d,sweepActive:h?.sweepActive??!1,onConfirm:si(async()=>{await m({...x,expectedWorkspaceVersion:l.workspaceVersion,previewToken:l.previewToken,reviewedAt:l.reviewedAt})&&P()})})]})}function uy(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 dy(e,t){return{...uy(t),text:e.queryText,queryClass:`keep`}}function fy(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=py(t);if(!i||gy(t)||r&&!t.wholeSite&&t.targetKeys.length+t.groupKeys.length+t.marketKeys.length===0)return null;let a=r?my(t,n):void 0;return{additions:[{input:i,...a?{audience:a}:{},...r&&!hy(t)&&t.contexts.length>0?{contexts:t.contexts}:{},...r&&t.queryClass!==`auto`&&t.queryClass!==`keep`?{queryClass:t.queryClass}:{}}],removals:[]}}function py(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 my(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 hy(e){return e.marketKeys.length>0&&e.targetKeys.length===0&&e.groupKeys.length===0}function gy(e){return e.source===`template`&&e.template.includes(`{market}`)&&(e.wholeSite||e.marketKeys.length===0)}function _y(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 vy(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 yy(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 by(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=>yy(e,t)))}function xy({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 Sy(e){return e.measurementScopeKey&&e.measurementScope!==`project`?`${e.measurementScope}:${e.measurementScopeKey}`:`project`}function Cy(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 wy(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=>yy(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 Ty({row:e,workspace:t,selection:n}){let r=Ey(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:wy(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 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=e.assignments.filter(e=>yy(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 Dy({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 Oy({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:qr(e.lastMeasuredAt),children:Er(e.lastMeasuredAt)}):null]}):(0,Q.jsx)(J,{tone:`caution`,children:`Awaiting check`})}function ky({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)(ws,{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)(Ry,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):n.kind===`edit`?(0,Q.jsxs)(ws,{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)(Ry,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):(0,Q.jsxs)(ws,{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)(Ay,{templates:t,advanced:e.mode===`advanced`,draft:r,onDraftChange:i}):null,r.source===`research`?(0,Q.jsx)(jy,{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)(jy,{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)(Ly,{workspace:e,draft:r,onDraftChange:i}):null]}),e.mode===`advanced`&&!hy(r)?(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Iy,{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)(Ry,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]})}function Ay({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":gy(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]}),gy(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 jy({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 My(e){return{providers:[...e.providers],models:{...e.models},location:e.location?.label??null}}function Ny(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 Py(e){return[...new Map(e.map(e=>[Ny(e),e])).values()]}function Fy(e){let t=e.providers.map(t=>{let n=e.models[t];return n&&n!==on(t)?`${Bo(t)} (${on(t)?Re(n):n})`:Bo(t)}).join(`, `);return`${e.location??`No location`} · ${t}`}function Iy({workspace:e,draft:t,onDraftChange:n}){let r=(0,Z.useMemo)(()=>Py([...e.defaultContexts.map(My),...t.contexts]),[t.contexts,e.defaultContexts]),i=t.contexts.length===1?Ny(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=>Ny(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:Ny(e),children:Fy(e)},Ny(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 Ly({workspace:e,draft:t,onDraftChange:n}){let{canWrite:r}=oi(),[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)($l,{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 Ry({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)(ds,{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 zy({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)(ws,{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:By(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)(Vy,{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)(Vy,{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)(ds,{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 By(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 Vy({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`:Uy(t,r,n)}),e===`Added`||e===`Reused`?(0,Q.jsx)(Hy,{row:r.find(e=>e.queryId===t.queryId),workspace:n}):null]},`${e}:${t.queryId}`))})]})}function Hy({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=>Fy(My(e))).join(`; `);return(0,Q.jsx)(`li`,{children:[r,i,a].filter(Boolean).join(` · `)},`${e.targetKey}:${n}`)})})]})}function Uy(e,t,n){let r=t.find(t=>t.queryId===e.queryId);if(!r)return`${e.assignmentCount} ${e.assignmentCount===1?`assignment`:`assignments`}`;let i=Py(r.assignments.flatMap(e=>e.contexts).map(My)),a=i.length===1?Fy(i[0]):i.length>1?`${i.length} contexts`:null;return[wy(r,n),a].filter(e=>e!==null).join(` · `)}function Wy({projectName:e,selection:t={measurementScope:`project`,queryClass:`all`},onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s}){let c=L(),[l,u]=(0,Z.useState)(null),d=H({...Fo({client:Y,path:{name:e}})}),f=H({...yi({client:Y,path:{name:e}}),staleTime:6e4}),p=oe({...oa(),onSuccess:e=>u(e),onError:async t=>{u(null),await c.invalidateQueries({queryKey:Si({client:Y,path:{name:e}})}),ci({title:`Could not review tracking changes`,detail:t instanceof Error?t.message:`Update the draft and review it again.`,tone:`negative`})}}),m=oe({...qi(),onSuccess:async t=>{u(null),i?.(void 0),await mi(c,e),ci({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 mi(c,e),ci({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)(ws,{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)(ws,{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)(ly,{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 Gy({projectName:e,onReviewDiscoveryProbe:t}){let n=L(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(`100`),l=H({...Pi({client:Y,path:{name:e},query:{limit:`10`}}),refetchInterval:e=>e.state.data?.some(e=>ry.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=H({...pa({client:Y,path:{name:e,id:r??``}}),enabled:!!r,refetchInterval:d&&ry.has(d.status)?3e3:!1}),p=f.data??null,m=oe({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),en(e,t)},onSuccess:async t=>{i(t.sessionId),o(``),await Qy(n,e,t.sessionId),ci({title:`Discovery started`,detail:`Run ${Zy(t.sessionId)} is testing questions your customers might ask.`,tone:`neutral`,dedupeKey:`discovery:start:${t.sessionId}`,dedupeMode:`replace`})},onError:e=>{ci({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 _(){try{let t=await l.refetch();if(t.error)throw t.error;let n=t.data?.length??0;ci({title:`Discovery sessions refreshed`,detail:`${n} recent session${n===1?``:`s`} loaded.`,tone:`positive`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}catch(t){ci({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 _(),children:[(0,Q.jsx)(v,{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)(ws,{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)(ds,{type:`button`,size:`sm`,disabled:m.isPending,onClick:()=>m.mutate(),children:[(0,Q.jsx)(M,{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:Zy(e.id)}),(0,Q.jsx)(J,{tone:qy(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 `,Zy(h.id)]}),(0,Q.jsx)(J,{tone:qy(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)(Ky,{label:`Questions tested`,value:h.probeCount??0}),(0,Q.jsx)(Ky,{label:`Cited queries`,value:h.citedCount??0,tone:`positive`}),(0,Q.jsx)(Ky,{label:`Worth tracking`,value:h.aspirationalCount??0,tone:`caution`}),(0,Q.jsx)(Ky,{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:Jy(e.bucket),children:Xy(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)(ds,{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 Ky({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 qy(e){return e===`completed`?`positive`:e===`failed`?`negative`:ry.has(e)?`caution`:`neutral`}function Jy(e){return e===`cited`?`positive`:e===`aspirational`?`caution`:e===`wasted-surface`?`negative`:`neutral`}var Yy={cited:`Cited queries`,aspirational:`Worth tracking`,"wasted-surface":`Skip`};function Xy(e){return e?Yy[e]:`Not classified`}function Zy(e){return e.length>8?e.slice(0,8):e}async function Qy(e,t,n){await Promise.all([li(e,`discovery`),e.invalidateQueries({queryKey:Eo({client:Y})})])}var $y=4e3,eb={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 tb(e){return`canonry:embed-query-draft:${e}`}function nb(e){try{return window.sessionStorage.getItem(tb(e))??``}catch{return``}}function rb(e,t){try{t?window.sessionStorage.setItem(tb(e),t):window.sessionStorage.removeItem(tb(e))}catch{}}function ib(e,t){return e.trim().replace(/\s+/g,` `).toLocaleLowerCase()===t.trim().replace(/\s+/g,` `).toLocaleLowerCase()}function ab({projectName:e,limit:t}){let n=L(),r=Fo({client:Y,path:{name:e}}),i=H(r),[a,o]=(0,Z.useState)(()=>nb(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 Le(()=>Ft({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:a}}));return n.diff.noOp?`unchanged`:(await Le(()=>zt({client:Y,path:{name:e},body:{...t,expectedWorkspaceVersion:n.workspaceVersion,previewToken:n.previewToken,reviewedAt:n.reviewedAt}})),`saved`)}catch(e){if(e instanceof zn&&e.code===`EMBED_QUERY_LIMIT`)return`limit`;if(i===0&&e instanceof zn&&e.code===`QUERY_TRACKING_PREVIEW_STALE`)continue;throw e}}throw Error(`The query list kept changing.`)}async function v(r,i){if(m.some(e=>ib(e.queryText,r)))return u({kind:`error`,text:eb.duplicate}),!1;c(i),u(null);try{let i=await _({additions:[{input:{source:`manual`,text:r}}],removals:[]});return i===`unchanged`?(u({kind:`error`,text:eb.duplicate}),!1):i===`limit`?(u({kind:`error`,text:eb.limit(t)}),!1):(await mi(n,e),u({kind:`added`,query:r}),!0)}catch{return u({kind:`error`,text:eb.failed}),!1}finally{c(null)}}async function b(t){t.preventDefault();let n=a.trim();n&&s===null&&!g&&await v(n,`add`)&&(o(``),rb(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 mi(n,e),p.current=r,u({kind:`removed`,query:t.queryText})}catch{u({kind:`error`,text:eb.failed})}finally{c(null)}}}async function S(e){s===null&&await v(e,`undo`)&&d.current?.focus()}if(i.isLoading)return(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,role:`status`,children:eb.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:eb.loadFailed}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void i.refetch(),children:eb.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:eb.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:eb.count(m.length,t)}),` · `,h?eb.nextCheck:eb.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:eb.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:eb.placeholder,maxLength:$y,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),rb(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`?eb.adding:eb.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:[eb.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`?eb.adding:eb.undo})]}):l?.kind===`added`?(0,Q.jsx)(`span`,{className:`sr-only`,children:eb.added(l.query)}):null,h&&g&&!C?(0,Q.jsx)(`span`,{className:`block`,children:eb.limit(t)}):null]})]}),m.length===0?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:eb.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":`${eb.remove} ${e.queryText}`,disabled:s!==null,onClick:()=>void x(e,t),children:[(0,Q.jsx)(y,{"aria-hidden":`true`,size:13}),n?eb.removing:eb.remove]}):null]},e.queryId)})})]})}var ob=/^www\./i;function sb(e){if(!e)return null;try{return new URL(e).hostname}catch{return null}}function cb(e){return e.trim().toLowerCase().replace(ob,``)}function lb(e,t){if(!t)return!1;try{return cb(new URL(e).hostname)===cb(t)}catch{return!1}}function ub(e,t){if(!e)return``;if(!lb(e,t))return e;let n=new URL(e),r=`${n.pathname}${n.search}${n.hash}`;return r===``?`/`:r}function db(e){let t=sb(e);return t?cb(t):null}function fb(e,t,n){if(!e||n.length<2||lb(e,t))return null;let r;try{r=new URL(e)}catch{return null}let i=cb(r.hostname);if(!n.some(e=>cb(e)===i))return null;let a=`${r.pathname}${r.search}${r.hash}`;return{site:i,path:a===``?`/`:a}}function pb(e,t){return ub(e.url,t)||e.path||`/`}var mb=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)}})),hb=mb();function gb(){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 _b=gb;typeof Object.assign==`function`&&(_b=Object.assign);function vb(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 yb(e){return typeof e==`object`&&!!e}function bb(e){let t;for(t in e)return!1;return!0}function xb(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function Sb(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 Cb(e){return!(!yb(e)||e.attributes&&!Array.isArray(e.attributes))}function wb(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function Tb(){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 Eb(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}var Db=class extends Error{constructor(e){super(),this.name=`GraphError`,this.message=e}},Ob=class e extends Db{constructor(t){super(t),this.name=`InvalidArgumentsGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},$=class e extends Db{constructor(t){super(t),this.name=`NotFoundGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},kb=class e extends Db{constructor(t){super(t),this.name=`UsageGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}};function Ab(e,t){this.key=e,this.attributes=t,this.clear()}Ab.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 jb(e,t){this.key=e,this.attributes=t,this.clear()}jb.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function Mb(e,t){this.key=e,this.attributes=t,this.clear()}Mb.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function Nb(e,t,n,r,i){this.key=t,this.attributes=i,this.undirected=e,this.source=n,this.target=r}Nb.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)},Nb.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)},Nb.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]},Nb.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 Pb=0,Fb=1,Ib=2,Lb=3;function Rb(e,t,n,r,i,a,o){let s,c,l,u;if(r=``+r,n===Pb){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===Lb){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===Fb?c.source:c.target,l=i,u=a}return[s,l,u]}function zb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);return a.attributes[o]}}function Bb(e,t,n){e.prototype[t]=function(e,r){let[i]=Rb(this,t,n,e,r);return i.attributes}}function Vb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);return a.attributes.hasOwnProperty(o)}}function Hb(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Rb(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 Ub(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Rb(this,t,n,e,r,i,a);if(typeof c!=`function`)throw new Ob(`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 Wb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(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 Gb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);if(!yb(o))throw new Ob(`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 Kb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);if(!yb(o))throw new Ob(`Graph.${t}: provided attributes are not a plain object.`);return _b(a.attributes,o),this.emit(`nodeAttributesUpdated`,{key:a.key,type:`merge`,attributes:a.attributes,data:o}),this}}function qb(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Rb(this,t,n,e,r,i);if(typeof o!=`function`)throw new Ob(`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 Jb=[{name:e=>`get${e}Attribute`,attacher:zb},{name:e=>`get${e}Attributes`,attacher:Bb},{name:e=>`has${e}Attribute`,attacher:Vb},{name:e=>`set${e}Attribute`,attacher:Hb},{name:e=>`update${e}Attribute`,attacher:Ub},{name:e=>`remove${e}Attribute`,attacher:Wb},{name:e=>`replace${e}Attributes`,attacher:Gb},{name:e=>`merge${e}Attributes`,attacher:Kb},{name:e=>`update${e}Attributes`,attacher:qb}];function Yb(e){Jb.forEach(function({name:t,attacher:n}){n(e,t(`Node`),Pb),n(e,t(`Source`),Fb),n(e,t(`Target`),Ib),n(e,t(`Opposite`),Lb)})}function Xb(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 Zb(e,t,n){e.prototype[t]=function(e){let r;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new kb(`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=vb(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 kb(`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 Qb(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 $b(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new kb(`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=vb(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 kb(`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 ex(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new kb(`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=vb(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 kb(`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 Ob(`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 tx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 nx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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(!yb(r))throw new Ob(`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 rx(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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(!yb(r))throw new Ob(`Graph.${t}: provided attributes are not a plain object.`);return _b(i.attributes,r),this.emit(`edgeAttributesUpdated`,{key:i.key,type:`merge`,attributes:i.attributes,data: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 kb(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new kb(`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=vb(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 kb(`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 Ob(`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 ax=[{name:e=>`get${e}Attribute`,attacher:Xb},{name:e=>`get${e}Attributes`,attacher:Zb},{name:e=>`has${e}Attribute`,attacher:Qb},{name:e=>`set${e}Attribute`,attacher:$b},{name:e=>`update${e}Attribute`,attacher:ex},{name:e=>`remove${e}Attribute`,attacher:tx},{name:e=>`replace${e}Attributes`,attacher:nx},{name:e=>`merge${e}Attributes`,attacher:rx},{name:e=>`update${e}Attributes`,attacher:ix}];function ox(e){ax.forEach(function({name:t,attacher:n}){n(e,t(`Edge`),`mixed`),n(e,t(`DirectedEdge`),`directed`),n(e,t(`UndirectedEdge`),`undirected`)})}var sx=[{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 cx(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 lx(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 ux(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 dx(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 fx(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 px(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 mx(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 hx(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 gx(e,t){if(e.size===0)return Eb();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 _x(e,t,n,r,i,a){let o=t?lx:cx,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 vx(e,t,n,r){let i=[];return _x(!1,e,t,n,r,function(e){i.push(e)}),i}function yx(e,t,n){let r=Eb();return e!==`undirected`&&(t!==`out`&&n.in!==void 0&&(r=Tb(r,ux(n.in))),t!==`in`&&n.out!==void 0&&(r=Tb(r,ux(n.out,t?void 0:n.key)))),e!==`directed`&&n.undirected!==void 0&&(r=Tb(r,ux(n.undirected))),r}function bx(e,t,n,r,i,a,o){let s=n?fx:dx,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 xx(e,t,n,r,i){let a=[];return bx(!1,e,t,n,r,i,function(e){a.push(e)}),a}function Sx(e,t,n,r){let i=Eb();return e!==`undirected`&&(n.in!==void 0&&t!==`out`&&r in n.in&&(i=Tb(i,px(n.in,r))),n.out!==void 0&&t!==`in`&&r in n.out&&(t||n.key!==r)&&(i=Tb(i,px(n.out,r)))),e!==`directed`&&n.undirected!==void 0&&r in n.undirected&&(i=Tb(i,px(n.undirected,r))),i}function Cx(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 mx(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 vx(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 xx(r,this.multi,i,a,t)}throw new Ob(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function wx(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,hx(!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 _x(!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 bx(!1,r,this.multi,i,o,t,n)}throw new Ob(`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 Ob(`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 Ob(`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 Tx(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,hx(!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 _x(!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 bx(!0,r,this.multi,i,o,t,n)}throw new Ob(`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 Ex(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 Eb();if(!arguments.length)return gx(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 yx(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 Sx(r,i,n,t)}throw new Ob(`Graph.${a}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function Dx(e){sx.forEach(t=>{Cx(e,t),wx(e,t),Tx(e,t),Ex(e,t)})}var Ox=[{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 kx(){this.A=null,this.B=null}kx.prototype.wrap=function(e){this.A===null?this.A=e:this.B===null&&(this.B=e)},kx.prototype.has=function(e){return this.A!==null&&e in this.A||this.B!==null&&e in this.B};function Ax(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 jx(e,t,n,r,i){if(t!==`mixed`){if(t===`undirected`)return Ax(e,null,r,r.undirected,i);if(typeof n==`string`)return Ax(e,null,r,r[n],i)}let a=new kx,o;if(t!==`undirected`){if(n!==`out`){if(o=Ax(e,null,r,r.in,i),e&&o)return o;a.wrap(r.in)}if(n!==`in`){if(o=Ax(e,a,r,r.out,i),e&&o)return o;a.wrap(r.out)}}if(t!==`directed`&&(o=Ax(e,a,r,r.undirected,i),e&&o))return o}function Mx(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 jx(!1,e,t,n,function(e){r.push(e)}),r}function Nx(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 Px(e,t,n){if(e!==`mixed`){if(e===`undirected`)return Nx(null,n,n.undirected);if(typeof t==`string`)return Nx(null,n,n[t])}let r=Eb(),i=new kx;return e!==`undirected`&&(t!==`out`&&(r=Tb(r,Nx(i,n,n.in))),t!==`in`&&(r=Tb(r,Nx(i,n,n.out)))),e!==`directed`&&(r=Tb(r,Nx(i,n,n.undirected))),r}function Fx(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 Mx(r===`mixed`?this.type:r,i,t)}}function Ix(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.`);jx(!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 Ob(`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 Lx(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 jx(!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 Rx(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 Eb();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 Px(r===`mixed`?this.type:r,i,t)}}function zx(e){Ox.forEach(t=>{Fx(e,t),Ix(e,t),Lx(e,t),Rx(e,t)})}function Bx(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 Vx(e,t){let n={key:e};return bb(t.attributes)||(n.attributes=_b({},t.attributes)),n}function Hx(e,t,n){let r={key:t,source:n.source.key,target:n.target.key};return bb(n.attributes)||(r.attributes=_b({},n.attributes)),e===`mixed`&&n.undirected&&(r.undirected=!0),r}function Ux(e){if(!yb(e))throw new Ob(`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 Ob(`Graph.import: serialized node is missing its key.`);if(`attributes`in e&&(!yb(e.attributes)||e.attributes===null))throw new Ob(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`)}function Wx(e){if(!yb(e))throw new Ob(`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 Ob(`Graph.import: serialized edge is missing its source.`);if(!(`target`in e))throw new Ob(`Graph.import: serialized edge is missing its target.`);if(`attributes`in e&&(!yb(e.attributes)||e.attributes===null))throw new Ob(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`);if(`undirected`in e&&typeof e.undirected!=`boolean`)throw new Ob(`Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.`)}var Gx=wb(),Kx=new Set([`directed`,`undirected`,`mixed`]),qx=new Set([`domain`,`_events`,`_eventsCount`,`_maxListeners`]),Jx=[{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`}],Yx={allowSelfLoops:!0,multi:!1,type:`mixed`};function Xx(e,t,n){if(n&&!yb(n))throw new Ob(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(t=``+t,n||={},e._nodes.has(t))throw new kb(`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 Zx(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 Qx(e,t,n,r,i,a,o,s){if(!r&&e.type===`undirected`)throw new kb(`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 kb(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(s&&!yb(s))throw new Ob(`Graph.${t}: invalid attributes. Expecting an object but got "${s}"`);if(a=``+a,o=``+o,s||={},!e.allowSelfLoops&&a===o)throw new kb(`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 kb(`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 kb(`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 Nb(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 $x(e,t,n,r,i,a,o,s,c){if(!r&&e.type===`undirected`)throw new kb(`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 kb(`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 Ob(`Graph.${t}: invalid updater function. Expecting a function but got "${s}"`)}else if(!yb(s))throw new Ob(`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 kb(`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 kb(`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 _b(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 kb(`Graph.${t}: the "${i}" edge already exists in the graph.`);let h=!1,g=!1;u||(u=Zx(e,a,{}),h=!0,a===o&&(d=u,g=!0)),d||(d=Zx(e,o,{}),g=!0),f=new Nb(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 eS(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 tS=class e extends hb.EventEmitter{constructor(e){if(super(),e=_b({},Yx,e),typeof e.multi!=`boolean`)throw new Ob(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${e.multi}".`);if(!Kx.has(e.type))throw new Ob(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${e.type}".`);if(typeof e.allowSelfLoops!=`boolean`)throw new Ob(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${e.allowSelfLoops}".`);let t=e.type===`mixed`?Ab:e.type===`directed`?jb:Mb;xb(this,`NodeDataClass`,t);let n=`geid_`+Gx()+`_`,r=0;xb(this,`_attributes`,{}),xb(this,`_nodes`,new Map),xb(this,`_edges`,new Map),xb(this,`_directedSize`,0),xb(this,`_undirectedSize`,0),xb(this,`_directedSelfLoopCount`,0),xb(this,`_undirectedSelfLoopCount`,0),xb(this,`_edgeKeyGenerator`,()=>{let e;do e=n+r++;while(this._edges.has(e));return e}),xb(this,`_options`,e),qx.forEach(e=>xb(this,e,this[e])),Sb(this,`order`,()=>this._nodes.size),Sb(this,`size`,()=>this._edges.size),Sb(this,`directedSize`,()=>this._directedSize),Sb(this,`undirectedSize`,()=>this._undirectedSize),Sb(this,`selfLoopCount`,()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),Sb(this,`directedSelfLoopCount`,()=>this._directedSelfLoopCount),Sb(this,`undirectedSelfLoopCount`,()=>this._undirectedSelfLoopCount),Sb(this,`multi`,this._options.multi),Sb(this,`type`,this._options.type),Sb(this,`allowSelfLoops`,this._options.allowSelfLoops),Sb(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 Ob(`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 Ob(`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 Ob(`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 kb(`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 kb(`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 kb(`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 Xx(this,e,t).key}mergeNode(e,t){if(t&&!yb(t))throw new Ob(`Graph.mergeNode: invalid attributes. Expecting an object but got "${t}"`);e=``+e,t||={};let n=this._nodes.get(e);return n?(t&&(_b(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 Ob(`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 eS(this,n),n=n.next;while(n)}for(let e in t.in){n=t.in[e];do eS(this,n),n=n.next;while(n)}}if(this.type!==`directed`)for(let e in t.undirected){n=t.undirected[e];do eS(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=vb(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 eS(this,t),this}dropDirectedEdge(e,t){if(arguments.length<2)throw new kb(`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 kb(`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=vb(this,e,t,`directed`);if(!n)throw new $(`Graph.dropDirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return eS(this,n),this}dropUndirectedEdge(e,t){if(arguments.length<2)throw new kb(`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 kb(`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=vb(this,e,t,`undirected`);if(!n)throw new $(`Graph.dropUndirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return eS(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 Ob(`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(!yb(e))throw new Ob(`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(!yb(e))throw new Ob(`Graph.mergeAttributes: provided attributes are not a plain object.`);return _b(this._attributes,e),this.emit(`attributesUpdated`,{type:`merge`,attributes:this._attributes,data:e}),this}updateAttributes(e){if(typeof e!=`function`)throw new Ob(`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 Ob(`Graph.updateEachNodeAttributes: expecting an updater function.`);if(t&&!Cb(t))throw new Ob(`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 Ob(`Graph.updateEachEdgeAttributes: expecting an updater function.`);if(t&&!Cb(t))throw new Ob(`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 Ob(`Graph.forEachAdjacencyEntry: expecting a callback.`);Bx(!1,!1,!1,this,e)}forEachAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new Ob(`Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.`);Bx(!1,!1,!0,this,e)}forEachAssymetricAdjacencyEntry(e){if(typeof e!=`function`)throw new Ob(`Graph.forEachAssymetricAdjacencyEntry: expecting a callback.`);Bx(!1,!0,!1,this,e)}forEachAssymetricAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new Ob(`Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.`);Bx(!1,!0,!0,this,e)}nodes(){return Array.from(this._nodes.keys())}forEachNode(e){if(typeof e!=`function`)throw new Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`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 Ob(`Graph.reduceNodes: expecting a callback.`);if(arguments.length<2)throw new Ob(`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++]=Vx(r,n)});let n=Array(this._edges.size);return t=0,this._edges.forEach((e,r)=>{n[t++]=Hx(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(!yb(t))throw new Ob(`Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.`);if(t.attributes){if(!yb(t.attributes))throw new Ob(`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 Ob(`Graph.import: invalid nodes. Expecting an array.`);for(r=0,i=a.length;r<i;r++){o=a[r],Ux(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 Ob(`Graph.import: invalid edges. Expecting an array.`);for(r=0,i=a.length;r<i;r++){s=a[r],Wx(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(_b({},this._options,t));return n.replaceAttributes(_b({},this.getAttributes())),n}emptyCopy(e){let t=this.nullCopy(e);return this._nodes.forEach((e,n)=>{let r=_b({},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 kb(`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 kb(`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 kb(`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,Qx(t,`copy`,!1,i.undirected,i.key,i.source.key,i.target.key,_b({},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)&&!qx.has(e)&&typeof this[e]!=`function`&&typeof e!=`symbol`&&(r[e]=this[e]);return r.attributes=this._attributes,r.nodes=e,r.edges=t,xb(r,`constructor`,this.constructor),r}};typeof Symbol<`u`&&(tS.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=tS.prototype.inspect),Jx.forEach(e=>{[`add`,`merge`,`update`].forEach(t=>{let n=e.name(t),r=t===`add`?Qx:$x;e.generateKey?tS.prototype[n]=function(i,a,o){return r(this,n,!0,(e.type||this.type)===`undirected`,null,i,a,o,t===`update`)}:tS.prototype[n]=function(i,a,o,s){return r(this,n,!1,(e.type||this.type)===`undirected`,i,a,o,s,t===`update`)}})}),Yb(tS),ox(tS),Dx(tS),zx(tS);var nS=class extends tS{constructor(e){let t=_b({type:`directed`},e);if(`multi`in t&&t.multi!==!1)throw new Ob(`DirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`directed`)throw new Ob(`DirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},rS=class extends tS{constructor(e){let t=_b({type:`undirected`},e);if(`multi`in t&&t.multi!==!1)throw new Ob(`UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`undirected`)throw new Ob(`UndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},iS=class extends tS{constructor(e){let t=_b({multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ob(`MultiGraph.from: inconsistent indication that the graph should be simple in given options!`);super(t)}},aS=class extends tS{constructor(e){let t=_b({type:`directed`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ob(`MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`directed`)throw new Ob(`MultiDirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},oS=class extends tS{constructor(e){let t=_b({type:`undirected`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new Ob(`MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`undirected`)throw new Ob(`MultiUndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}};function sS(e){e.from=function(t,n){let r=new e(_b({},t.options,n));return r.import(t),r}}sS(tS),sS(nS),sS(rS),sS(iS),sS(aS),sS(oS),tS.Graph=tS,tS.DirectedGraph=nS,tS.UndirectedGraph=rS,tS.MultiGraph=iS,tS.MultiDirectedGraph=aS,tS.MultiUndirectedGraph=oS,tS.InvalidArgumentsGraphError=Ob,tS.NotFoundGraphError=$,tS.UsageGraphError=kb;var cS={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`}},lS={property:`--chart-neutral-text-dim`,fallback:`#71717a`},uS=2.5,dS=200,fS=3,pS=1.6;function mS(e){let t=dS/Math.max(dS,e);return Math.max(fS,9*t**.25)}function hS(e){return mS(e)*pS}var gS={eligible:cS.eligible,hidden:cS.hidden,resource:cS.resource,redirect:cS.redirect,failed:cS.failed,unchecked:cS.unchecked,dimmedNode:{property:`--chart-neutral-text-dim`,fallback:`#71717a`},edge:lS,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`}},_S=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,vS=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/;function yS(e){return _S.test(e)||vS.test(e)}var bS=50,xS=.75,SS=[{maxRatio:.2,budget:1/0},{maxRatio:.45,budget:60},{maxRatio:xS,budget:24}];function CS(e){for(let t of SS)if(e<=t.maxRatio)return t.budget;return 1}function wS(e){return Math.max(0,Math.min(1,(e.linkScoreNormalized??0)/100))}function TS(e){return e.healthState?e.healthState:hn(e)}function ES(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 DS(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 OS(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 kS(e){switch(e){case`eligible`:return`●`;case`hidden`:return`◆`;case`resource`:return`▪`;case`redirect`:return`↗`;case`failed`:return`×`;case`unchecked`:return`○`}}function AS(e,t){return!!t&&e.nodeKey===t}function jS(e,t=!1,n=1){let r=mS(n),i=uS+Math.sqrt(wS(e))*(r-uS);return t?Math.max(hS(n),i):i}function MS(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 NS(e){return .35+Math.min(1.65,Math.log2(Math.max(1,e)+1)*.28)}function PS(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)}function FS(e,t,n,r=null){let i=new aS({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)=>dt(e.nodeKey,t.nodeKey))){if(!PS(e))continue;let t=TS(e),o=MS(t,n),s=kS(t),c=AS(e,r);i.addNode(e.nodeKey,{x:e.x,y:e.y,size:jS(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)=>dt(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:NS(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 IS(e,t,n=bS){let r=t.trim().toLocaleLowerCase(),i=Math.max(0,Math.min(bS,Math.floor(n)));return[...e].sort((e,t)=>dt(e.path||e.url,t.path||t.url)||dt(e.nodeKey,t.nodeKey)).filter(e=>PS(e)?!r||`${e.path}\n${e.url}\n${e.nodeKey}`.toLocaleLowerCase().includes(r):!1).slice(0,i)}function LS(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)||dt(r.path,i.path)||dt(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>xS;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=CS(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()>xS,[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 RS={"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 zS(e){return(e&&RS[e])??RS[`no-crawl`]}var BS=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),gt({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}},VS=220;function HS(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?0:VS}function US(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function WS(e,t,n){let r=window.getComputedStyle(e).getPropertyValue(t).trim();if(r&&!r.includes(`var(`)&&yS(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(`)&&yS(a)?a:n}function GS(e){let t=t=>{let n=gS[t];return WS(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 KS(){if(typeof document>`u`)return!1;try{return!!document.createElement(`canvas`).getContext(`webgl2`)}catch{return!1}}function qS({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 JS({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 YS({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=HS();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>xS,t=CS(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(LS(n,b,()=>f.getCamera().getState().ratio,r,a));let t=f.getCamera().getState().ratio;S.current={overview:t>xS,budget:CS(t)},f.refresh()},[b,n,a,f,r,e]),null}function XS({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,x]=(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)(``),[ee,te]=(0,Z.useState)(!1),[ne,F]=(0,Z.useState)(0),[I,L]=(0,Z.useState)(``),[re,ie]=(0,Z.useState)(0),ae=(0,Z.useRef)(null),R=(0,Z.useDeferredValue)(N),z=c===void 0?k:c,B=(0,Z.useMemo)(()=>new Map(e.map(e=>[e.nodeKey,e])),[e]),V=(0,Z.useMemo)(()=>sb(a?B.get(a)?.url:null),[B,a]),oe=(0,Z.useCallback)(e=>pb(e,V),[V]),H=z?B.get(z)??null:null,se=j?B.get(j.nodeKey)??null:null,ce=(0,Z.useMemo)(()=>IS(e,R),[R,e]),le=e.some(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)),ue=(0,Z.useMemo)(()=>b?FS(e,t,b,a):null,[t,e,a,b]),de=(0,Z.useMemo)(()=>{if(!b||!ue)return null;let e=LS(ue.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}}},[ue,b]);(0,Z.useEffect)(()=>{let e=m.current;if(!e)return;let t=()=>x(GS(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`||!le?E(`checking`):E(KS()?`ready`:`unavailable`)},[le,n,e.length]),(0,Z.useEffect)(()=>{if(T!==`ready`){w(null);return}let e=!0;return Cr(()=>import(`./react-sigma_core.esm.min-DWNI6FGP.js`).then(t=>{e&&w(t)}),__vite__mapDeps([0,1,2]),import.meta.url).catch(()=>{e&&E(`unavailable`)}),()=>{e=!1}},[T]),(0,Z.useEffect)(()=>{F(0)},[R]);let fe=(0,Z.useCallback)(e=>{g.current=e,O(!!e)},[]),pe=(0,Z.useCallback)(e=>{M(e)},[]),me=(0,Z.useCallback)((e,t)=>{let n=B.get(e);n&&(c===void 0&&A(e),l?.(n),t&&g.current?.gotoNode(e),L(`Focused ${oe(n)}`))},[B,l,oe,c]),he=(0,Z.useCallback)(e=>{me(e,!1)},[me]);(0,Z.useEffect)(()=>{!D||!c||!B.has(c)?c||(ae.current=null):ae.current!==c&&(g.current?.gotoNode(c),ae.current=c)},[D,B,c]);let ge=e=>{me(e.nodeKey,!0),P(oe(e)),te(!1)},_e=()=>{window.setTimeout(()=>{document.activeElement!==h.current&&te(!1)},0)},ve=(0,Z.useMemo)(()=>s?t.length:t.filter(e=>e.isTemplate!==!0).length,[t,s]),ye=`Interactive site map showing ${US(e.length,`page`)} and ${US(ve,`internal link`)}`,be=e=>`${v}-${e.replaceAll(/[^\w-]/g,`-`)}`,xe=zS(r);if(n===`unavailable`)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??ye,className:Zt(`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:xe.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:xe.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??ye,className:Zt(`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(!le)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??ye,className:Zt(`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:xe.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:xe.detail}),d&&(0,Q.jsx)(q,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});let Se=ce.at(ne),Ce=(0,Q.jsx)(JS,{onRetry:()=>ie(e=>e+1)}),U=C?.SigmaContainer;return(0,Q.jsxs)(`section`,{ref:m,role:`group`,"aria-label":f??ye,"aria-describedby":y,className:Zt(`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)(S,{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":ee,"aria-activedescendant":ee&&Se?be(Se.nodeKey):void 0,value:N,placeholder:H?`Focused: ${oe(H)}`:`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:()=>te(!0),onBlur:_e,onChange:e=>{P(e.target.value),te(!0)},onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),te(!0),F(e=>Math.max(0,Math.min(ce.length-1,e+1)))):e.key===`ArrowUp`?(e.preventDefault(),F(e=>Math.max(0,e-1))):e.key===`Enter`&&ee&&Se?(e.preventDefault(),ge(Se)):e.key===`Escape`&&te(!1)}}),ee&&(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:ce.length>0?ce.map((e,t)=>{let n=TS(e);return(0,Q.jsxs)(`button`,{id:be(e.nodeKey),type:`button`,role:`option`,"aria-selected":t===ne,tabIndex:-1,className:Zt(`flex min-h-11 w-full items-center justify-between gap-3 px-3 py-2 text-left text-button-14 outline-none`,t===ne?`bg-surface-active text-primary`:`text-secondary hover:bg-surface-hover hover:text-primary`),onPointerDown:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>F(t),onClick:()=>ge(e),children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:oe(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(${cS[n].property})`},"aria-hidden":`true`,children:kS(n)}),(0,Q.jsx)(`span`,{title:OS(n),children:ES(n)})]})]},e.nodeKey)}):(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-secondary`,children:`No rendered pages match.`})}),ce.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:`${US(e.length,`page`)} on the map · ${US(ve,`link`)} shown`})]}),(0,Q.jsx)(`div`,{className:`relative min-h-0 flex-1 overflow-hidden`,children:T===`unavailable`?(0,Q.jsx)(qS,{onOpenInventory:d}):T===`checking`||!b||!ue||!de||!C||!U?(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)(BS,{fallback:Ce,resetToken:re,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`absolute inset-0`,children:(0,Q.jsx)(U,{graph:ue.graph,className:`relative size-full bg-bg [&_.sigma-container]:size-full`,style:{width:`100%`,height:`100%`,background:b.background},options:de.options,children:(0,Q.jsx)(YS,{setReducers:de.setReducers,reactSigma:C,graph:ue.graph,theme:b,selectedNodeKey:z,showTemplateLinks:s,onSelectNodeKey:he,onHoverNode:pe,onCameraReady:fe})})}),(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`})})]}),se&&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:oe(se)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13-strong text-heading`,children:ES(TS(se))}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-copy-13 text-secondary`,children:OS(TS(se))}),se.depth!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[US(se.depth,`click`),` from home`]}),se.auditScore!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 tabular-nums text-heading`,children:[`Score `,Math.round(se.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:[an.map(e=>(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,title:OS(e),children:[(0,Q.jsx)(`span`,{className:`w-3 text-center font-mono text-label-16-strong`,style:{color:`var(${cS[e].property})`},"aria-hidden":`true`,children:kS(e)}),DS(e)]},e)),(0,Q.jsx)(`span`,{className:`ml-auto`,children:`Bigger = more linked`}),ue&&(ue.omittedNodes>0||ue.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:I})]})}var ZS={"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 QS(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 $S(e,t){return`Worth ${U(e,et.percent)} of the ${t} score`}function eC(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function tC(e){return e>=70?`pass`:e>=40?`partial`:`fail`}function nC(e){return e===`pass`?`positive`:e===`partial`?`caution`:`negative`}function rC(e){return e===`pass`?`Pass`:e===`partial`?`Partial`:`Fail`}function iC({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)(aC,{audit:e}):(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`No findings are available for this page.`})]})}function aC({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:eC(e.auditScore),children:rC(tC(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:QS(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)(h,{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:nC(t.status),children:rC(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:$S(t.sharePct,`page`)}):null]})]})]}),ZS[t.id]&&(0,Q.jsx)(`div`,{className:`flex min-h-14 items-center`,children:(0,Q.jsx)(X,{text:ZS[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 oC=`Not recorded by this scan`,sC=`Not compared with the previous scan, because it scored different sites.`,cC=100,lC=12,uC=[];function dC(e){return Yl(e.url)}function fC(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function pC(e){return e>=70?`text-positive-400`:e>=40?`text-caution-400`:`text-negative-400`}function mC(e){return e===kn.pass?`positive`:e===kn.partial?`caution`:`negative`}var hC={[kn.pass]:`Pass`,[kn.partial]:`Partial`,[kn.fail]:`Fail`},gC=`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.`,_C=`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.`,vC={[kn.fail]:0,[kn.partial]:1,[kn.pass]:2};function yC(e){return e.pagesPartial+e.pagesFailing}function bC(e){return[...e].sort((e,t)=>vC[e.status]-vC[t.status]||yC(t)-yC(e)||e.avgScore-t.avgScore)}function xC(e){return e>=70?`Pass`:e>=40?`Partial`:`Fail`}function SC(e){return Yr(Wr(String(e)))}function CC(e){return Hr(Wr(String(e)))}function wC({projectName:e,projectId:t,runId:n,integrated:i=!1}){let{isAdmin:a}=oi(),o=Dn(gr[`site-audit`])&&!a,[s,l]=(0,Z.useState)(!1),[u,d]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=n===void 0?f:n,[g,_]=(0,Z.useState)(!1),y=(0,Z.useRef)(null),b=H(So({client:Y,path:{name:e},...m?{query:{runId:m}}:{}})),S=H({...Ci({client:Y,path:{name:e},query:{limit:30}}),enabled:!i}),C=H({...Co({client:Y,path:{name:e},query:{surface:`site-health`}}),enabled:i}),w=H(Ao({client:Y,path:{name:e},query:{limit:cC,sort:`score-asc`,...m?{runId:m}:{}}})),T=H({...Ni({client:Y,path:{name:e},query:{kind:gr[`site-audit`],limit:10}}),enabled:!i,refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.some(e=>e.status===`queued`||e.status===`running`)?3e3:1e4}),E=Ec(),O=(0,Z.useSyncExternalStore)(Ms,Qs,Qs),k=Object.values(O.runs).find(e=>e.kind===gr[`site-audit`]&&e.projectId===t),A=T.data??[],j=A.find(e=>e.status===`queued`||e.status===`running`),N=A.at(-1),P=E.isPending||!!k||!!j,ee=E.isPending?`starting`:j?.status??k?.lastAnnouncedStatus,te=(0,Z.useCallback)(async()=>{i&&C.refetch();let e=await Promise.all([b.refetch(),w.refetch(),...i?[]:[S.refetch()]]),t=e.find(e=>e.error);if(t?.error)throw t.error;return e[0]},[i,w.refetch,b.refetch,S.refetch,C.refetch]);(0,Z.useEffect)(()=>{i||m||!N||N.status!==`completed`&&N.status!==`partial`||b.data?.runId!==N.id&&y.current!==N.id&&(y.current=N.id,te().catch(t=>{ci({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`})}))},[m,i,N?.id,N?.status,e,te,b.data?.runId]);let ne=async()=>{_(!0);try{let t=await te();ci({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){ci({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{_(!1)}},F=()=>{(!Dn(gr[`site-audit`])||a)&&E.mutate({projectName:e,projectId:t})},I=ee===`running`?`Scan running`:ee===`queued`?`Scan queued`:`Starting scan`,L=b.data,re=w.data?.pages??uC,ie=(L?.pagesErrored??0)>0,ae=s&&ie,R=Ql({rows:(0,Z.useMemo)(()=>ae?re.filter(e=>e.status===`error`):re,[re,ae]),getSearchText:dC}),z=L?L.pagesAudited>re.length:!1;if((0,Z.useEffect)(()=>{l(!1),d(null)},[m,i]),b.isLoading)return(0,Q.jsxs)(`div`,{className:`flex min-h-40 items-center justify-center gap-2 text-label-14 text-secondary ${i?``:`mt-6`}`,role:`status`,children:[(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading score…`]});if(b.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 ${i?``:`mt-6`}`,role:`alert`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,Q.jsx)(D,{className:`mt-0.5 size-4 shrink-0 text-negative`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{children:[i?(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 ne(),disabled:g,children:[(0,Q.jsx)(v,{className:`size-4 ${g?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),g?`Trying again…`:`Try again`]})]});if(!L||!L.hasData)return i?(0,Q.jsxs)(`section`,{className:`material-base px-5 py-7 text-center`,children:[(0,Q.jsx)(x,{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:o?tc:`Run a new Agent Readiness audit scan to calculate page-level findings.`})]}):(0,Q.jsxs)(ws,{className:`surface-card mt-6 p-8 text-center`,children:[(0,Q.jsx)(x,{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()&&!o&&(0,Q.jsx)(`div`,{className:`mt-5 flex items-center justify-center gap-3`,children:(0,Q.jsxs)(ds,{type:`button`,onClick:F,disabled:P,children:[P?(0,Q.jsx)(c,{className:`mr-1.5 h-4 w-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(M,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?I:`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 B=L.deltaScore==null?null:`${L.deltaScore>=0?`+`:``}${L.deltaScore} vs previous`,V=L.trend===`up`?`positive`:L.trend===`down`?`negative`:`neutral`,oe=B?(0,Q.jsx)(J,{tone:V,children:B}):L.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:sC})]}):null,se=S.data?.points??[],le=se.map(e=>({runId:e.runId,date:e.auditedAt,score:e.aggregateScore})),ue=n===void 0&&f!==null,pe=re.filter(e=>e.status===`success`),me=L.factors.filter(e=>yC(e)>0).length,he=L.runStatus===`partial`,ge=L.crossCuttingIssues.some(e=>e.topRecommendations.length>0);function xe(e){let t=[];for(let n of pe){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:i?``:`mt-6`,children:[i?(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:he?`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":he?`Score so far ${L.aggregateScore} out of 100, from a scan that did not cover the whole site`:`Agent Readiness score ${L.aggregateScore} out of 100`,className:`inline-flex items-baseline gap-1 font-mono tabular-nums ${pC(L.aggregateScore)}`,children:[(0,Q.jsx)(`span`,{className:`text-heading-32`,children:L.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-14 text-muted`,children:`/100`})]}),(0,Q.jsx)(J,{tone:fC(L.aggregateScore),children:xC(L.aggregateScore)}),he?(0,Q.jsx)(J,{tone:`caution`,children:`Part of the site`}):null,oe]}),(L.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)(h,{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:(L.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 ${pC(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:[L.pagesAudited,` page`,L.pagesAudited===1?``:`s`,` scored`]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-faint`,children:`·`}),(0,Q.jsxs)(`span`,{children:[me,` check`,me===1?``:`s`,` with pages below pass`]}),L.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:[L.pagesErrored,` crawl error`,L.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:ue?`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 ${pC(L.aggregateScore)}`,children:L.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-18 text-muted`,children:`/ 100`}),(0,Q.jsx)(J,{tone:fC(L.aggregateScore),children:xC(L.aggregateScore)}),oe,P?(0,Q.jsx)(J,{tone:`neutral`,children:I}):null]}),(0,Q.jsxs)(`p`,{className:`supporting-copy mt-2 tabular-nums`,children:[L.pagesDiscovered,` URL`,L.pagesDiscovered===1?``:`s`,` in sitemap · `,L.pagesAudited,` audited · `,L.pagesSkipped,` skipped · `,L.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:L.sitemapUrl??`#`,target:`_blank`,rel:`noreferrer`,className:`max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong`,children:L.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>`."})]}),L.auditedAt?(0,Q.jsxs)(`p`,{className:`mt-0.5 text-copy-13 text-faint`,children:[`Scanned `,new Date(L.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&&se.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`}),[...se].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 ne(),disabled:g,children:[(0,Q.jsx)(v,{className:`mr-1.5 h-4 w-4 ${g?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),g?`Refreshing…`:`Refresh`]}),!K()&&!o&&(0,Q.jsxs)(ds,{type:`button`,size:`sm`,onClick:F,disabled:P,children:[P?(0,Q.jsx)(c,{className:`mr-1.5 h-4 w-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(M,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?I:`Re-run scan`]})]})]}),i?(0,Q.jsx)(TC,{trend:C.data}):null,!i&&le.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(...le.map(e=>e.score)),` to `,Math.max(...le.map(e=>e.score)),` across `,le.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)(de,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(be,{data:le,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ce,{stroke:$r,vertical:!1}),(0,Q.jsx)(fe,{dataKey:`date`,tick:Xr,tickLine:!1,axisLine:{stroke:ti},tickFormatter:SC,minTickGap:24}),(0,Q.jsx)(ve,{domain:[0,100],ticks:[0,25,50,75,100],tick:Xr,tickLine:!1,axisLine:!1,width:32}),(0,Q.jsx)(_e,{...ei,cursor:{stroke:ti,strokeWidth:1},labelFormatter:CC,formatter:e=>[`${e}/100`,`Agent Readiness score`]}),(0,Q.jsx)(ye,{type:`monotone`,dataKey:`score`,name:`score`,stroke:Zr.positive,strokeWidth:2.5,dot:{r:2.5,fill:Zr.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,(0,Q.jsxs)(`section`,{className:i?`pt-5`:`page-section-divider`,children:[i?(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:gC})]}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:ge?`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:_C})]})]}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`evidence-table ${i?`min-w-[42rem]`:``}`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:i?`Check`:`Factor`}),i?null:(0,Q.jsx)(`th`,{className:`text-right`,children:`Share`}),(0,Q.jsx)(`th`,{className:`text-right`,children:i?`Score`:`Avg`}),(0,Q.jsx)(`th`,{children:i?`Worst page`:`Status`}),(0,Q.jsx)(`th`,{children:i?`Pages affected`:`Pass / Partial / Fail`})]})}),(0,Q.jsx)(`tbody`,{children:(i?bC(L.factors):L.factors).map(e=>{let t=u===e.id,n=L.crossCuttingIssues.find(t=>t.factorId===e.id),a=t?xe(e.id):[],o=yC(e),s=e.pagesPassing+o,l=!!n?.topRecommendations.length,f=l&&o>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:()=>d(t?null:e.id),children:[t?(0,Q.jsx)(r,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}):(0,Q.jsx)(h,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}),e.name]}),ZS[e.id]&&(0,Q.jsx)(X,{text:ZS[e.id],placement:`bottom`})]})}),i?null:(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-muted`,children:typeof e.sharePct==`number`?U(e.sharePct,et.percent):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:U(null)}),(0,Q.jsx)(`span`,{className:`sr-only`,children:oC})]})}),(0,Q.jsxs)(`td`,{className:`text-right font-mono tabular-nums text-strong`,children:[e.avgScore,i?(0,Q.jsx)(`span`,{className:`text-muted`,children:`/100`}):null]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{tone:mC(e.status),children:hC[e.status]})}),i?(0,Q.jsxs)(`td`,{className:`tabular-nums ${o>0?`text-strong`:`text-muted`}`,children:[o,` of `,s]}):(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:i?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:[l&&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))}),i&&typeof e.sharePct==`number`?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:$S(e.sharePct,`site`)}):null]}):o===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Every audited page passes this check.`}):null,o>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 (`,o,`)`]}),i&&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)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading affected pages…`]}):i&&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)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(v,{className:`size-4`,"aria-hidden":`true`}),w.isFetching?`Retrying affected pages…`:`Retry affected pages`]})]}):a.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5`,children:a.slice(0,lC).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 ${pC(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.`}),a.length>lC?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`+ `,a.length-lC,` more below pass`]}):null,z&&(!i||!w.isLoading&&!w.error)?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Showing the worst `,re.length,` audited pages.`]}):null]}):null]})})}):null]},e.id)})})]})})]}),!i&&L.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:L.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:fC(e.avgScore),children:xC(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 (`,U(e.affectedPct,et.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,i?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`})]}),ie?(0,Q.jsxs)(`div`,{className:`segmented`,role:`group`,"aria-label":`Filter pages`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{l(!1),R.setPage(1)},"aria-pressed":!ae,className:`segmented-option min-h-11 tabular-nums ${ae?``:`segmented-option-active`}`,children:[`All `,L.pagesAudited]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{l(!0),R.setPage(1)},"aria-pressed":ae,className:`segmented-option min-h-11 tabular-nums ${ae?`segmented-option-active text-negative`:``}`,children:[`Errors `,L.pagesErrored]})]}):null]}),re.length>0?(0,Q.jsx)($l,{value:R.query,onChange:R.setQuery,label:`Filter audited page URLs`,placeholder:`Filter page URL or query parameters`,className:`mt-3 max-w-md`}):null,R.totalRows===0?(0,Q.jsx)(`p`,{className:`supporting-copy mt-3`,children:R.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:R.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)(D,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`err`]}):(0,Q.jsx)(`span`,{className:pC(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:fC(e.overallScore),children:xC(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)(Zl,{value:e.url,headLength:54,tailLength:20,title:e.status===`error`?e.error??e.url:e.url})})})]},e.url))})]})}),(0,Q.jsx)(eu,{page:R.page,pageSize:R.pageSize,visibleRows:R.rows.length,totalRows:R.totalRows,onPageChange:R.setPage,itemLabel:R.hasQuery?`matches`:`rows`}),z?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-faint`,children:[`Showing the worst `,re.length,` of `,L.pagesAudited,` audited pages.`]}):null]})]})]})}function TC({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===or.score&&e.value!==null?`/100`:void 0,change:Ru(e.change,e.unit),series:Bu(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`&&ju(e))?null:(0,Q.jsx)(`section`,{"aria-label":`Agent Readiness over time`,className:`border-b border-default py-5`,children:(0,Q.jsx)(Ku,{name:`Agent Readiness figures`,groups:[{key:`site-health`,label:`Every scan`,basis:zu(r.figures),figures:i}],selected:[t],onSelect:n,cadence:`scan`,instants:!0,span:Vu(o,s)})})}var EC=[{id:`map`,label:`Map`},{id:`inventory`,label:`Pages`},{id:`technical`,label:`Score`}],DC={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.`},OC=[{id:`all`,label:`All pages`,healthState:void 0},{id:`hidden`,label:`Hidden pages`,healthState:ln.hidden}];function kC(e,t,n){return AC(ub(e,n)||t)}function AC(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 jC(e){return e?e.urlVersions+(e.urlVersionsNotFetched??0):null}function MC(e,t=!1){let n=`${ZC(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 NC={[ir.metaRobotsNoindex]:`Hidden by meta robots tag`,[ir.xRobotsNoindex]:`Hidden by X-Robots-Tag header`,[ir.robotsDisallow]:`Blocked by robots.txt`,[ir.redirectTerminal]:`Redirects to another page`,[ir.canonicalToOther]:`Points to another page as canonical`,[ir.notHtmlOrUnavailable]:`Not an HTML page, so it was not scored`},PC=new Map(Object.entries(NC));function FC(e){return PC.get(e)??e}var IC=20,LC=200,RC=100,zC=100,BC=50,VC=Bn,HC=Qt,UC=new Intl.NumberFormat,WC=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}),GC={eligible:`positive`,hidden:`caution`,resource:`neutral`,redirect:`neutral`,failed:`negative`,unchecked:`neutral`};function KC(e){if(!e)return`Date unavailable`;let t=new Date(e);return Number.isNaN(t.getTime())?`Date unavailable`:WC.format(t)}function qC(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function JC(e){let t=TS(e);return{label:ES(t),tone:GC[t]}}function YC(e){return e==null?`Not scored`:U(e,et.percent)}function XC(e){return e.auditScore==null?`Not checked`:`${Math.round(e.auditScore)}/100`}function ZC(e){return e==null?`Not available`:UC.format(e)}var QC={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.`},$C=new Set([`clicksFromHome`,`linkImportance`,`internalLinks`,`pagesFound`,`pagesChecked`]);function ew(e,t){let n=QC[e];return $C.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 tw(e,t){return`${UC.format(e)} ${t}${e===1?``:`s`}`}function nw(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 rw(e){return e===`completed`?`positive`:e===`partial`||e===`queued`||e===`running`?`caution`:e===`failed`||e===`cancelled`?`negative`:`neutral`}function iw(e){return e?.hasData?e.runStatus===vt.partial?`Score so far ${e.aggregateScore}/100`:e.runStatus===vt.completed?`Score ${e.aggregateScore}/100`:null:null}var aw=`Latest scan`,ow=`Shows the most complete scan from the latest day with results. Choose a dated entry to view another scan.`;function sw(e){let t=KC(e.finishedAt??e.startedAt??e.createdAt),n=e.hasCrawlData?``:` · Score only`;return`${t} · ${qC(e.status)}${n}`}var cw=new Map(Object.entries({complete:`This scan finished on its own.`,unknown:`This scan stopped before it checked every page it found.`,"max-pages":`This scan stopped at the page limit, so some pages were not checked.`,"max-edges":`This scan stopped at the link limit, so some links are missing.`,"max-fetches":`This scan stopped after checking as many pages as it could.`,"max-duration":`This scan ran out of time, so some pages were not checked.`,"max-bytes":`This scan stopped at the data limit, so some pages were not checked.`,"max-page-bytes":`This scan skipped a page that was too large to read.`,"max-depth":`This scan stopped at the depth limit, so deeper pages were not checked.`,"max-links-per-page":`This scan stopped reading links on pages that had too many.`,"max-query-variants":`This scan stopped at the limit for pages that differ only by a query string.`,"max-sitemap-fanout":`This scan stopped at the sitemap limit, so some sitemaps were not read.`,"max-sitemap-urls":`This scan stopped at the sitemap page limit, so some pages were not found.`,"root-host-redirect":`The site moved to another address during this scan.`})),lw=gc,uw=[{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)`}],dw={"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 fw(e){return e?dw[e]??null:null}function pw(e){return e?cw.get(e)??`This scan stopped early: ${e}.`:`This scan stopped before it checked every page it found.`}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 ${tw(e.totalEdgeCount,`link`)} shown.`;let t=`${UC.format(e.contentEdgeCount)} link${e.contentEdgeCount===1?``:`s`} in your page text`,n=UC.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?`, ${UC.format(r)} unchecked`:``;return e===`complete`?t?{label:`Broken links: ${UC.format(t)} found${i}`,tone:`negative`}:r>0?{label:`Broken links: none found, ${UC.format(r)} unchecked`,tone:`caution`}:{label:`Broken links: none found`,tone:`positive`}:e===`partial`?{label:`Broken links: ${UC.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:ZC(e.total),hiddenNote:null,filtered:!1}:{filtered:!0,value:e.truncated?`${ZC(e.visible)}+`:ZC(e.visible),hiddenNote:e.hidden===0?null:e.truncated?`At least ${ZC(e.hidden)} menu and footer hidden`:`${ZC(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:ew(`clicksFromHome`,!1)}),(0,Q.jsx)(Tw,{label:`Links in`,value:t.value,hiddenNote:t.hiddenNote,help:ew(`linksIn`,t.filtered)}),(0,Q.jsx)(Tw,{label:`Links out`,value:n.value,hiddenNote:n.hiddenNote,help:ew(`linksOut`,n.filtered)}),(0,Q.jsx)(Tw,{label:`Link importance`,value:YC(e.linkScoreNormalized),help:ew(`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 ${ZC(t)} menu and footer links hidden.`:`${tw(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:ew(t,!1)})]})}function kw({url:e,rootHost:t,siteHosts:n,pageSite:r}){let i=db(e);if(n.length<2||i===null||!n.includes(i))return(0,Q.jsx)(Q.Fragment,{children:ub(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=db(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,` (`,ZC(t.length),`)`]}),n&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`First `,zC]})]}),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:ZC(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=fb(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:a,outboundTruncated:o,audit:s,auditLoading:l,auditError:u,onRetryAudit:d,rootHost:f,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=JC(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:a,showTemplateLinks:_,known:w}),O=ww({total:e.outboundUniqueEdges,visible:C.length,hidden:E,truncated:o,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:f,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 ${ub(x,f)}, not scored`}),b.map(e=>(0,Q.jsx)(`li`,{children:FC(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)(p,{className:`size-3.5`,"aria-hidden":`true`})]})})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(iC,{audit:s,isLoading:l,error:u,onRetry:d})}),(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)(c,{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:a,rootHost:f,hiddenTemplateCount:T,siteHosts:v,pageUrl:e.url}),(0,Q.jsx)(Aw,{direction:`outbound`,edges:C,truncated:o,rootHost:f,hiddenTemplateCount:E,siteHosts:v,pageUrl:e.url})]})})]})]})}function Pw({pages:e,total:t,skippedUrlVersions:n,rootHost:r,selectedNodeKey:i,onSelect:a,hasNextPage:o,isFetchingNextPage:s,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]),x=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 ${ZC(e.length)} of ${ZC(t)} pages.`:`Showing ${ZC(e.length)} of ${ZC(t)} hidden pages.`}),n!=null&&n>0&&(0,Q.jsx)(X,{...MC(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=OC.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:OC.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsxs)(`label`,{className:Zt(`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)(S,{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:OS(`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=JC(e),n=fb(e.url,r,v),o=n?AC(n.path):kC(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:OS(TS(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:ZC(e.inboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:ZC(e.outboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:YC(e.linkScoreNormalized)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:XC(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.`:x?`No matches in the ${ZC(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:s,onClick:l,children:[s&&(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),s?`Loading more pages`:`Load more pages`]})})]})}function Fw({projectName:e,runId:t,site:n,section:i,onSelect:a}){let[o,s]=(0,Z.useState)(!1),c=i.pageCount-+!!i.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:[c?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${o?`Collapse`:`Expand`} ${i.path}`,"aria-expanded":o,onClick:()=>s(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:o?(0,Q.jsx)(r,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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:()=>a(i.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:i.path}),(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:ZC(i.pageCount)})]}),o&&(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:i.path,onSelect:a})})]})}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:ZC(1)})]})})}function Lw({site:e,children:t}){let[n,i]=(0,Z.useState)(!1),a=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:[a?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${n?`Collapse`:`Expand`} ${e.host}`,"aria-expanded":n,onClick:()=>i(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)(r,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(h,{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}),a?(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:ZC(e.pages)}):(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12 text-secondary`,title:e.error??void 0,children:`Not reached`})]}),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 s={client:Y,path:{name:e},query:{runId:t,parentPath:r,limit:RC,...n?{site:n}:{}}},l=ie({...ca(s),initialPageParam:s,getNextPageParam:e=>e.nextCursor?{path:s.path,query:{...s.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)(c,{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)(c,{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),r=[`Find pages`,n===1&&t!==null?`Check pages · ${ZC(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":r[n],children:[(0,Q.jsx)(`div`,{className:`grid grid-cols-[1fr_2fr_1fr] gap-1.5`,"aria-hidden":`true`,children:r.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:r.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)(b,{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?ZC(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?ZC(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?ZC(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?ZC(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({phase:e,progress:t,onRunAgain:n}){let r=e===`cancelled`,i=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:r?`Scan cancelled`:`Scan failed`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:r?`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.`}),i&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:i}),n&&(0,Q.jsx)(q,{type:`button`,className:`mt-4`,onClick:n,children:`Run scan again`})]})}function Zw({projectName:e,projectId:t,initialRunId:n,onReleaseInitialRun:i}){let a=(0,Z.useId)(),[o,s]=(0,Z.useState)(`map`),l=(0,Z.useRef)([]),u=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=e=>{u.current?.open&&e.target instanceof Node&&!u.current.contains(e.target)&&(u.current.open=!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[]);let[d,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),[O,k]=(0,Z.useState)(null),[A,j]=(0,Z.useState)(`all`),[N,P]=(0,Z.useState)(`all`),[ee,te]=(0,Z.useState)(null),[ne,F]=(0,Z.useState)(!1),I=K(),{isAdmin:L}=oi(),re=ot(),ae=(re||Dn(gr[`site-audit`]))&&!L,R=Ec(),z=!I&&!ae,B=H({...Ai({client:Y,path:{name:e}}),enabled:z,staleTime:di});(0,Z.useEffect)(()=>{let e=h.current;e!==n&&(h.current=n,f(t=>n??(t===e?null:t)),_(null))},[n]);let V=H({...Oo({client:Y,path:{name:e},query:{limit:IC}}),refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.scans.some(e=>e.status===`queued`||e.status===`running`)?3e3:15e3}),oe=V.data?.scans??[],se=oe.find(e=>e.status===`queued`||e.status===`running`),ce=oe.find(e=>e.status===`completed`||e.status===`partial`),le=R.data?.runId??null,ue=le&&le!==p&&oe.some(e=>e.runId===le&&(e.status===`completed`||e.status===`partial`))?le:null,de=d??ue??V.data?.preferredRunId??ce?.runId??se?.runId??null,fe=se?.runId===de?se:null,pe=de?oe.find(e=>e.runId===de):void 0,me=!!(n&&de===n),he=fe?.runId??(me?de:null),ge=H({...Oa({client:Y,path:{name:e,runId:he??``}}),enabled:!!he,refetchInterval:e=>Ww(e.state.data?.phase)?3e3:!1,refetchIntervalInBackground:!0});(0,Z.useEffect)(()=>{me&&ge.isError&&qw(ge.error)===`NOT_FOUND`&&(f(null),_(null),i?.())},[ge.error,ge.isError,me,i]);let _e=Gw(ge.data?.phase),ve=Kw(ge.data?.phase)?null:fe,ye=!!(he&&ge.isPending),be=!!(me&&!pe&&ge.isError),xe=!!(ve||_e||ye||be),Se=ge.data?.phase===`failed`||ge.data?.phase===`cancelled`?ge.data.phase:me&&(pe?.status===`failed`||pe?.status===`cancelled`)?pe.status:null,Ce=H({...Ma({client:Y,path:{name:e},...de?{query:{runId:de}}:{}}),enabled:!xe}),U=Ce.data,we=de??U?.runId??null,Te=!!(we&&U?.hasCrawlData&&U.detailsAvailable),Ee=we?{runId:we}:{},De=H({...Ba({client:Y,path:{name:e},query:{...Ee,maxNodes:VC,maxEdges:HC}}),enabled:Te&&!xe}),Oe=OC.find(e=>e.id===A)?.healthState,ke=U?.sites??[],Ae=ke.map(e=>e.host),W=ke.length>1&&Ae.includes(N)?N:`all`,je={client:Y,path:{name:e},query:{...Ee,...Oe?{healthState:Oe}:{},...W===`all`?{}:{site:W},urlVersions:`exclude`,limit:LC,sort:`path`}},Me=ie({...ao(je),enabled:Te,initialPageParam:je,getNextPageParam:e=>e.nextCursor?{path:je.path,query:{...je.query,cursor:e.nextCursor}}:void 0}),Ne=Te&&(U?.deadLinks.state===`complete`||U?.deadLinks.state===`partial`),Pe=H({...Ha({client:Y,path:{name:e},query:{...Ee,limit:BC}}),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||!xn(ze),Ve=(0,Z.useMemo)(()=>ne||Be?Ie:Ie.filter(e=>!e.isTemplate),[Ie,ne,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(B.data),Ke=(ee??B.data?.siteAuditDomains??[]).filter(e=>Ge.owned.includes(e)),qe=(0,Z.useMemo)(()=>Ue.find(e=>e.nodeKey===g)??null,[Ue,g]),G=!!(Te&&g&&!qe),Je=H({...Qa({client:Y,path:{name:e},query:{...Ee,...Oe?{healthState:Oe}:{},nodeKey:g??void 0,limit:1}}),enabled:G}),Ye=qe??Je.data?.pages[0]??null,Xe=!!(g&&Oe&&G&&Je.isSuccess&&Je.data.healthStateFilter===`applied`&&Je.data.pages.length===0);(0,Z.useEffect)(()=>{Xe&&_(null)},[Xe]);let Ze=(0,Z.useMemo)(()=>Xe?null:Fe.find(e=>e.nodeKey===g)??Ye,[Fe,Ye,g,Xe]),Qe=Ze?.nodeKey??null;Ws(e,{view:`site-health`,page:{...we?{runId:we}:{},...Qe?{nodeKey:Qe}:{}}});let $e=Ze?Ye?`ready`:Je.isError?`error`:G&&Je.isLoading?`loading`:`ready`:`idle`,et=H({...wa({client:Y,path:{name:e},query:{...Ee,nodeKey:Qe??void 0,limit:zC}}),enabled:Te&&!!Qe}),tt=H({...La({client:Y,path:{name:e},query:{...Ee,nodeKey:Qe??void 0}}),enabled:Te&&!!Qe}),nt=(0,Z.useMemo)(()=>{let e=oe.filter(e=>e.status===`completed`||e.status===`partial`),t=d?oe.find(e=>e.runId===d):void 0;return t&&!e.some(e=>e.runId===t.runId)?[t,...e]:e},[oe,d]),rt=nt.length>0,it=oe[0]?.status??null,at=we?pe:void 0,st=ve?ve.status:_e?ge.data?.status??null:Se??U?.runStatus??at?.status??null,ct=st===`running`?`Scan running`:st===`queued`?`Scan queued`:st===`partial`?`Partial scan`:st===`completed`?`Complete`:st===`failed`?`Scan failed`:st===`cancelled`?`Scan cancelled`:`No scan`,lt=!!we&&(st===vt.completed||st===vt.partial),ut=H({...So({client:Y,path:{name:e},...we?{query:{runId:we}}:{}}),enabled:lt}),dt=lt?iw(ut.data):null,ft=Pe.data,pt=ft&&`found`in ft?ft:U?.deadLinks&&`found`in U.deadLinks?U.deadLinks:void 0,mt=Cw(ft?.state??U?.deadLinks?.state??`unavailable`,pt?.found,pt?.unverified),ht=nw(U?.requestedRootUrl??null,U?.rootUrl??null),gt=sb(U?.rootUrl??null),_t=De.data?.rootNodeKey??null,yt=H({...Qa({client:Y,path:{name:e},query:{...Ee,nodeKey:_t??void 0,limit:1}}),enabled:!!(Te&&_t)}),bt=(0,Z.useMemo)(()=>Fe.find(e=>e.nodeKey===_t)??yt.data?.pages[0]??null,[Fe,_t,yt.data]),xt=se&&se.runId!==de?se:null,St=R.isPending||!!ve||!!xt||_e||ye,Ct=o===`technical`?`map`:o,wt=e=>{f(e||null),m(le),_(null)},Tt=()=>{(!re&&!Dn(gr[`site-audit`])||L)&&(u.current&&(u.current.open=!1),f(null),_(null),n&&i?.(),R.mutate({projectName:e,projectId:t,projectLabel:B.data?.displayName||e,body:{checkDeadLinks:v,...b?{includeGeo:!0}:{},...S?{}:{includeAgentSkills:!1},...w===null?{}:{maxPages:w},...O===null?{}:{maxDepth:O},...Ge.owned.length>0?{sites:Ke}:{}}}),te(null))},Et=(e,t)=>{let n=e=>!t||db(e)===t,r=Fe.find(t=>(t.path===e||t.path.startsWith(`${e}/`))&&n(t.url));r&&_(r.nodeKey)},Dt=e=>s(e),Ot=(e,t)=>{let n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%EC.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+EC.length)%EC.length:e.key===`Home`?n=0:e.key===`End`&&(n=EC.length-1),n!=null&&(e.preventDefault(),Dt(EC[n].id),l.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:`Audit scan`}),(0,Q.jsx)(X,{text:DC[o]}),(0,Q.jsx)(J,{tone:rw(st),children:ct}),dt&&(0,Q.jsx)(`span`,{className:`text-label-14-strong tabular-nums text-heading`,children:dt}),at&&(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:KC(at.finishedAt??at.startedAt)})]})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start gap-2`,children:[rt&&(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:a,children:`Scan history`}),(0,Q.jsx)(X,{text:ow,placement:`bottom`})]}),(0,Q.jsxs)(`select`,{id:a,"aria-label":`View an Agent Readiness audit scan`,value:d??ue??``,onChange:e=>wt(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:aw}),nt.map(e=>(0,Q.jsx)(`option`,{value:e.runId,children:sw(e)},e.runId))]})]}),!I&&!ae&&(0,Q.jsxs)(`div`,{className:Zt(`flex items-end gap-2`,rt&&`pt-5`),children:[(0,Q.jsxs)(`details`,{ref:u,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)(E,{className:`size-4`,"aria-hidden":`true`}),`Scan settings`,(0,Q.jsx)(r,{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:St,onChange:t=>te(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:St,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:ZS[`geographic-signals`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Geographic signals`,checked:b,disabled:St,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:ZS[`agent-skill-exposure`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Agent integrations`,checked:S,disabled:St,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:St,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(B.data)}),[...hc(B.data)?[hc(B.data)]:[],...lw].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:O===null?``:String(O),disabled:St,onChange:e=>k(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:uw.map(e=>(0,Q.jsx)(`option`,{value:e.value===null?``:String(e.value),children:e.label},String(e.value)))})]})]})]}),(0,Q.jsxs)(ds,{onClick:Tt,disabled:St,children:[St?(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(M,{className:`size-4`,"aria-hidden":`true`}),se?.status===`running`?`Scan running`:se?.status===`queued`?`Scan queued`:`Run scan`]})]})]})]}),ae&&(0,Q.jsx)(Bs,{projectName:e,kind:gr[`site-audit`],loadSchedule:!re}),U?.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:ew(`pagesFound`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.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:ew(`pagesChecked`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.counts.pagesFetched)})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`div`,{className:`text-label-12 text-muted`,title:OS(`eligible`),children:`Indexable`}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.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:ew(`internalLinks`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:ZC(U.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:EC.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`site-health-${e.id}-tab`,"aria-selected":o===e.id,"aria-controls":`site-health-${e.id}-panel`,tabIndex:o===e.id?0:-1,ref:e=>{l.current[t]=e},onClick:()=>Dt(e.id),onKeyDown:e=>Ot(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 ${o===e.id?`border-strong text-heading`:`border-transparent text-secondary hover:border-base hover:text-primary`}`,children:e.label},e.id))}),U?.hasCrawlData&&o!==`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:mt.tone,children:mt.label})]})]}),!d&&se&&!ve&&(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.`}),ht&&(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:ht.requested}),` and continued at`,` `,(0,Q.jsx)(`span`,{className:`font-mono text-primary`,children:ht.effective}),`.`,` `,`The map and inventory use the new address.`]}),U?.hasCrawlData&&!U.complete&&(0,Q.jsxs)(`div`,{className:`rounded-md border border-caution bg-caution-soft px-4 py-3 text-label-14 text-caution`,role:`status`,children:[pw(U.termination),` `,!I&&!ae?fw(U.termination):null]}),!se&&it===`failed`&&!d&&(0,Q.jsxs)(`div`,{className:`flex gap-3 rounded-md border border-negative bg-negative-soft px-4 py-3 text-label-14 text-negative`,role:`alert`,children:[(0,Q.jsx)(D,{className:`mt-0.5 size-4 shrink-0`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:U?.hasCrawlData?`The latest scan failed. The previous completed results remain available.`:`The latest scan failed, and there are no earlier results to show.`})]}),Se?(0,Q.jsx)(Jw,{view:Ct,children:(0,Q.jsx)(Xw,{phase:Se,progress:ge.data,onRunAgain:ae?void 0:Tt})}):xe?(0,Q.jsx)(Jw,{view:Ct,children:(0,Q.jsx)(Yw,{status:ge.data?.phase??(ve?.status===`running`?`running`:`queued`),progress:ge.data,progressError:ge.isError,onRetryProgress:()=>{ge.refetch()}})}):o===`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)(wC,{projectName:e,projectId:t,runId:we,integrated:!0})}):Ce.isLoading?(0,Q.jsx)(Jw,{view:o,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)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading Agent Readiness…`]})}):Ce.error?(0,Q.jsx)(Jw,{view:o,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 Ce.refetch(),children:`Try again`})]})}):U?.hasCrawlData?U.detailsAvailable?o===`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)(c,{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:jC(Me.data?.pages[0]?.inventorySummary),rootHost:gt,filterUnavailable:Me.data?.pages[0]?.healthStateFilter===`unavailable-legacy-scan`,selectedNodeKey:Qe,onSelect:_,hasNextPage:!!Me.hasNextPage,isFetchingNextPage:Me.isFetchingNextPage,onLoadMore:()=>void Me.fetchNextPage(),filter:A,onFilterChange:j,sites:ke,siteFilter:W,onSiteFilterChange:P}),(0,Q.jsx)(Nw,{page:Ze,isLoading:et.isLoading&&!!Ze,error:et.error,inbound:et.data?.inbound??[],outbound:et.data?.outbound??[],inboundTruncated:et.data?.inboundTruncated??!1,outboundTruncated:et.data?.outboundTruncated??!1,audit:tt.data,auditLoading:tt.isLoading&&!!Ze,auditError:tt.error,onRetryAudit:()=>{tt.refetch()},rootHost:gt,reasonSource:Ye,reasonsState:$e,onRetryReasons:()=>{Je.refetch()},showTemplateLinks:ne||Be,siteHosts:Ae})]}):(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 `,ZC(De.data.nodes.length),` of `,ZC(De.data.totalNodes),` pages`,` and `,ZC(De.data.edges.length),` of `,ZC(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:ne,contentEdgeCount:Re,templateEdgeCount:Le,totalEdgeCount:Ie.length}),(0,Q.jsx)(X,{text:Sw(ze,{staleLayout:He&&!Be})})]}),(0,Q.jsxs)(`label`,{className:Zt(`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:ne&&!Be,disabled:Be,onChange:e=>F(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:ke.length>1?`Sites and folders in this scan`:`Folders in this scan`})]}),(0,Q.jsx)(`div`,{className:`max-h-[468px] overflow-auto`,children:we&&ke.length>1?(0,Q.jsx)(`ul`,{className:`divide-y divide-default`,children:ke.map((t,n)=>(0,Q.jsx)(Lw,{site:t,children:(0,Q.jsx)(Rw,{projectName:e,runId:we,site:t.host,parentPath:`/`,onSelect:Et,rootPage:n===0?bt:null,onSelectRootPage:_})},t.host))}):we&&(0,Q.jsx)(Rw,{projectName:e,runId:we,parentPath:`/`,onSelect:Et,rootPage:bt,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:()=>s(`inventory`),children:`Open page inventory`})]})}):(0,Q.jsx)(XS,{nodes:De.data?.nodes??[],edges:Ie,showTemplateLinks:ne||Be,layoutState:De.data?.layout.state??`unavailable`,layoutUnavailableReason:De.data?.layout.state===`unavailable`?De.data.layout.reason:null,rootNodeKey:De.data?.rootNodeKey??null,selectedNodeKey:Qe,onSelectNode:e=>_(e.nodeKey),onOpenInventory:()=>s(`inventory`),ariaLabel:`Interactive site map showing ${tw(De.data?.nodes.length??0,`page`)} and ${tw(Ve.length,`internal link`)}`})})]})]}),(0,Q.jsx)(Nw,{page:Ze,isLoading:et.isLoading&&!!Ze,error:et.error,inbound:et.data?.inbound??[],outbound:et.data?.outbound??[],inboundTruncated:et.data?.inboundTruncated??!1,outboundTruncated:et.data?.outboundTruncated??!1,audit:tt.data,auditLoading:tt.isLoading&&!!Ze,auditError:tt.error,onRetryAudit:()=>{tt.refetch()},rootHost:gt,reasonSource:Ye,reasonsState:$e,onRetryReasons:()=>{Je.refetch()},showTemplateLinks:ne||Be,siteHosts:Ae})]}):(0,Q.jsx)(Jw,{view:o,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:o,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:ae?tc:U?.legacyAuditAvailable?`The existing score is preserved. Run a new scan to build the page and internal-link map.`:I?`An Agent Readiness audit scan has not been run for this project.`:`Run a scan to discover pages, site sections, and internal links.`}),U?.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:()=>s(`technical`),children:`View score`})})]})})]})}function Qw({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=H({...Mo({client:Y,path:{name:e},query:{limit:30}}),enabled:n===`health`}),l=H({...Ni({client:Y,path:{name:e},query:{kind:gr[`answer-visibility`],limit:100}}),enabled:n===`compare`}),u=(l.data??[]).filter(e=>(e.status===vt.completed||e.status===vt.partial)&&e.trigger!==Ae.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=H({...Na({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)(_l,{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)(Uc,{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)(ws,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`No coverage history yet`}),(0,Q.jsx)(`p`,{children:Te()?Is:`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:U(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:kr.label}):U(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)(ws,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`Two completed checks are required`}),(0,Q.jsx)(`p`,{children:Te()?Is:`Run another AI Visibility check before comparing historical evidence.`})]}):null,h.data&&_.length===0?(0,Q.jsxs)(ws,{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 $w={state:`not-connected`,selection:null,snapshotCount:0,evidence:`No stored evidence yet.`,lastSnapshotAt:null},eT={contract:null,assessment:null,googleAds:$w,gtm:$w,snapshots:[]};function tT(e){return e.contractSelectionRequired?`contract-selection-required`:e.assessmentState===`loading`?`assessment-loading`:e.assessmentState===`unavailable`?`assessment-unavailable`:oT(e)?`static-mismatch`:e.assessment?.status??(e.contract?`configured`:`not-configured`)}function nT(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 rT(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 iT(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 aT(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`&&sT(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 oT(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome===`fail`)}function sT(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome!==`pass`)}function cT(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 lT(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 uT(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 dT(e){return e.length<=12?e:`…${e.slice(-10)}`}function fT(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 pT(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 mT={"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 hT(e){return e.outcome===`pass`?{label:mT[e.code],tone:`positive`,outcome:`Pass`}:e.outcome===`fail`?{label:mT[e.code],tone:`negative`,outcome:`Fail`}:{label:mT[e.code],tone:`caution`,outcome:`Unknown`}}function gT(e){return e.runtime.productionHosts.length>0?e.runtime.productionHosts.join(`, `):`the declared production site`}function _T(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 vT(e){return e.provider===`google-ads`?`Google Ads`:`Tag Manager`}function yT({label:e,connection:t,changeSelectionLabel:n,onChangeSelection:r,actionPending:i}){let a=cT(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 ${qr(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)(ds,{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 bT=`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.`,xT=`Available once Google Ads and Tag Manager are connected.`;function ST({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:rT(e)},{title:`Tag Manager`,state:e.gtm.state,ready:s,summary:e.gtm.selection,changeLabel:`Change Tag Manager container`,onChange:r,action:l?d:iT(e)}],p=o&&s&&!u?aT(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:bT})]}),p&&t?(0,Q.jsx)(ds,{type:`button`,disabled:i,onClick:()=>t(p.id),children:i?`Working…`:p.label}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:xT})]}),(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`}:cT(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)(ds,{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)(ds,{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 CT({workspace:e=eT,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=tT(e),m=nT(p),h=aT(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)(ST,{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 `,qr(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:[vT(e),` `,e.kind,`, captured `,qr(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)(ds,{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)(ds,{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:fT(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:pT(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:dT(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:dT(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:dT(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:dT(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=hT(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=lT(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:uT(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:[yT({label:`Google Ads`,connection:e.googleAds,...e.googleAds.state===`connected`||e.googleAds.state===`stale`?{changeSelectionLabel:`Change Google Ads account`,onChangeSelection:u}:{},actionPending:n}),yT({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:qr(e.capturedAt)}),(0,Q.jsx)(`td`,{className:`text-label-12-mono text-muted`,children:dT(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=hT(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 `,gT(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:dT(e.contract.gtm.tagId)}),` fires with `,_T(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:dT(e.contract.googleAds.conversionActionId)}),`. Do not change the account or publish a Tag Manager version just to verify it.`]})]})]}):null]})}var wT=3e4,TT={name:``,eventName:``,conversionActionId:``,conversionId:``,conversionLabel:``,campaignIds:``,tagId:``,triggerIds:``,variableIds:``,productionHosts:``,requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},ET=`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`,DT=`text-label-14-strong text-secondary`;function OT(e,t,n,r){return n?{snapshotCount:e,snapshotState:`unavailable`,snapshotError:Ss(r)}:t?{snapshotCount:e,snapshotState:`loading`}:{snapshotCount:e}}function kT(e){return[...new Set(e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function AT(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 jT(e,t,n){let r=[`Container ${e}`,`account ${t}`];return n&&r.push(`workspace ${n}`),r.join(` · `)}function MT(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:jT(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 NT(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:kT(e.campaignIds),requireBiddableGoal:e.requireBiddableGoal,requirePrimaryAction:e.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:e.tagId.trim(),triggerIds:kT(e.triggerIds),variableIds:kT(e.variableIds)},runtime:{verificationRequired:e.verificationRequired,requireTransactionId:e.requireTransactionId,requireValue:e.requireValue,requireCurrency:e.requireCurrency,productionHosts:kT(e.productionHosts)}}}function PT(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 FT(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 IT(e,t,n){return e?`no longer accessible`:n?`access not verified`:t?`not in the current result`:`checking access`}function LT({id:e,label:t,value:n,onChange:r,children:i,disabled:a=!1}){return(0,Q.jsxs)(`label`,{htmlFor:e,className:DT,children:[t,(0,Q.jsx)(`select`,{id:e,className:ET,value:n,onChange:e=>r(e.target.value),disabled:a,children:i})]})}function RT({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 zT({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(Ss(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)(ds,{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)(ds,{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 BT({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:DT,children:t});return i?(0,Q.jsxs)(`div`,{children:[m,(0,Q.jsx)(`select`,{id:e,className:ET,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:ET,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:ET,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:ET,value:c,onChange:e=>l(e.target.value)}):(0,Q.jsxs)(`select`,{id:e,required:!0,className:ET,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 VT({projectId:e,projectName:t}){let n=oi(),[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)(TT),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null),P=H({...Da({client:Y,path:{name:t}}),staleTime:wT}),ee=H({...wo({client:Y,path:{name:t}}),staleTime:wT}),te=H({...No({client:Y,path:{name:t}}),staleTime:wT}),ne=H({...bi({client:Y,path:{name:t}}),staleTime:wT}),F=ne.data,I=H({...Ga({client:Y,path:{name:t},query:{limit:5}}),staleTime:wT}),L=H({...Ta({client:Y,path:{name:t},query:{limit:5}}),staleTime:wT}),re=te.data??[],ie=(j?re.find(e=>e.id===j)??null:null)??(re.length===1?re[0]??null:null),ae=re.length>1&&!ie,R=H({...aa({client:Y,path:{name:t,contractId:ie?.id??``}}),enabled:!!ie,staleTime:wT}),z=H({...no({client:Y,path:{name:t}}),enabled:d===`google-ads`&&P.data?.connected===!0,staleTime:0}),B=H({...Va({client:Y,path:{name:t}}),enabled:d===`gtm`&&ee.data?.connected===!0,staleTime:0}),V=H({...Ua({client:Y,path:{name:t,accountId:x}}),enabled:d===`gtm`&&!!x,staleTime:0}),se=H({...$a({client:Y,path:{name:t,accountId:x,containerId:C}}),enabled:d===`gtm`&&!!x&&!!C,staleTime:0}),ce=oe(Yi({client:Y})),le=oe(ta({client:Y})),ue=oe(Mi({client:Y})),de=oe(Wi({client:Y})),fe=oe(Zi({client:Y})),pe=oe(ki({client:Y})),me=oe(eo({client:Y})),he=oe(fo({client:Y})),ge=oe(Xa({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||!ee.isSuccess)return;let e=ee.data.selection;S(e?.accountId??``),w(e?.containerId??``),E(e?.workspaceId??``),g(!0)},[h,ee.data,ee.isSuccess,d]),(0,Z.useEffect)(()=>{j&&te.data&&(te.data.some(e=>e.id===j)||M(null))},[te.data,j]);let _e=(0,Z.useMemo)(()=>{let e=I.data?.snapshots??[],t=L.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=R.data?.googleAdsSnapshot,a=R.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:R.data?.assessment.contract??ie,assessment:R.data?.assessment??null,contractSelectionRequired:ae,assessmentState:ie?R.isError?`unavailable`:R.isLoading?`loading`:void 0:void 0,assessmentError:R.isError?Ss(R.error):null,googleAds:AT(P.data,OT(I.data?.total??0,I.isLoading,I.isError,I.error),P.isError),gtm:MT(ee.data,OT(L.data?.total??0,L.isLoading,L.isError,L.error),ee.isError),snapshots:n,assessmentEvidenceSnapshots:r}},[ie,ae,I.data,I.error,I.isError,I.isLoading,P.data,P.isError,L.data,L.error,L.isError,L.isLoading,ee.data,ee.isError,R.data,R.error,R.isError,R.isLoading]),ve=(0,Z.useSyncExternalStore)(Ms,Qs,Qs),ye=Object.values(ve.runs).some(t=>t.projectId===e&&(t.kind===gr[`google-ads-sync`]||t.kind===gr[`gtm-sync`])),be=ce.isPending||le.isPending||ue.isPending||de.isPending||fe.isPending||pe.isPending||me.isPending||he.isPending||ge.isPending||ye;async function xe(){await Promise.all([P.refetch(),ee.refetch(),te.refetch(),I.refetch(),L.refetch(),ne.refetch(),ie?R.refetch():Promise.resolve()])}async function Se(e){await xe();for(let t=0;t<10&&!e();t+=1)await new Promise(e=>setTimeout(e,1500)),await xe()}function Ce(){let e=document.activeElement;N.current=e instanceof HTMLElement?e:null}function U(e){typeof window<`u`&&typeof window.requestAnimationFrame==`function`?window.requestAnimationFrame(e):globalThis.setTimeout(e,0)}function we(e){e&&(!e.matches(`a[href], button, input, select, textarea, summary, [contenteditable="true"]`)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=-1),e.focus({preventScroll:!0}))}function Te(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`}),we(document.getElementById(t)??n)}function Ee(e,t){Ce(),U(()=>Te(e,t))}function De(){let e=N.current;N.current=null,e&&U(()=>{e.isConnected&&e.focus({preventScroll:!0})})}function Oe(){i(null),c(!1),De()}function ke(){i(null),f(null),De()}function Ae(){i(null),O(!1),De()}function W(){i(null),f(null),c(!0),Ee(`google-ads-connect-panel`,`google-ads-connect-title`)}function je(){i(null),v(``),b(``),m(!1),f(`google-ads`),c(!1),Ee(`google-ads-selection-panel`,`google-ads-selection-title`)}function Me(){i(null),S(``),w(``),E(``),g(!1),f(`gtm`),c(!1),Ee(`gtm-selection-panel`,`gtm-selection-title`)}function Ne(){i(null),O(!0),Ee(`conversion-integrity-contract-form`,`conversion-integrity-contract-form-title`)}function Pe(e,n){Ks({id:e.id,projectId:e.projectId,kind:e.kind,projectLabel:t,sourceAction:n}),ci({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 Fe(){jc(n),i(null);try{let e=await ce.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.`),PT(e.authorizationUrl,()=>{xe(),o(null),De()})}catch(e){i(Ss(e))}}async function Ie(){jc(n),i(null);try{let e=await le.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.`),PT(e.authorizationUrl,()=>{xe(),o(null),De()})}catch(e){i(Ss(e))}}async function Le(){if(jc(n),!_)i(`Select a Google Ads customer before saving.`);else{i(null);try{await ue.mutateAsync({path:{name:t},body:{customerId:_,...y.trim()?{loginCustomerId:y.trim()}:{}}}),f(null),De(),await Se(()=>P.data?.selectedCustomer!=null)}catch(e){i(Ss(e))}}}async function Re(){if(jc(n),!x||!C)i(`Select a Tag Manager account and container before saving.`);else{i(null);try{await de.mutateAsync({path:{name:t},body:{accountId:x,containerId:C,...T?{workspaceId:T}:{}}}),f(null),De(),await Se(()=>ee.data?.status===`connected`)}catch(e){i(Ss(e))}}}async function ze(){jc(n),i(null),await me.mutateAsync({path:{name:t}}),f(null),c(!1),v(``),b(``),m(!1),o(null),await xe(),ci({title:`Google Ads disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`google-ads-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,U(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Be(){jc(n),i(null),await he.mutateAsync({path:{name:t}}),f(null),S(``),w(``),E(``),g(!1),o(null),await xe(),ci({title:`Tag Manager disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`gtm-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,U(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Ve(){jc(n),i(null);try{Pe(await fe.mutateAsync({path:{name:t}}),`google-ads-sync`)}catch(e){i(Ss(e))}}async function He(){jc(n),i(null);try{Pe(await pe.mutateAsync({path:{name:t}}),`gtm-sync`)}catch(e){i(Ss(e))}}async function Ue(){jc(n),i(null);try{let e=await Promise.allSettled([fe.mutateAsync({path:{name:t}}),pe.mutateAsync({path:{name:t}})]),[n,r]=e;n.status===`fulfilled`&&Pe(n.value,`google-ads-sync`),r.status===`fulfilled`&&Pe(r.value,`gtm-sync`);let i=e.find(e=>e.status===`rejected`);if(i?.status===`rejected`)throw i.reason}catch(e){i(Ss(e))}}async function We(){jc(n);let e=P.data?.connection?.selection.customerId,r=ee.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 ge.mutateAsync({path:{name:t},body:NT(k,e,{accountId:r.accountId,containerId:r.containerId})});A(TT),O(!1),De(),(await te.refetch()).data?.some(e=>e.id===n.id)&&M(n.id)}catch(e){i(Ss(e))}}}function Ge(e){switch(e){case`connect-google-ads`:W();return;case`connect-gtm`:Ce(),Ie();return;case`select-google-ads`:je();return;case`select-gtm`:Me();return;case`sync-google-ads`:Ve();return;case`sync-gtm`:He();return;case`sync-static-evidence`:Ue();return;case`declare-contract`:Ne();return;case`review-findings`:Ee(`conversion-integrity-findings`,`conversion-integrity-findings`);return;case`review-runtime-verification`:Ee(`conversion-integrity-runtime-guidance`,`conversion-integrity-runtime-title`);return;case`retry-connection-status`:xe();return;case`select-contract`:Ee(`conversion-integrity-contract-select`,`conversion-integrity-contract-select`);return;case`retry-integrity`:R.refetch();return;case`waiting-for-integrity`:return}}let Ke=z.data?.customers??[],qe=B.data?.accounts??[],G=V.data?.containers??[],Je=se.data?.workspaces??[],Ye=!!_&&!Ke.some(e=>e.customerId===_),Xe=!!x&&!qe.some(e=>e.id===x),Ze=!!C&&!G.some(e=>e.id===C),Qe=!!T&&!Je.some(e=>e.id===T),$e=Ye&&z.isSuccess&&z.data.truncated===!1,et=Xe&&B.isSuccess&&B.data.truncated===!1,tt=Ze&&V.isSuccess&&V.data.truncated===!1,nt=Qe&&se.isSuccess&&se.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=IT($e,z.data,z.isError),ot=IT(et,B.data,B.isError),st=IT(tt,V.data,V.isError),ct=IT(nt,se.data,se.isError),lt=z.isError?Ss(z.error):null,ut=B.isError?Ss(B.error):V.isError?Ss(V.error):se.isError?Ss(se.error):null,dt=d===`google-ads`?lt:d===`gtm`?ut:null,ft=FT(`customer`,z.data,Ke.length),pt=FT(`account`,B.data,qe.length),mt=FT(`container`,V.data,G.length),ht=FT(`draft workspace`,se.data,Je.length),gt=B.isError||V.isError||se.isError&&!!T,_t=s||d!==null||D;function vt(){z.refetch()}function yt(){B.isError?B.refetch():V.isError?V.refetch():se.isError&&se.refetch()}return P.isLoading||ee.isLoading||te.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…`})]}):te.isError&&!te.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: `,Ss(te.error)]}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void te.refetch(),children:`Retry contracts`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(CT,{workspace:_e,onPrimaryAction:Ge,actionPending:be,actionError:_t?null:r,contracts:re,selectedContractId:ie?.id??null,onSelectContract:e=>M(e||null),contractError:te.isError?Ss(te.error):null,onRetryContracts:()=>void te.refetch(),onRetryEvidence:()=>{Promise.all([I.refetch(),L.refetch()])},onChangeGoogleAdsSelection:je,onChangeGtmSelection:Me,onAddContract:()=>Ge(`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:si(async e=>{e.preventDefault(),await Fe()}),children:[(0,Q.jsxs)(`label`,{htmlFor:`google-ads-developer-token`,className:DT,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:ET,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)(ds,{type:`submit`,disabled:ce.isPending,children:ce.isPending?`Starting…`:`Continue to Google`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:Oe,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)(LT,{id:`google-ads-customer`,label:`Customer account`,value:_,onChange:e=>{m(!0),v(e);let t=Ke.find(t=>t.customerId===e);b(t?.parentCustomerId??``)},disabled:z.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:z.isLoading?`Loading accessible customers…`:`Select a customer`}),Ye?(0,Q.jsxs)(`option`,{value:_,disabled:$e,children:[`Saved customer `,_,` (`,at,`)`]}):null,Ke.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:DT,children:[`Manager account ID (optional)`,(0,Q.jsx)(`input`,{id:`google-ads-login-customer`,className:ET,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 ${z.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)(ds,{type:`button`,disabled:ue.isPending||z.isLoading||z.isError||$e||!_,onClick:si(Le),children:ue.isPending?`Saving…`:`Save customer selection`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]}),P.data?.connected?(0,Q.jsx)(zT,{providerLabel:`Google Ads`,disabled:be,onDisconnect:ze}):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:B.isError?`Retry account list`:V.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)(LT,{id:`gtm-account`,label:`Account`,value:x,onChange:e=>{g(!0),e!==x&&(w(``),E(``)),S(e)},disabled:B.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:B.isLoading?`Loading accounts…`:`Select an account`}),Xe?(0,Q.jsxs)(`option`,{value:x,disabled:et,children:[`Saved account `,x,` (`,ot,`)`]}):null,qe.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(LT,{id:`gtm-container`,label:`Container`,value:C,onChange:e=>{g(!0),e!==C&&E(``),w(e)},disabled:!x||V.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:V.isLoading?`Loading containers…`:`Select a container`}),Ze?(0,Q.jsxs)(`option`,{value:C,disabled:tt,children:[`Saved container `,C,` (`,st,`)`]}):null,G.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(LT,{id:`gtm-workspace`,label:`Draft workspace (optional)`,value:T,onChange:e=>{g(!0),E(e)},disabled:!C||se.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:se.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:B.data?.truncated?`text-caution`:`text-secondary`,children:pt}):null,mt?(0,Q.jsx)(`p`,{role:`status`,className:V.data?.truncated?`text-caution`:`text-secondary`,children:mt}):null,ht?(0,Q.jsx)(`p`,{role:`status`,className:se.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)(ds,{type:`button`,disabled:de.isPending||B.isLoading||V.isLoading||se.isLoading&&!!T||gt||rt||!x||!C,onClick:si(Re),children:de.isPending?`Saving…`:`Save container selection`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]}),ee.data?.connected?(0,Q.jsx)(zT,{providerLabel:`Tag Manager`,disabled:be,onDisconnect:Be}):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:si(async e=>{e.preventDefault(),await We()}),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:DT,children:[`Conversion name`,(0,Q.jsx)(`input`,{id:`contract-name`,required:!0,maxLength:120,className:ET,value:k.name,onChange:e=>A(t=>({...t,name:e.target.value})),placeholder:`Booking completed`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-event-name`,className:DT,children:[`Website event`,(0,Q.jsx)(`input`,{id:`contract-event-name`,required:!0,className:ET,value:k.eventName,onChange:e=>A(t=>({...t,eventName:e.target.value})),placeholder:`booking_complete`})]}),(0,Q.jsx)(BT,{id:`contract-conversion-action`,label:`Google Ads conversion action`,options:F?.googleAds.conversionActions??[],synced:F?.googleAds.syncedAt!=null,loading:ne.isLoading,failed:ne.isError,onRetry:()=>void ne.refetch(),emptyHint:`Run a Google Ads sync to list conversion actions.`,value:k.conversionActionId,onChange:e=>A(t=>({...t,conversionActionId:e}))}),(0,Q.jsx)(BT,{id:`contract-gtm-tag`,label:`Tag Manager tag`,options:F?.gtm.tags??[],synced:F?.gtm.syncedAt!=null,loading:ne.isLoading,failed:ne.isError,onRetry:()=>void ne.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:DT,children:[`Google conversion ID (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-id`,className:ET,value:k.conversionId,onChange:e=>A(t=>({...t,conversionId:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-conversion-label`,className:DT,children:[`Google conversion label (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-label`,className:ET,value:k.conversionLabel,onChange:e=>A(t=>({...t,conversionLabel:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-trigger-ids`,className:DT,children:[`Trigger IDs`,(0,Q.jsx)(`input`,{id:`contract-trigger-ids`,className:ET,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:DT,children:[`Variable IDs`,(0,Q.jsx)(`input`,{id:`contract-variable-ids`,className:ET,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:DT,children:[`Campaign IDs`,(0,Q.jsx)(`input`,{id:`contract-campaign-ids`,className:ET,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:DT,children:[`Production hosts`,(0,Q.jsx)(`input`,{id:`contract-production-hosts`,className:ET,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)(RT,{id:`contract-primary-action`,checked:k.requirePrimaryAction,onChange:e=>A(t=>({...t,requirePrimaryAction:e})),children:`Google Ads action is primary`}),(0,Q.jsx)(RT,{id:`contract-biddable-goal`,checked:k.requireBiddableGoal,onChange:e=>A(t=>({...t,requireBiddableGoal:e})),children:`Google Ads goal is biddable`}),(0,Q.jsx)(RT,{id:`contract-runtime-verification`,checked:k.verificationRequired,onChange:e=>A(t=>({...t,verificationRequired:e})),children:`Runtime proof is required`}),(0,Q.jsx)(RT,{id:`contract-transaction-id`,checked:k.requireTransactionId,onChange:e=>A(t=>({...t,requireTransactionId:e})),children:`Transaction ID is required`}),(0,Q.jsx)(RT,{id:`contract-value`,checked:k.requireValue,onChange:e=>A(t=>({...t,requireValue:e})),children:`Conversion value is required`}),(0,Q.jsx)(RT,{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)(ds,{type:`submit`,disabled:ge.isPending,children:ge.isPending?`Saving…`:`Save conversion contract`}),(0,Q.jsx)(q,{type:`button`,variant:`outline`,onClick:Ae,children:`Cancel`})]})]})]}):null]})}var HT=6e4,UT=[`7d`,`14d`,`30d`],WT=`not available`,GT=`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%.`,KT=`No Google Ads snapshot stored yet`,qT=`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.`,JT=`No closed days yet`,YT=`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.`,XT={"insufficient-history":`Period change is hidden: the stored snapshot does not cover a prior period of equal length yet.`},ZT=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),QT=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),$T=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function eE(e,t){return e===null||!Number.isFinite(e)?WT:t===null?$T.format(e/1e6):cl(e,t)}function tE(e){return e===null||!Number.isFinite(e)?WT:U(e)}function nE(e,t){return e===null||!Number.isFinite(e)?`${WT} vs prior ${t}d`:e===0?`no change vs prior ${t}d`:`${e>0?`↑`:`↓`} ${U(Math.abs(e))} vs prior ${t}d`}function rE(e){return e===`enabled`?`positive`:e===`paused`?`caution`:`neutral`}function iE(e){return e===`enabled`?`Enabled`:e===`paused`?`Paused`:e===`removed`?`Removed`:`Unknown`}function aE(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 oE({projectName:e}){let[t,n]=(0,Z.useState)(`14d`),[r,i]=(0,Z.useState)(()=>new Set([`costMicros`,`conversions`])),a=H({...mo({client:Y,path:{name:e},query:{window:t}}),staleTime:HT}),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:GT})]}),o?.source?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[Jr(o.startDate),` to `,Jr(o.endDate),` · `,o.days,` closed `,o.days===1?`day`:`days`]}):null]}),(0,Q.jsx)(wu,{windows:UT,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: `,Ss(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?JT:KT}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e?YT:qT})]})]})}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:eE(c.costMicros,m),change:d?.change.costMicros??null,direction:`none`,seriesKey:`costMicros`},{key:`conversions`,comparable:!0,label:`Conversions`,value:QT.format(c.conversions),change:d?.change.conversions??null,direction:`up-good`,seriesKey:`conversions`},{key:`cost-per-conversion`,label:`Cost / conv.`,value:g?`no conversions`:eE(c.costPerConversionMicros,m),change:null,comparable:!1,direction:`down-good`,seriesKey:null},{key:`conversion-rate`,comparable:!0,label:`Conv. rate`,value:tE(c.conversionRate),change:d?.change.conversionRate??null,direction:`up-good`,seriesKey:null}],v=[{key:`clicks`,label:`Clicks`,value:ZT.format(c.clicks),seriesKey:`clicks`},{key:`impressions`,label:`Impressions`,value:ZT.format(c.impressions),seriesKey:`impressions`},{key:`ctr`,label:`CTR`,value:tE(c.ctr),seriesKey:`ctr`},{key:`cpc`,label:`CPC`,value:eE(c.cpcMicros,m),seriesKey:null}],y={costMicros:{label:`Spend`,color:Rr[1],axisId:`spend`,formatValue:e=>eE(e,m)},conversions:{label:`Conversions`,color:Rr[0],axisId:`conversions`,formatValue:e=>QT.format(e)},clicks:{label:`Clicks`,color:Rr[2],axisId:`clicks`,formatValue:e=>ZT.format(e)},impressions:{label:`Impressions`,color:Rr[3],axisId:`impressions`,formatValue:e=>ZT.format(e)},ctr:{label:`CTR`,color:Rr[4],axisId:`ctr`,formatValue:e=>tE(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 `,ZT.format(h.queried),` of`,` `,ZT.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:XT[`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 ${aE(e.change,e.direction)}`,children:nE(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)(Br,{data:l,xKey:`date`,series:b,xTickFormatter:Vr,labelFormatter:Jr}),(0,Q.jsx)(`ul`,{className:`sr-only`,children:l.map(e=>(0,Q.jsxs)(`li`,{children:[Jr(e.date),`:`,` `,b.map(t=>{let n=e[t.dataKey];return`${t.label} ${n===null?WT: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:rE(e.status),children:iE(e.status)})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:ZT.format(e.totals.impressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:ZT.format(e.totals.clicks)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:eE(e.totals.costMicros,m)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:QT.format(e.totals.conversions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:tE(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:eE(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:Hr(Wr(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:Jr(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:Jr(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 sE={proposed:{label:`New`,tone:`caution`},confirmed:{label:`Included`,tone:`positive`},excluded:{label:`Excluded`,tone:`neutral`}};function cE(e){return e.trim().toLocaleLowerCase()}function lE(e,t){return!t||`${e.name} ${(e.urls??[e.url]).join(` `)}`.toLocaleLowerCase().includes(t)}function uE({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 dE({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)(mE,{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 fE({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=cE(r),m=t.filter(e=>lE(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=sE[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)(uE,{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 pE(e){return e.activeStep===`import`?(0,Q.jsx)(dE,{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)(fE,{...e})}function mE({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
7
  `)??``),[u,d]=(0,Z.useState)(e?.identityAliases.join(`
8
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
9
  `).map(e=>e.trim()).filter(Boolean):[o.trim()],identityAliases:u.split(`