@canonry/canonry 7.99.0 → 7.100.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -16
- package/assets/agent-workspace/AGENTS.md +13 -6
- package/assets/agent-workspace/skills/aero/SKILL.md +45 -26
- package/assets/agent-workspace/skills/aero/references/agent-operations.md +47 -12
- package/assets/agent-workspace/skills/aero/references/memory-patterns.md +1 -1
- package/assets/agent-workspace/skills/aero/references/orchestration.md +9 -9
- package/assets/agent-workspace/skills/aero/references/reporting.md +8 -4
- package/assets/agent-workspace/skills/aero/references/seo-analysis.md +2 -2
- package/assets/agent-workspace/skills/aero/references/site-health.md +23 -22
- package/assets/agent-workspace/skills/aero/soul.md +2 -2
- package/assets/agent-workspace/skills/canonry/SKILL.md +37 -7
- package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +14 -11
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +122 -53
- package/assets/assets/AccessControls-DzO5Y8v9.js +2 -0
- package/assets/assets/AgentSetupPage-DWWovaCw.js +36 -0
- package/assets/assets/AuditHistoryPanel-BG-n1i8c.js +1 -0
- package/assets/assets/BacklinksPage-D6wdOMXt.js +1 -0
- package/assets/assets/ChartPrimitives-CtKdkn64.js +3 -0
- package/assets/assets/Hint-3TTi0MgX.js +1 -0
- package/assets/assets/{HistoryPage-DNE76LNh.js → HistoryPage-B_ReWHbL.js} +1 -1
- package/assets/assets/InfoTooltip-D29JcNMW.js +1 -0
- package/assets/assets/MeasurementPropertyPage-zdyLL-kl.js +4 -0
- package/assets/assets/ProjectPage-KZNKXR4w.js +15 -0
- package/assets/assets/RunsPage-DxN0xXQh.js +1 -0
- package/assets/assets/ServerTrafficSection-CvISj5pf.js +40 -0
- package/assets/assets/SettingsPage-CpRpBlMV.js +1 -0
- package/assets/assets/ToneBadge-DcwPruHr.js +60 -0
- package/assets/assets/TrafficPage-zk6zMZyz.js +1 -0
- package/assets/assets/TrafficSourceDetailPage-DJtsI06Z.js +1 -0
- package/assets/assets/{account-context-j3asaevn.js → account-context-CoJVqEXZ.js} +1 -1
- package/assets/assets/{agent-trust-copy--U_DFYQE.js → agent-trust-copy-BIXDMtBm.js} +1 -1
- package/assets/assets/{card-CQAQ-c3g.js → card-Dwmc7Srx.js} +1 -1
- package/assets/assets/index-fh1T5JQY.css +1 -0
- package/assets/assets/index-mqc2mWUR.js +42 -0
- package/assets/assets/query-client-Tg1fZu4i.js +1 -0
- package/assets/assets/react-query-BqcEEfEO.js +1 -0
- package/assets/assets/{react-sigma_core.esm.min-BAq_-iP1.js → react-sigma_core.esm.min-D1q0DR_j.js} +3 -3
- package/assets/assets/{server-traffic-jKXLZyeC.js → server-traffic-Djnh_9f0.js} +1 -1
- package/assets/assets/service-BQjBdN4O.js +1 -0
- package/assets/assets/use-tooltip-position-BOzm-6Wy.js +1 -0
- package/assets/assets/vendor-lucide-iE5MEh2-.js +1 -0
- package/assets/assets/{vendor-markdown-BDQ1GKGP.js → vendor-markdown-BBGbNklj.js} +1 -1
- package/assets/assets/{vendor-radix-BGYlvS2l.js → vendor-radix-DKCt5Z_h.js} +1 -1
- package/assets/assets/{vendor-recharts-DhEHcK3G.js → vendor-recharts-D3MLFU3q.js} +1 -1
- package/assets/assets/{vendor-tanstack-BNuZ37rE.js → vendor-tanstack-B90HW50P.js} +2 -2
- package/assets/index.html +16 -15
- package/dist/{ads-EYDUTG4U.js → ads-FVPZ6R6Z.js} +3 -3
- package/dist/{agent-KTK2IDB3.js → agent-2LPU2E5I.js} +7 -7
- package/dist/{agent-ask-KPZOH6RY.js → agent-ask-5ODREK6D.js} +3 -3
- package/dist/{agent-conversations-BCWA4JJL.js → agent-conversations-SNLOOJEM.js} +3 -3
- package/dist/{agent-journeys-UBVLQ7JV.js → agent-journeys-XDXVL6PK.js} +3 -3
- package/dist/{agent-memory-24SYEGEX.js → agent-memory-NKAI2S3U.js} +3 -3
- package/dist/{agent-providers-E7EWFE5P.js → agent-providers-R5L7A72X.js} +3 -3
- package/dist/{agent-transcript-QGJ45NW5.js → agent-transcript-C5WAGYVC.js} +3 -3
- package/dist/{analytics-GHVG5CCT.js → analytics-EJVOLIQL.js} +33 -13
- package/dist/{apply-7YLB2DPH.js → apply-I6JOM247.js} +3 -3
- package/dist/{backfill-WNQ6O5WP.js → backfill-UVUR36IB.js} +10 -10
- package/dist/{backlinks-ZBZR4D27.js → backlinks-3VMVACWN.js} +3 -3
- package/dist/{bing-4VBSKPSX.js → bing-R5RL3PW2.js} +3 -3
- package/dist/{bootstrap-7ESCLP2G.js → bootstrap-GMMSDTNO.js} +12 -12
- package/dist/{cdp-WBL6FZTL.js → cdp-FJKUXHEY.js} +7 -7
- package/dist/{chunk-L53ZSQN5.js → chunk-2DV7F6XA.js} +91 -2
- package/dist/{chunk-MTW37GXF.js → chunk-2FWYWGIR.js} +2 -2
- package/dist/{chunk-DMPSA7ZS.js → chunk-56VVRWJM.js} +14 -5
- package/dist/{chunk-YACKJGY4.js → chunk-7BEGCVVB.js} +1 -1
- package/dist/{chunk-YMHN4UIT.js → chunk-7BH53MOB.js} +27 -2
- package/dist/{chunk-XPIMVXAI.js → chunk-7J2RIIYU.js} +1366 -1033
- package/dist/{chunk-UY6SKAKW.js → chunk-7SNMIXEQ.js} +2 -2
- package/dist/{chunk-C55P75G4.js → chunk-AMGM55CP.js} +2 -2
- package/dist/{chunk-ZN2TEBBX.js → chunk-AYKTVQF7.js} +13 -5
- package/dist/{chunk-74V5EPZH.js → chunk-BKDRT4VS.js} +7 -7
- package/dist/{chunk-O6RXNSNW.js → chunk-COHSL6KW.js} +1 -1
- package/dist/{chunk-3WDQ5GPO.js → chunk-DGDLLRS4.js} +1 -1
- package/dist/{chunk-VADVPARO.js → chunk-DHIB7EIA.js} +4 -4
- package/dist/{chunk-3MFYM2IS.js → chunk-EE3QTCLS.js} +18 -6
- package/dist/{chunk-DLOWRO5R.js → chunk-F46TBLXK.js} +204 -94
- package/dist/{chunk-P764TJKQ.js → chunk-FBO25TA3.js} +1 -1
- package/dist/{chunk-SY3CWJR4.js → chunk-FZ3MUTU3.js} +2 -2
- package/dist/{chunk-WA6APXI6.js → chunk-G6QN4VFS.js} +16 -10
- package/dist/{chunk-YBWATBX4.js → chunk-HBHLYWKE.js} +9 -6
- package/dist/{chunk-5ZOM5BJS.js → chunk-HL2LGRTI.js} +8 -6
- package/dist/chunk-J6536OL6.js +31 -0
- package/dist/{chunk-3MKJ4LP6.js → chunk-KVRX7YIH.js} +20 -10
- package/dist/{chunk-3VPBRGPN.js → chunk-LJO2BKWU.js} +1 -1
- package/dist/{chunk-YEUULP44.js → chunk-LNVFERI4.js} +1 -1
- package/dist/{chunk-WXAF7AMC.js → chunk-NQYJHKML.js} +39 -7
- package/dist/{chunk-UPHHKO3L.js → chunk-O5UFAXUI.js} +646 -588
- package/dist/{chunk-XQP3XHLJ.js → chunk-O6APBEJE.js} +2 -2
- package/dist/{chunk-47X24IJG.js → chunk-O7S7OHLE.js} +9393 -8394
- package/dist/{chunk-2RW5D55K.js → chunk-QS5DWJDI.js} +2 -2
- package/dist/{chunk-TVBOK4P2.js → chunk-RBG2QXQM.js} +4 -4
- package/dist/{chunk-LM7HTNUO.js → chunk-SWZXHHAG.js} +16 -8
- package/dist/{chunk-AY7SDX6G.js → chunk-T7UDY7W3.js} +26 -11
- package/dist/{chunk-AJD252SX.js → chunk-UGO2FO6V.js} +119 -55
- package/dist/{chunk-PT5HNVCM.js → chunk-VHULVUDL.js} +1 -1
- package/dist/{chunk-ZGBLNKFN.js → chunk-YGAQQSCL.js} +56303 -54933
- package/dist/{chunk-RRXLJPBN.js → chunk-YIIRS7V7.js} +98 -65
- package/dist/{chunk-VOVT2H25.js → chunk-YU2WX7RD.js} +3 -3
- package/dist/{citations-N5MGNKJN.js → citations-LOEQRDUB.js} +21 -10
- package/dist/{cli-catalog-FFU7PHW7.js → cli-catalog-5RXNUFBS.js} +3 -3
- package/dist/{cli-commands-AMIDEUO2.js → cli-commands-HE2BQY3Y.js} +7 -7
- package/dist/cli.js +22 -17
- package/dist/{competitor-GRA2GMZR.js → competitor-PIX2BHJW.js} +3 -3
- package/dist/{content-YVAPTIV4.js → content-PJGW4WZF.js} +3 -3
- package/dist/{dashboard-33ACBR5A.js → dashboard-7OKBD4MG.js} +6 -6
- package/dist/{demo-AGXWBMR6.js → demo-SCOFAWFM.js} +1 -1
- package/dist/{demo-server-W4YAC7GT.js → demo-server-SJPI6RSL.js} +38 -36
- package/dist/{discover-BH33TO4Z.js → discover-I3WL2QUN.js} +10 -8
- package/dist/{discover-eval-3CEA6DEE.js → discover-eval-YRECOIP5.js} +3 -3
- package/dist/{doctor-ZAYTD5PC.js → doctor-F4J6LILX.js} +3 -3
- package/dist/{evidence-247GL7UK.js → evidence-MYQTCY4V.js} +25 -10
- package/dist/{export-cmd-HLKWFI5Q.js → export-cmd-3SUFOJM6.js} +3 -3
- package/dist/{ga-BMING57Z.js → ga-VA6FYK4L.js} +3 -3
- package/dist/{gbp-MIB5CXSD.js → gbp-DI6ZVFHL.js} +3 -3
- package/dist/{google-5JP6RYAW.js → google-UVKWJCD2.js} +4 -4
- package/dist/{google-marketing-25OBMPS6.js → google-marketing-S63HN733.js} +1 -1
- package/dist/{health-cmd-D5XSEL7H.js → health-cmd-DOZXGI46.js} +16 -9
- package/dist/{history-6MDRFPQ3.js → history-UTJTUDYK.js} +3 -3
- package/dist/index.d.ts +211 -19
- package/dist/index.js +26 -26
- package/dist/{init-RDR75N2Y.js → init-IVJSS33J.js} +19 -19
- package/dist/{insights-QZVMBGVM.js → insights-UHCVCZ76.js} +3 -3
- package/dist/intelligence-service-3EENJ5DS.js +16 -0
- package/dist/{journeys-TABTZDFZ.js → journeys-XIT7WDM2.js} +3 -3
- package/dist/{keys-SL5YF7NQ.js → keys-MQKW4JUI.js} +3 -3
- package/dist/{keyword-OCDEXRSW.js → keyword-EASMKYZ3.js} +3 -3
- package/dist/{logs-CSC7O364.js → logs-ZHZ6XM55.js} +3 -3
- package/dist/{mcp-P725OHAJ.js → mcp-ECVT2YGU.js} +4 -4
- package/dist/mcp.js +10 -10
- package/dist/{measurement-plan-Z42GBJBO.js → measurement-plan-7FQKUOMR.js} +5 -5
- package/dist/{notify-E5JBES4I.js → notify-TC7ARC6W.js} +3 -3
- package/dist/{organic-evidence-CUA3T64O.js → organic-evidence-M34MWJXE.js} +7 -4
- package/dist/overview-P6BRMXJN.js +314 -0
- package/dist/{project-2ULM64TV.js → project-WZ2YXFPJ.js} +4 -4
- package/dist/project-setup-WV6SPGIV.js +176 -0
- package/dist/{query-Y47IEFKJ.js → query-WAFJKDHG.js} +3 -3
- package/dist/{research-DPFQZ3TE.js → research-B5ZPQX7R.js} +3 -3
- package/dist/{results-export-KBHOBQAH.js → results-export-NIZV6R3K.js} +3 -3
- package/dist/{run-4CYHVIIU.js → run-ICLPZ7QT.js} +7 -4
- package/dist/{schedule-GY4P3RON.js → schedule-4C44LQ7R.js} +22 -3
- package/dist/{search-AGVNZMJQ.js → search-UJM7KII3.js} +11 -4
- package/dist/{serve-5LFKIXNL.js → serve-A6UIO6WP.js} +30 -29
- package/dist/{session-YAYEDM3P.js → session-RTE22GQT.js} +14 -14
- package/dist/settings-BOF5Z7ML.js +211 -0
- package/dist/{sitemaps-APTY7U6H.js → sitemaps-BM7S76H2.js} +4 -4
- package/dist/{skills-4BUONEIZ.js → skills-X5SR4HRO.js} +2 -2
- package/dist/{snapshot-BXCWSF5P.js → snapshot-KLKE37VY.js} +4 -4
- package/dist/{src-R7XZUX3D.js → src-EKLG5A6O.js} +4 -2
- package/dist/{status-SB6HPBYJ.js → status-OYG57DWU.js} +6 -5
- package/dist/{technical-aeo-G7UEMWZD.js → technical-aeo-KWVWOOTI.js} +23 -23
- package/dist/{telemetry-H4S4Y7YV.js → telemetry-KGE6FF3Y.js} +4 -4
- package/dist/{tools-46XX6I4R.js → tools-4R33AZQ3.js} +11 -11
- package/dist/{traffic-I6WRJN3W.js → traffic-SVMOKCSS.js} +7 -11
- package/dist/{trends-AQK3GLWF.js → trends-RGAKGX3L.js} +4 -4
- package/dist/{users-SNTVY6OB.js → users-47WKA2TO.js} +3 -3
- package/dist/{visibility-stats-44QAD2XS.js → visibility-stats-DTGQJPNV.js} +9 -5
- package/dist/{wordpress-N7LTOW46.js → wordpress-2CNUX4UE.js} +3 -3
- package/package.json +1 -1
- package/assets/assets/AgentSetupPage-yOqSVJ-e.js +0 -18
- package/assets/assets/AuditHistoryPanel-CiTzFgbw.js +0 -1
- package/assets/assets/BacklinksPage-DmRdQsFQ.js +0 -1
- package/assets/assets/ChartPrimitives-CvK6CQrj.js +0 -1
- package/assets/assets/Hint-c4a4W87X.js +0 -1
- package/assets/assets/InfoTooltip-Drnst4ML.js +0 -1
- package/assets/assets/MeasurementPropertyPage-Cx64Fnmz.js +0 -4
- package/assets/assets/ProjectPage-DNfgC82V.js +0 -11
- package/assets/assets/RunsPage-BmPKBKKr.js +0 -1
- package/assets/assets/SettingsPage-Dl0TNeVK.js +0 -1
- package/assets/assets/SiteHealthSection-DxQPaR--.js +0 -2
- package/assets/assets/ToneBadge-BhjTBHi-.js +0 -60
- package/assets/assets/TrafficPage-CJp0pS01.js +0 -40
- package/assets/assets/TrafficSourceDetailPage-DKE8tSw5.js +0 -1
- package/assets/assets/format-helpers-BPugHeIX.js +0 -3
- package/assets/assets/index-BAxHW-1G.css +0 -1
- package/assets/assets/index-xlDLvgRC.js +0 -60
- package/assets/assets/query-client-CwZpfiiD.js +0 -1
- package/assets/assets/react-query-CBpNFR4t.js +0 -1
- package/assets/assets/service-DFumlmXt.js +0 -1
- package/assets/assets/vendor-lucide-DuOM7wVi.js +0 -1
- package/dist/intelligence-service-KQE7RO5I.js +0 -16
- package/dist/overview-UKQ52I72.js +0 -213
- package/dist/settings-HUKMWRHY.js +0 -119
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./react-sigma_core.esm.min-D1q0DR_j.js","./rolldown-runtime-XKyaHtl9.js","./vendor-lucide-iE5MEh2-.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,U as p,X as m,a as h,b as g,c as _,dt as v,et as y,ft as b,g as x,h as S,i as C,n as w,p as T,s as E,st as D,t as O,tt as k,w as A}from"./vendor-lucide-iE5MEh2-.js";import{a as j,i as M,o as N,r as P,s as F,t as I}from"./vendor-radix-DKCt5Z_h.js";import{r as L}from"./vendor-markdown-BBGbNklj.js";import{O as R,T as z,_ as B,d as ee,f as te,p as ne,r as V,u as H,v as re,x as U}from"./vendor-tanstack-B90HW50P.js";import{c as ie,f as ae,i as oe,l as se,m as ce,o as le,p as ue,r as de,s as fe,t as pe,u as me}from"./vendor-recharts-D3MLFU3q.js";import{$n as he,$r as ge,A as _e,Ai as ve,Ar as ye,At as be,Bi as xe,Bt as Se,Ca as Ce,Ci as we,Cr as Te,Da as Ee,Di as De,Dr as W,Ea as Oe,Ei as ke,Er as Ae,Et as G,F as je,Fi as Me,Fn as Ne,Gr as Pe,H as Fe,Ht as Ie,I as Le,In as Re,Jr as ze,Jt as Be,K as Ve,Kr as He,Kt as Ue,L as We,Li as Ge,Lr as Ke,Ma as qe,Mr as Je,N as Ye,Na as Xe,Nt as Ze,Oc as Qe,Oi as $e,Or as et,Ot as tt,Pi as nt,Qi as rt,Qn as K,Qr as it,Ri as at,Rn as ot,Rr as st,Rt as ct,Sa as lt,Si as ut,Ta as dt,Ti as ft,Tr as pt,Tt as mt,Ur as ht,Ut as gt,Vi as _t,Vt as vt,W as yt,Wi as bt,Wr as xt,X as St,Xi as Ct,Xn as wt,Xr as Tt,Yr as Et,Yt as Dt,Zi as Ot,Zn as kt,Zr as At,Zt as jt,_a as Mt,_t as Nt,a as Pt,ar as Ft,at as It,ba as Lt,bi as Rt,c as zt,ca as Bt,cr as Vt,ct as Ht,da as Ut,dn as Wt,dr as Gt,dt as Kt,ea as qt,ei as Jt,er as Yt,f as Xt,fn as Zt,fr as Qt,ft as $t,g as en,ga as tn,gi as nn,gr as rn,gt as q,h as an,ha as on,hn as sn,hr as cn,i as ln,ia as un,ir as dn,it as fn,j as pn,ja as mn,ji as hn,jn as gn,jr as _n,kc as vn,ki as yn,kr as bn,l as xn,la as Sn,lr as Cn,m as wn,ma as Tn,mn as En,mr as Dn,na as On,nr as kn,o as An,or as jn,ot as Mn,p as Nn,pa as Pn,pn as Fn,pr as In,pt as Ln,qi as Rn,qr as zn,qt as Bn,r as J,ra as Vn,rr as Hn,s as Un,sn as Wn,sr as Gn,t as Y,ta as Kn,ti as qn,tr as Jn,u as Yn,ur as Xn,vt as Zn,wi as Qn,wn as $n,wr as er,wt as tr,x as nr,xi as rr,xt as ir,yt as ar,zi as or,zt as sr}from"./ToneBadge-DcwPruHr.js";import{A as cr,B as lr,C as ur,D as dr,E as fr,F as pr,H as mr,I as hr,L as gr,M as _r,N as vr,O as yr,P as br,R as xr,S as Sr,T as Cr,V as wr,_ as Tr,a as Er,b as Dr,c as Or,d as kr,f as Ar,g as jr,h as Mr,i as Nr,j as Pr,k as Fr,l as Ir,m as Lr,n as Rr,o as zr,p as Br,r as Vr,s as Hr,u as Ur,v as Wr,w as Gr,x as Kr,y as qr,z as Jr}from"./AccessControls-DzO5Y8v9.js";import{B as Yr,C as Xr,D as Zr,F as Qr,I as $r,L as ei,M as ti,N as ni,O as ri,P as ii,R as ai,S as oi,T as si,_ as ci,a as li,b as ui,c as di,d as fi,f as pi,g as mi,h as hi,i as gi,j as _i,k as vi,l as yi,m as bi,n as xi,o as Si,p as Ci,r as wi,s as Ti,t as Ei,u as Di,x as Oi,y as ki,z as Ai}from"./ChartPrimitives-CtKdkn64.js";import{r as ji}from"./account-context-CoJVqEXZ.js";import{t as Mi}from"./async-handler-Bj3TnIRw.js";import{d as Ni,l as Pi,n as Fi,o as Ii,s as Li,t as Ri,u as zi}from"./query-client-Tg1fZu4i.js";import{$ as Bi,$t as Vi,A as Hi,An as Ui,At as Wi,B as Gi,Bn as Ki,Bt as qi,C as Ji,Cn as Yi,D as Xi,Dn as Zi,Dt as Qi,E as $i,En as ea,F as ta,Ft as na,G as ra,Gt as ia,H as aa,Ht as oa,I as sa,In as ca,It as la,J as ua,Jt as da,K as fa,Kt as pa,L as ma,Ln as ha,M as ga,Mn as _a,Mt as va,N as ya,Nn as ba,Nt as xa,O as Sa,On as Ca,Ot as wa,P as Ta,Pn as Ea,Pt as Da,Q as Oa,Qt as ka,R as Aa,Rn as ja,S as Ma,Sn as Na,T as Pa,Tn as Fa,Tt as Ia,U as La,Ut as Ra,V as za,Vt as Ba,W as Va,Wt as Ha,X as Ua,Xt as Wa,Y as Ga,Yt as Ka,Z as qa,Zt as Ja,_ as Ya,_n as Xa,_t as Za,an as Qa,at as $a,b as eo,c as to,ct as no,d as ro,dn as io,dt as ao,en as oo,et as so,f as co,fn as lo,ft as uo,g as fo,gt as po,h as mo,ht as ho,in as go,it as _o,j as vo,jn as yo,k as bo,kn as xo,kt as So,l as Co,lt as wo,m as To,n as Eo,nt as Do,o as Oo,on as ko,ot as Ao,p as jo,pn as Mo,pt as No,q as Po,qt as Fo,r as Io,rn as Lo,rt as Ro,s as zo,st as Bo,t as Vo,tt as Ho,u as Uo,ut as Wo,v as Go,vn as Ko,vt as qo,w as Jo,wn as Yo,wt as Xo,x as Zo,xt as Qo,y as $o,z as es,zn as ts,zt as ns}from"./react-query-BqcEEfEO.js";import{t as X}from"./InfoTooltip-D29JcNMW.js";import{t as rs}from"./card-Dwmc7Srx.js";import{$ as is,A as as,At as os,C as ss,Ct as cs,D as ls,Dt as us,E as ds,F as fs,Ft as ps,G as ms,H as hs,I as gs,It as _s,J as vs,K as ys,L as bs,Lt as xs,M as Ss,Mt as Cs,N as ws,Nt as Ts,O as Es,Ot as Ds,P as Os,Pt as ks,Q as As,R as js,Rt as Ms,S as Ns,St as Ps,T as Fs,U as Is,W as Ls,X as Rs,Y as zs,Z as Bs,a as Vs,at as Hs,b as Us,c as Ws,d as Gs,dt as Ks,et as qs,f as Js,ft as Ys,g as Xs,h as Zs,i as Qs,it as $s,j as ec,jt as tc,kt as nc,lt as rc,m as ic,n as ac,nt as oc,o as sc,p as cc,pt as lc,q as uc,s as dc,st as fc,t as pc,ut as mc,w as hc,x as gc,xt as _c,y as vc,z as yc,zt as bc}from"./index-mqc2mWUR.js";import{t as xc}from"./Hint-3TTi0MgX.js";import{t as Sc}from"./AuditHistoryPanel-BG-n1i8c.js";import{a as Cc,i as wc,l as Tc,n as Ec,o as Dc,r as Oc,t as kc,u as Ac}from"./service-BQjBdN4O.js";import{a as jc,c as Mc,s as Nc,t as Pc}from"./server-traffic-Djnh_9f0.js";import{i as Fc,n as Ic,r as Lc}from"./agent-trust-copy-BIXDMtBm.js";import{t as Rc}from"./ServerTrafficSection-CvISj5pf.js";function zc(e){return e.split(/[?#]/)[0]||`/`}var Bc=1e6;function Vc(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/Bc);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(b(),1),Hc={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 Uc(e,t){return e!==`viewer`||t!==null}function Wc(e,t){return e===`research`&&!t?`tracked`:e}function Gc(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 Kc(e,t){return e.find(e=>e.kind===t.measurementScope&&(e.kind===`project`||e.id===t.measurementScopeKey))}function qc(e){return e.measurementScope!==`project`||e.marketKey!==void 0}function Jc(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=L();function Yc({state:e,label:t,className:n}){return(0,Q.jsx)(Y,{tone:cs(e),className:n,children:t??(e===`not-measured`?ei.label:$r(e))})}function Xc({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 Zc=[{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],Qc={"non-brand":`Non-brand`,branded:`Branded`,pooled:`All queries`},$c={"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.`},el=`Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.`;function tl(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:$e(e.score,Lt.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 nl({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:el})]}),(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:$e(e.share)})]},e.label))})]})}function rl({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=tl(u,{hasCompetitors:n.length>0,unavailable:e.unavailable===!0,noRun:e.breakdown.snapshotsTotal===0&&e.branded.snapshotsTotal===0,otherClassHasData:d.snapshotsTotal>0}),p=ii(f.headline),m=l===`non-brand`?_c[e.tone]:`text-secondary`;function h(e){let t=Zc.findIndex(e=>e.value===c),n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%Zc.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+Zc.length)%Zc.length:e.key===`Home`?n=0:e.key===`End`&&(n=Zc.length-1),n!==null&&(e.preventDefault(),i(Zc[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:$c[l]})]}),s?(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":a,className:`segmented flex-wrap`,onKeyDown:h,children:Zc.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:Qc[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:Qc[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)(nl,{breakdown:u,projectLabel:t})]})}function il({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 al=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],ol={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,all:`all checks`},sl={"non-brand":`Non-brand`,branded:`Branded`,all:`All queries`},cl={"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.`},ll={"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`},ul=`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.`,dl=100;function fl(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 ml(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 hl(e,t,n){return e===1?t:n}function gl(e){let t=e.label.trim(),n=lt(e.domain);return t&&t.toLowerCase()!==e.domain.toLowerCase()&&t.toLowerCase()!==n.toLowerCase()?t:null}function _l({row:e,aliases:t=[],autoAliases:n=[]}){let r=gl(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 vl(e){let t=gl(e);return t?`${t} (${e.domain})`:e.domain}function yl(e,t){return t&&e>=dl?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:e})}function bl({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)(J,{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 xl({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 Sl({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 Cl({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}=ii($e(e,Lt.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 wl({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)(_l,{row:e})}),(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:ml(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Sl,{count:e.mentionCount,of:n,state:t,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Sl,{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)(xl,{urls:e.sampleUrls}):null,i?(0,Q.jsx)(bl,{action:`pin`,domain:e.domain,mutation:i}):null]})})]},e.domain))})]})})}function Tl({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)(J,{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 El({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=fl(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?_c[Ps(t.project.shareOfVoice)]:`text-primary`,M=e=>_?e.pinned?l?(0,Q.jsx)(bl,{action:`unpin`,domain:e.domain,mutation:l}):null:c?(0,Q.jsx)(bl,{action:`pin`,domain:e.domain,mutation:c}):null:null,N=w.some(e=>M(e)!==null),P=[m,E?sl[E]:null,ol[e],t?.basis?C?`observed competitors only`:`tracked competitors only`:null].filter(Boolean).join(` · `),F=[];if(t&&!C&&w.length===0&&F.push({key:`no-pins`,text:`No pinned competitors.`}),t?.reason&&F.push({key:`reason`,text:`Mention share: ${ll[t.reason]}`}),t&&T.length>0){let e=T.length;F.push({key:`others`,text:O&&e>=dl?`${dl} or more other competitors seen`:`${e} other ${hl(e,`competitor`,`competitors`)} seen`})}D>0&&F.push({key:`pending`,text:`${t?.scope.kind===`all-markets`?`Pending publication across markets`:`Pending publication`}: ${D} ${hl(D,`competitor`,`competitors`)}`});let I=[x&&x.missingAnswerTextResults>0?`Answer data incomplete`:null,x&&x.incompleteSourceResults>0?`Citation data incomplete`:null].filter(Boolean);I.length>0&&F.push({key:`incomplete`,text:I.join(` · `),className:_c.caution});let L=[];if(t&&x){L.push(t.runCount===void 0?(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,hl(x.answeredResults,`answer`,`answers`)]}):(0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:t.runCount}),` `,hl(t.runCount,`check`,`checks`),`, `,(0,Q.jsx)(`strong`,{children:x.answeredResults}),` `,hl(x.answeredResults,`answer`,`answers`)]})),!t.reason&&S===`measured`&&t.project.shareOfVoice!==null&&L.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`]})),L.push((0,Q.jsxs)(Q.Fragment,{children:[`Answers with source links: `,(0,Q.jsx)(`strong`,{children:x.sourceResults})]})),T.length===0&&L.push(`Other competitors seen: none`),x.missingAnswerTextResults>0&&L.push((0,Q.jsxs)(Q.Fragment,{children:[`No answer text: `,(0,Q.jsx)(`strong`,{children:x.missingAnswerTextResults}),` `,hl(x.missingAnswerTextResults,`answer`,`answers`),`, left out of mention share`]})),x.incompleteSourceResults>0&&L.push((0,Q.jsxs)(Q.Fragment,{children:[`Incomplete source lists: `,(0,Q.jsx)(`strong`,{children:x.incompleteSourceResults}),` `,hl(x.incompleteSourceResults,`answer`,`answers`),`, not counted as misses`]}));let e=x.excludedProbeResults+x.excludedNonCompletedResults;e>0&&L.push((0,Q.jsxs)(Q.Fragment,{children:[`Left out: `,(0,Q.jsx)(`strong`,{children:e}),` `,hl(e,`answer`,`answers`),` from spot checks or unfinished checks`]}))}let R=[...t?[{name:`You`,row:t.project}]:[],...w.map(e=>({name:e.domain,row:e}))].filter(e=>e.row.sampleUrls.length>0);S===`measured`&&R.length>0&&L.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:R.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&&L.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other competitors seen: `,yl(T.length,O)]}),(0,Q.jsx)(`div`,{className:`av-subdetails-body`,children:(0,Q.jsx)(wl,{rows:T,state:S,named:k,cited:A,onPin:_?c:void 0})})]}));let z=t?.observedNames??[];if(z.length>0){let e=t?.observedNamesTotal??z.length;L.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Company names in answers: `,e>z.length?(0,Q.jsxs)(Q.Fragment,{children:[`top `,(0,Q.jsx)(`strong`,{children:z.length}),` of `,(0,Q.jsx)(`strong`,{children:e})]}):(0,Q.jsx)(`strong`,{children:z.length})]}),(0,Q.jsx)(`ul`,{className:`av-subdetails-body`,children:z.map(e=>(0,Q.jsxs)(`li`,{children:[e.name,` · `,e.answerCount,` `,hl(e.answerCount,`answer`,`answers`)]},e.name))})]}))}return b.length>0&&L.push((0,Q.jsxs)(`details`,{className:`av-subdetails`,children:[(0,Q.jsxs)(`summary`,{children:[`Other sites cited: `,yl(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:[vl(e),` · `,ml(e.surfaceClass),` · `,e.citationCount,` `,hl(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?`${cl[E]} ${ul}`:ul})]}),(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)(nc,{label:`Competitors over time window`,className:`flex-wrap`,options:al,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)(J,{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)(Cl,{percent:t.project.shareOfVoice,state:S,toneClass:j})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Sl,{count:t.project.mentionCount,of:k,state:S,toneClass:j})}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(Sl,{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:ni(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)(_l,{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:ml(e.surfaceClass)}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Cl,{percent:e.shareOfVoice,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Sl,{count:e.mentionCount,of:k,state:S,toneClass:`text-primary`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Sl,{count:e.citationCount,of:A,state:S,toneClass:`text-primary`})}),N?(0,Q.jsx)(`td`,{className:`av-brand-actions`,children:M(e)}):null]},e.domain))]})]}):null,F.length>0?(0,Q.jsx)(`div`,{className:`space-y-1 text-label-13 text-secondary`,children:F.map(e=>(0,Q.jsx)(`p`,{className:e.className,children:e.text},e.key))}):null]}),(0,Q.jsx)(il,{items:L}),_&&u?(0,Q.jsx)(`div`,{className:`border-t border-subtle px-5 py-3`,children:(0,Q.jsx)(Tl,{onAddCompetitor:u})}):null]})}function Dl(e){return e.trim().toLocaleLowerCase().split(/\s+/).filter(Boolean)}function Ol(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 kl(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 Al({value:e,headLength:t,tailLength:n,className:r,title:i}){let a=kl(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 jl({rows:e,getSearchText:t,pageSize:n=25}){let[r,i]=(0,Z.useState)(``),[a,o]=(0,Z.useState)(1),s=(0,Z.useMemo)(()=>Dl(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 Ml({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=>{ot(e.target.value),t(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&ot(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)(w,{"aria-hidden":`true`,className:`size-3.5`})}):null]})}function Nl({page:e,pageSize:t=25,visibleRows:n,totalRows:i,hasNextPage:a,onPageChange:o,itemLabel:s=`rows`,className:c,disabled:l=!1}){if(n===0)return null;let u=(e-1)*t+1,f=u+n-1,p=i===void 0?void 0:Math.max(1,Math.ceil(i/t)),m=a??(p!==void 0&&e<p),h=e>1||m;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 ${c??``}`,children:[(0,Q.jsxs)(`p`,{className:`tabular-nums`,children:[u.toLocaleString(`en-US`),` to `,f.toLocaleString(`en-US`),i===void 0?`${m?`+`:``} ${s}`:` of ${i.toLocaleString(`en-US`)} ${s}`]}),h?(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>o(e-1),disabled:l||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)(r,{"aria-hidden":`true`,className:`size-3.5`}),`Previous`]}),(0,Q.jsx)(`span`,{className:`tabular-nums`,children:p===void 0?`Page ${e}`:`Page ${e} of ${p}`}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>o(e+1),disabled:l||!m,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)(d,{"aria-hidden":`true`,className:`size-3.5`})]})]}):null]})}function Pl({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":ei.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(`/`)?mr(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(`/`)?mr(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 Fl(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 Il(e){let t=e.filter(e=>e!==`pending`);if(t.length===0)return`pending`;let n=Ke(t.map(Ll));return n===Rn.cited?t.includes(`cited`)?`cited`:`emerging`:n===Rn[`not-cited`]?t.includes(`lost`)?`lost`:`not-cited`:`not-measured`}function Ll(e){switch(e){case`cited`:case`emerging`:return Rn.cited;case`not-cited`:case`lost`:return Rn[`not-cited`];case`not-measured`:return Rn[`not-measured`]}}var Rl=320;function zl(e){return e===`branded`?`Branded`:e===`non-brand`?`Non-brand`:`Unclassified`}function Bl(e){return e===`non-brand`?0:e===`branded`?1:2}function Vl(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 Hl(e){return e.phrase}function Ul(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 Wl(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 ei.label;case`lost`:return`Lost`;case`emerging`:return`Emerging`;case`pending`:return`Pending`}}function Gl(e,t){return e.map(e=>Kl(e,t))}function Kl(e,t){return t===`citations`?e:{...e,citationState:Ul(e,t),runHistory:e.runHistory.map(e=>({...e,citationState:Ul(e,t)}))}}function ql(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:ei.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 Jl(e){let t=Fl(Gl(e,`mentions`)),n=Fl(e);return[ql(t,`mentions`),ql(n,`citations`)]}function Yl({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 Xl({items:e}){return(0,Q.jsx)(`div`,{className:`query-evidence-signals`,"aria-label":`Latest run mention and citation signals`,children:Jl(e).map(e=>(0,Q.jsx)(Yl,{signal:e},e.key))})}function Zl({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)(Ss,{}),t]})}):null,e?(0,Q.jsx)(ws,{queryClass:e,manage:!!t}):null]})}function Ql({evidence:e,compareLocations:t=!1,defaultDensity:n=`detailed`,providerSelection:r,onProviderSelectionChange:i,addedQueries:a=[],actions:o,actionPanel:s}){let{openEvidence:c}=oc(),l=(0,Z.useId)(),[u,f]=(0,Z.useState)(new Set),p=gs(),[m,h]=(0,Z.useState)(`mentions`),[g,_]=(0,Z.useState)(n),[v,y]=(0,Z.useState)(`all`),[b,x]=(0,Z.useState)(``),S=r??b,C=e=>{x(e),i?.(e)},w=(0,Z.useMemo)(()=>[...new Set([...e.map(e=>e.provider).filter(Boolean),...S?[S]:[]])].sort(),[e,S]),T=(0,Z.useMemo)(()=>{let n=new Map;for(let r of e){if(S&&r.provider!==S)continue;let e=r.query,i=r.queryClass??null,a=t?r.location??null:null,o=JSON.stringify([e,i,a]),s=n.get(o)??{key:o,phrase:e,queryClass:i,location:a,items:[],rawItems:[]};s.items.push(Kl(r,m)),s.rawItems.push(r),n.set(o,s)}return[...n.values()].sort((e,t)=>Bl(e.queryClass)-Bl(t.queryClass))},[e,m,t,S]),E=jl({rows:(0,Z.useMemo)(()=>T.filter(e=>v===`all`||(v===`unclassified`?e.queryClass===null:e.queryClass===v)),[T,v]),getSearchText:Hl}),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(st)),[a]),k=p?6:5,A=E.rows.map(e=>e.key),j=A.length>0&&A.every(e=>u.has(e)),M=e=>{f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},N=m===`mentions`?`mentioned`:`cited`,P=m===`mentions`?`Mention History`:`Citation History`,F=m===`mentions`?`mentioned`:`cited`;return(0,Q.jsxs)(`div`,{className:`query-evidence`,children:[(0,Q.jsx)(Zl,{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":m===e,tabIndex:m===e?0:-1,onClick:()=>h(e),onKeyDown:t=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t.key))return;t.preventDefault();let n=t.key===`Home`?`mentions`:t.key===`End`||e===`mentions`?`citations`:`mentions`;h(n),document.getElementById(`${l}-${n}`)?.focus()},children:e===`mentions`?`Mentions`:`Citations`},e))}),(0,Q.jsx)(X,{text:`Mentions track your brand or domain in answer text. Citations track your domain in source links. Each signal is measured independently.`})]}),(0,Q.jsxs)(`div`,{className:`query-evidence-display-controls`,children:[(0,Q.jsxs)(`label`,{className:`query-evidence-preview-toggle`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:g===`detailed`,onChange:e=>_(e.target.checked?`detailed`:`compact`)}),`Show answer previews`]}),(0,Q.jsx)(J,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:A.length===0,onClick:()=>{f(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)(Ml,{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:fr(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}-${m}`,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`}),p&&(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`})})]})}),Vl(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:[zl(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),f=A.indexOf(e),h=`${l}-query-${f}`,_=O.has(st(n)),v=Il(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=Fl(a),S=a.filter(e=>e.citationState===Rn.cited||e.citationState===`emerging`).length,C=m===`citations`?a.filter(e=>e.citationState===`not-measured`).length:0,w=a.length-C,T=`${S} of ${w} engines ${F}${C>0?`, ${C} not measured`:``}`;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`query-evidence-row`,onClick:()=>M(e),children:[(0,Q.jsx)(`td`,{className:`evidence-query-cell`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`query-evidence-query`,"aria-label":n,"aria-describedby":h,"aria-expanded":s,onClick:t=>{t.stopPropagation(),M(e)},children:[(0,Q.jsx)(d,{size:16,"aria-hidden":`true`,className:s?`rotate-90`:``}),(0,Q.jsxs)(`span`,{className:`min-w-0`,children:[(0,Q.jsx)(`span`,{children:n}),(0,Q.jsxs)(`span`,{id:h,className:`query-evidence-meta`,children:[(0,Q.jsx)(`span`,{children:zl(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)(Yc,{state:v,label:Wl(v,m),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]})}),p&&(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Os,{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)(Pl,{history:x,signal:m})}),(0,Q.jsx)(`td`,{className:`evidence-change-cell`,children:_?(0,Q.jsx)(`span`,{className:`query-evidence-new`,children:`new query`}):(0,Q.jsx)(Xl,{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?fr(e.provider):`Awaiting engine`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Yc,{state:e.citationState,className:`rounded-none border-0 bg-transparent p-0 text-label-14`,label:Wl(e.citationState,m)})}),p&&(0,Q.jsx)(`td`,{children:(0,Q.jsx)(ec,{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)(Pl,{history:e.runHistory,signal:m})}),(0,Q.jsx)(`td`,{className:`evidence-change-cell`,children:_?null:(0,Q.jsx)(Xl,{items:[o[t]??e]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(J,{variant:`ghost`,className:`pointer-coarse:min-h-11`,type:`button`,title:`View ${e.provider?fr(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)(tu,{item:e,mode:m,onViewFull:()=>c(e.id)},m)})})]},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)(Nl,{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 $l(e){let t=(e.matchedTerms??[]).filter(e=>e.trim().length>2),n=lc(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 eu(e,t){let n=t.toLowerCase().replace(/^www\./,``);return(e.citedCompetitorDomains??[]).some(e=>e.toLowerCase().replace(/^www\./,``)===n)}function tu({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)(nu,{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:ei.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)(rc,{url:t.uri,title:t.title}),eu(e,Ce(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,eu(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)(J,{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)(nu,{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 nu({item:e,onViewFull:t,contextOnly:n=!1}){let{matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}=e,s=(0,Z.useMemo)(()=>$l({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>Rl;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)(Ks,{headingLevel:4,highlightGroups:s,previewLength:Rl,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,eu(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)(J,{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 ru({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&&Re(`window`),n(e)},children:i?i(e):e},e))})}var iu=[``,`sm:grid-cols-1`,`sm:grid-cols-2`,`sm:grid-cols-3`],au=[``,`lg:grid-cols-1`,`lg:grid-cols-2`,`lg:grid-cols-3`,`lg:grid-cols-4`,`lg:grid-cols-5`,`lg:grid-cols-6`],ou=14,su=li[1],cu={current:`current`,previous:`previous`},lu=e=>e.series?.filter(e=>e.current!==null).length??0,uu=e=>e.interactive??lu(e)>=2,du=e=>e!=null;function fu(e){return e.charAt(0).toLowerCase()+e.slice(1)}function pu(e){if(!e)return``;if(e.kind===`note`)return fu(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 mu({date:e,observedAt:t}){return t?Ci(hi(t)):Di(e)}function hu({date:e,observedAt:t}){return t?mi(hi(t)):Number(e.slice(0,4))}function gu(e){return e.label??mu(e)}function _u(e,t){if(!e)return;let n=`since ${gu(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`?`${yn(r).magnitude} pts`:r.toLocaleString(),direction:e.difference>0?`up`:`down`,tone:e.tone,basis:n}}function vu(e){let t=new Set(e.map(e=>e.change?gu(e.change.basis):null)),[n]=[...t];return t.size===1&&n?`since ${n}`:void 0}function yu(e){return e.series.map(e=>({date:e.observedAt??e.date,current:e.value,...e.label?{label:e.label}:{}}))}function bu(e,t){if(e.label&&t.label)return e.label===t.label?e.label:`${e.label} to ${t.label}`;let n=(e,t)=>t?`${mu(e)}, ${hu(e)}`:mu(e);return`${n(e,hu(e)!==hu(t))} to ${n(t,!0)}`}function xu({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`?D:v,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 Su({figure:e,active:t}){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:`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 Cu(e,t){return e.formatExact?.(t)??e.formatValue?.(t)??t.toLocaleString()}function wu({active:e,payload:t,figure:n,previousLabel:r,rowLabel:i}){let a=t?.[0]?.payload;if(!e||!a)return null;let o=e=>du(e)?Cu(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?yi(a.previousDate):r}),(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:o(a.previous)})]})]})}function Tu({name:e,groups:t,mode:n=`single`,selected:r,onSelect:i,span:a,cadence:o=`day`,instants:s=!1,currentLabel:c,previous:l,chart:u,legendExtra:d,controls:f,notice:p,emptyChartMessage:m,refreshing:h=!1,chartHeight:g=240,frame:_=`card`}){let v=(0,Z.useId)().replace(/:/g,``),b=e=>s?pi(hi(e)):yi(e),x=e=>e.label??b(e.date),S=e=>bi(hi(new Date(e).toISOString())),[C,w]=(0,Z.useState)(new Set),T=!Is(),E=t.flatMap(e=>e.figures),D=n===`single`?E.find(e=>e.key===r[0]&&uu(e)):void 0,O=D?.series??[],k=s?O.map(e=>({...e,at:Date.parse(e.date)})):O,A=new Map(O.flatMap(e=>e.label?[[e.date,e.label]]:[])),j=!!l?.available&&O.some(e=>du(e.previous)),M=O.some(e=>e.current!==null||j&&du(e.previous)),N=!j||!C.has(cu.current),P=j&&!C.has(cu.previous),F=lu(D??{key:``,label:``,value:``})<ou?`linear`:`monotone`,I=o===`day`?`per day`:o===`scan`?`per scan`:`per release`,L=D?`${D.label} ${I}, ${c?fu(c):a??``}${j?` and the previous period`:``}`:``,R=E.filter(uu).map(e=>e.key),z=R.includes(r[0]??``)?r[0]:R[0],B=e=>{i(e),document.getElementById(`${v}-tab-${e}`)?.focus()},ee=(e,t)=>{let n=R.indexOf(t),r=R.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(),B(R[i]))},te=e=>w(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),ne=(e,t,a)=>{let o=uu(e),s=o&&r.includes(e.key),c=!!t.basis,l=[`${e.label} ${e.spokenValue??e.value}${e.detail?` ${e.detail}`:``}`,pu(e.change)].filter(Boolean).join(`, `),u=(0,Q.jsxs)(`div`,{className:`flex min-h-5 items-center gap-1.5`,children:[n===`compare`&&o&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2.5 shrink-0 rounded-full`,style:{backgroundColor:s?e.color:`transparent`,border:`1.5px solid ${e.color}`}}),e.picker?(0,Q.jsxs)(`span`,{className:`relative inline-flex max-w-full items-center`,children:[(0,Q.jsx)(`select`,{"aria-label":e.picker.ariaLabel,value:e.picker.value,onChange:t=>e.picker.onChange(t.target.value),className:`max-w-full cursor-pointer appearance-none truncate rounded-sm bg-transparent py-0.5 pr-5 text-label-14-strong [field-sizing:content] transition-colors duration-150 hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${s?`text-link`:`text-secondary`}`,children:e.picker.options.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))}),(0,Q.jsx)(y,{"aria-hidden":`true`,className:`pointer-events-none absolute right-0 size-3.5 ${s?`text-link`:`text-muted`}`})]}):(0,Q.jsx)(`span`,{className:`text-label-14-strong ${s?n===`single`?`text-link`:`text-heading`:`text-secondary`}`,children:e.label}),e.help&&(0,Q.jsx)(X,{text:e.help})]});return a?(0,Q.jsxs)(`div`,{className:`relative flex min-w-0 flex-col px-4 pb-4 pt-3 transition-colors duration-150 ${s&&n===`single`?`bg-surface-active`:o?`hover:bg-surface-hover`:``}`,children:[n===`single`&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-x-0 top-0 h-[3px] bg-link transition-opacity duration-200 ${s?`opacity-100`:`opacity-0`}`}),u,(0,Q.jsxs)(`button`,{type:`button`,id:`${v}-tab-${e.key}`,...n===`single`?{role:`tab`,"aria-selected":s,"aria-controls":`${v}-panel`,"aria-disabled":!o||void 0,tabIndex:o&&e.key===z?0:-1,onKeyDown:t=>ee(t,e.key)}:{"aria-pressed":s},"aria-label":l,disabled:n===`compare`&&(e.disabled||!o),onClick:o?()=>i(e.key):void 0,className:`mt-auto block w-full rounded-sm pt-1 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${o?``:`cursor-default`} ${e.disabled?`disabled:cursor-not-allowed disabled:opacity-50`:``}`,children:[(0,Q.jsx)(Su,{figure:e,active:s}),(0,Q.jsx)(xu,{change:e.change,hideBasis:c})]})]},e.slot??e.key):(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-col px-4 pb-4 pt-3`,children:[(0,Q.jsx)(`dt`,{children:u}),(0,Q.jsxs)(`dd`,{className:`mt-auto pt-1`,children:[(0,Q.jsx)(Su,{figure:e,active:!1}),(0,Q.jsx)(xu,{change:e.change,hideBasis:c}),e.change&&(0,Q.jsx)(`span`,{className:`sr-only`,children:pu(e.change)})]})]},e.slot??e.key)};return(0,Q.jsxs)(`div`,{className:`${_===`card`?`overflow-hidden material-base`:`-mx-4`} transition-opacity duration-200 ${h?`opacity-60`:``}`,children:[(0,Q.jsx)(`div`,{className:`flex flex-col lg:flex-row`,children:t.map((t,r)=>{let i=t.figures.some(uu),a=`${v}-group-${t.key}`,o=`grid grid-cols-2 ${iu[Math.min(t.figures.length,3)]} ${au[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)&&(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&&(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=>ne(e,t,!0))}):(0,Q.jsx)(`dl`,{className:o,children:t.figures.map(e=>ne(e,t,!1))})]},t.key)})}),(0,Q.jsxs)(`div`,{id:`${v}-panel`,...n===`single`&&D?{role:`tabpanel`,"aria-labelledby":`${v}-tab-${D.key}`}:{role:`region`,"aria-label":`${e} chart`},className:`border-t border-default px-4 pb-3 pt-4`,children:[p&&(0,Q.jsx)(`div`,{className:`mb-3 text-copy-14 text-secondary`,children:p}),n===`compare`?u:!D||!M?(0,Q.jsx)(`p`,{className:`px-4 py-4 text-copy-13 text-secondary`,children:m}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{role:`img`,"aria-label":L,style:{height:g},children:(0,Q.jsx)(ce,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(pe,{data:[...k],margin:{top:8,right:0,bottom:0,left:4},children:[(0,Q.jsx)(ie,{stroke:wi,vertical:!1}),s?(0,Q.jsx)(oe,{dataKey:`at`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:S,minTickGap:32,padding:{left:12,right:12}}):(0,Q.jsx)(oe,{dataKey:`date`,tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:e=>A.get(e)??fi(e),minTickGap:32,padding:A.size>0?{left:40,right:40}:{left:12,right:12}}),(0,Q.jsx)(de,{orientation:`right`,tick:xi,tickLine:!1,axisLine:!1,width:52,allowDecimals:D.allowDecimals??!1,tickFormatter:e=>D.formatValue?.(e)??e.toLocaleString()}),(0,Q.jsx)(ae,{cursor:{stroke:gi.textFaint,strokeWidth:1},wrapperStyle:{outline:`none`},content:(0,Q.jsx)(wu,{figure:D,previousLabel:j?l?.label:void 0,rowLabel:x})}),P&&(0,Q.jsx)(fe,{type:F,dataKey:cu.previous,stroke:su,strokeOpacity:.65,strokeWidth:1.5,strokeDasharray:`4 4`,dot:!1,activeDot:{r:3,strokeWidth:0,fill:su},connectNulls:!1,isAnimationActive:T,animationDuration:320,animationEasing:`ease-out`}),N&&(0,Q.jsx)(fe,{type:F,dataKey:cu.current,stroke:su,strokeWidth:2.25,dot:F===`linear`&&{r:3,strokeWidth:0,fill:su},activeDot:{r:5,strokeWidth:2,stroke:su,fill:`var(--color-bg)`},connectNulls:!1,isAnimationActive:T,animationDuration:320,animationEasing:`ease-out`})]})})}),(0,Q.jsx)(`div`,{className:`sr-only`,children:(0,Q.jsxs)(`table`,{children:[(0,Q.jsx)(`caption`,{children:L}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:O.some(e=>e.label)?`Release`:`Date`}),(0,Q.jsx)(`th`,{scope:`col`,children:D.label}),j&&(0,Q.jsx)(`th`,{scope:`col`,children:l.label})]})}),(0,Q.jsx)(`tbody`,{children:O.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:x(e)}),(0,Q.jsx)(`td`,{children:e.current===null?`Not recorded`:Cu(D,e.current)}),j&&(0,Q.jsx)(`td`,{children:du(e.previous)?Cu(D,e.previous):`No data`})]},e.date))})]})})]}),n===`single`&&D&&M&&c||d||a||f?(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center justify-between gap-x-6 gap-y-1`,children:[(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:D?`${D.label} series`:`${e} options`}),n===`single`&&D&&M&&c&&l&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Eu,{label:c,checked:N,disabled:!j||N&&!P,onChange:()=>te(cu.current),dash:void 0}),(0,Q.jsx)(Eu,{label:j?l.label:`${l.label}: no earlier data`,checked:P,disabled:!j||P&&!N,onChange:()=>te(cu.previous),dash:`4 3`})]}),d]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[a&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:a}),f]})]}):null]})]})}function Eu({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:su,strokeWidth:i?1.5:2.5,strokeDasharray:i})}),e]})}var Du=`baseline`;function Ou(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,[Du]:i.get(e)??null};for(let e of n)a[e.dataKey]=t?.[e.key]??0;return a}),series:n}}var ku=`text-label-12-strong normal-case text-muted`;function Au({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 ju({children:e}){return(0,Q.jsx)(`div`,{className:`[&>details:first-child]:border-t-0`,children:e})}function Mu({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 Nu={3:`lg:grid-cols-3`,4:`lg:grid-cols-4`,5:`lg:grid-cols-5`};function Pu({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 ${Nu[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 Fu({label:e,sortKey:t,current:n,dir:r,onSort:i,align:a}){let o=n===t;return(0,Q.jsx)(`th`,{className:`py-2 ${a===`right`?`pl-4 text-right`:`text-left`}`,"aria-sort":o?r===`asc`?`ascending`:`descending`:void 0,children:(0,Q.jsxs)(`button`,{type:`button`,className:`${ku} 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,o&&(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`ml-0.5`,children:r===`asc`?`↑`:`↓`})]})})}function Iu({label:e,align:t}){return(0,Q.jsx)(`th`,{className:`py-2 ${t===`right`?`pl-4 text-right`:`text-left`}`,children:(0,Q.jsx)(`span`,{className:ku,children:e})})}function Lu(e,t,n=`desc`){return e.key===t?{key:t,dir:e.dir===`desc`?`asc`:`desc`}:{key:t,dir:n}}function Ru(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 zu({groups:e,groupLabel:t,caption:n,childColumns:r,childRowKey:i,renderChildCells:a,pinLast:o}){let s=(0,Z.useId)(),[c,l]=(0,Z.useState)(new Set),[u,f]=(0,Z.useState)({key:`sessions`,dir:`desc`}),p=(0,Z.useMemo)(()=>{let t=Ru(u.key,u.dir);return[...e].sort((e,n)=>Number(o?.(e)??!1)-Number(o?.(n)??!1)||t(e,n))},[e,u,o]),m=e=>f(t=>Lu(t,e,e===`label`?`asc`:`desc`)),h=e=>l(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 min-w-[36rem] text-label-14`,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)(Fu,{label:t,sortKey:`label`,current:u.key,dir:u.dir,onSort:m,align:`left`}),(0,Q.jsx)(Fu,{label:`Sessions`,sortKey:`sessions`,current:u.key,dir:u.dir,onSort:m,align:`right`}),(0,Q.jsx)(Fu,{label:`Organic`,sortKey:`organicSessions`,current:u.key,dir:u.dir,onSort:m,align:`right`}),(0,Q.jsx)(Fu,{label:`Paid`,sortKey:`paidSessions`,current:u.key,dir:u.dir,onSort:m,align:`right`}),(0,Q.jsx)(Iu,{label:`Share`,align:`right`})]})}),(0,Q.jsx)(`tbody`,{children:p.map((e,t)=>{let n=c.has(e.label),o=`${s}-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?o:void 0,onClick:()=>h(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)(y,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-secondary`}):(0,Q.jsx)(d,{"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:$e(e.share)})]}),n&&(0,Q.jsx)(`tr`,{id:o,children:(0,Q.jsx)(`td`,{colSpan:5,className:`pb-3 pl-6`,children:(0,Q.jsx)(`div`,{className:`overflow-x-auto material-base px-3 pb-1`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[32rem] text-label-13`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`${e.label} sources`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsx)(`tr`,{children:r.map(e=>(0,Q.jsx)(Iu,{label:e.label,align:e.align},e.label))})}),(0,Q.jsx)(`tbody`,{children:e.sources.map(e=>(0,Q.jsx)(`tr`,{className:`border-t border-subtle`,children:a(e)},i(e)))})]})})})})]},e.label)})})]})})}function Bu(e,t){return e===`other`?gi.textDim:li[t%li.length]}function Vu({input:e,baseline:t,baselineLabel:n,label:r,height:i=224}){let{rows:a,series:o}=(0,Z.useMemo)(()=>Ou(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)(ce,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(pe,{data:a,margin:{top:4,right:4,bottom:0,left:0},children:[(0,Q.jsx)(ie,{stroke:wi,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`date`,tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:fi,minTickGap:24}),(0,Q.jsx)(de,{tick:xi,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(ae,{...Ti,labelFormatter:yi,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=Bu(e.key,o.indexOf(e));return(0,Q.jsx)(le,{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)(fe,{type:`monotone`,dataKey:`baseline`,name:`baseline`,stroke:gi.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:Bu(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:gi.textFaint,strokeWidth:`2`,strokeDasharray:`5 3`})}),n]})]})]})}var Hu=[`sessions`,`activeUsers`,`organicSessions`,`engagementRate`,`keyEvents`],Uu=`canonry.siteTraffic.slots`;function Wu(e){return typeof e==`string`&&xt.some(t=>t===e)}function Gu(){try{let e=JSON.parse(window.localStorage.getItem(Uu)??`null`);if(Array.isArray(e)&&e.length===Hu.length&&e.every(Wu))return[...e]}catch{}return[...Hu]}function Ku(e){try{window.localStorage.setItem(Uu,JSON.stringify(e))}catch{}}function qu(e,t,n){let r=it(e,t);return r===null||t===null?{kind:`note`,text:`No earlier data`}:{kind:`delta`,amount:$e(Math.abs(t),Lt.percent),direction:t>0?`up`:t<0?`down`:`flat`,tone:r===Et.better?`better`:r===Et.worse?`worse`:`neutral`,basis:n}}function Ju({overview:e,refreshing:t=!1}){let[n,r]=(0,Z.useState)(Gu),[i,a]=(0,Z.useState)(0),o=qn(e.window)?He[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,Ku(r),r}),u=n.map((t,n)=>({key:t,slot:`slot-${n}`,label:ht[t].label,value:At(t,e.totals[t],{compact:!0}),exactValue:At(t,e.totals[t]),change:qu(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:xt.map(e=>({value:e,label:ht[e].label})),onChange:e=>{Wu(e)&&l(n,e)}},formatValue:e=>At(t,e,{compact:!0}),formatExact:e=>At(t,e),allowDecimals:ht[t].unit!==Tt.count})),d=n[i]??Hu[0],f=e.current.startDate&&e.current.endDate&&e.previous.startDate&&e.previous.endDate?`${Yu(e.current.startDate,e.current.endDate,!0)} vs ${Yu(e.previous.startDate,e.previous.endDate,!1)}`:void 0;return(0,Q.jsx)(Tu,{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 ${ht[d].label.toLowerCase()} yet.`,refreshing:t})}function Yu(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 Xu(e){return e?yi(e.slice(0,10)):`—`}function Zu({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 Qu({rows:e,expanded:t,loading:n,onToggle:r,actions:i,lastReadLabel:a,empty:o}){let s=i?6:5,c=(e,a)=>{let o=t.has(e.url),s=n?.has(e.url)??!1;return(0,Q.jsxs)(`tr`,{className:`group`,children:[(0,Q.jsx)(`td`,{className:`max-w-md ${a?`pl-9`:``}`,children:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[e.isIndex&&!a&&(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":o,"aria-label":`${o?`Hide`:`Show`} the sitemaps in ${e.label}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>r(e.url),children:o?(0,Q.jsx)(y,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,Q.jsx)(Al,{value:e.label,title:e.url,className:`font-mono text-label-13 text-neutral`}),e.isIndex&&(0,Q.jsx)(`span`,{className:`shrink-0 text-label-12 text-secondary`,children:s?`Loading…`:e.files?`Index · ${e.files.length} ${e.files.length===1?`sitemap`:`sitemaps`}`:`Index`}),e.kind&&(0,Q.jsx)(`span`,{className:`shrink-0 text-label-12 text-secondary`,children:e.kind}),e.isDefault&&(0,Q.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 text-label-12 text-secondary`,children:[`Default`,(0,Q.jsx)(X,{text:`Canonry uses this sitemap when a command names none.`})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5 whitespace-nowrap`,children:[(0,Q.jsx)(Y,{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?Xu(e.submittedAt):a?(0,Q.jsx)(`span`,{title:`Submitted through its sitemap index.`,children:`Via index`}):(0,Q.jsx)(`span`,{title:`Nobody submitted it: the engine found it on its own.`,children:`Not submitted`})}),(0,Q.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:e.missing?`—`:e.lastReadAt?Xu(e.lastReadAt):`Not yet`}),i&&(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(`div`,{className:`flex justify-end gap-0.5 whitespace-nowrap ${e.missing?``:`opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100`}`,children:i(e,a)})})]},`${a?.url??``}|${e.url}`)};return(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Sitemap`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Status`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`URLs`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Submitted`}),(0,Q.jsx)(`th`,{className:`text-left`,children:a}),i&&(0,Q.jsx)(`th`,{className:`text-right`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,Q.jsxs)(`tbody`,{children:[e.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:s,className:`py-6 text-center text-secondary`,children:o})}),e.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[c(e,null),e.isIndex&&t.has(e.url)&&(e.files??[]).map(t=>c(t,e))]},e.url))]})]})})}var $u=10,ed={ok:`positive`,pending:`neutral`,warnings:`caution`,errors:`negative`,other:`neutral`},td={site:`on your site`,google:`in Google`,bing:`in Bing`};function nd(e){return e.map(e=>td[e]).join(` and `)}function rd(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 id(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:ed[t.state],detail:rd(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:nd(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=jl({rows:[...g,..._],getSearchText:e=>`${e.url} ${e.files?.map(e=>e.url).join(` `)??``}`,pageSize:$u});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)(rs,{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 `,vi(n.syncedAt)]}),!e.readOnly&&(e.canSubmit?(0,Q.jsx)(J,{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)(J,{type:`submit`,size:`sm`,disabled:e.submitting||!o.trim(),children:e.submitting?`Submitting…`:`Submit to ${t}`}),(0,Q.jsx)(J,{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)(Ml,{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)(Qu,{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)(Zu,{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)(Zu,{disabled:!e.canSubmit||e.submitting,onClick:()=>void y([n.url]),children:n.submittedAt?`Resubmit`:`Submit`}),e.onInspect&&(0,Q.jsx)(Zu,{disabled:e.inspecting,onClick:()=>e.onInspect(n.url),children:`Inspect URLs`}),e.onSetDefault&&!n.isDefault&&(0,Q.jsx)(Zu,{disabled:e.settingDefault,title:`Canonry uses this sitemap when a command names none.`,onClick:()=>e.onSetDefault(n.url),children:`Set as default`})]})}),v.totalRows>$u&&(0,Q.jsx)(Nl,{page:v.page,pageSize:$u,visibleRows:v.rows.length,totalRows:v.totalRows,onPageChange:v.setPage,itemLabel:`sitemaps`})]})]})}function ad({label:e,items:t,disabled:n=!1,menuLabel:r}){let[i,a]=(0,Z.useState)(!1),o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useId)();return(0,Z.useEffect)(()=>{if(!i)return;o.current?.querySelector(`[role="menuitem"]:not([disabled])`)?.focus();let e=e=>{o.current&&!o.current.contains(e.target)&&a(!1)},t=e=>{e.key===`Escape`&&(a(!1),s.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[i]),(0,Q.jsxs)(`div`,{className:`relative inline-flex`,ref:o,children:[(0,Q.jsxs)(J,{ref:s,type:`button`,variant:`outline`,size:`sm`,disabled:n,"aria-haspopup":`menu`,"aria-expanded":i,"aria-controls":i?c:void 0,onClick:()=>a(e=>!e),children:[e,(0,Q.jsx)(y,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),i&&(0,Q.jsx)(`div`,{id:c,role:`menu`,"aria-label":r,className:`project-subnav-menu min-w-[16rem]`,onKeyDown:e=>{let t=[...e.currentTarget.querySelectorAll(`[role="menuitem"]:not([disabled])`)],n=t.indexOf(document.activeElement),r=e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:null;r!==null&&(e.preventDefault(),t[r]?.focus())},onBlur:e=>{o.current?.contains(e.relatedTarget)||a(!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:()=>{a(!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 sd=`Search Console is not connected yet. Your Canonry team can set this up.`,cd=[`7d`,`30d`,`90d`,`all`],ld=500,ud=[{key:`clicks`,label:`Clicks`,color:li[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:li[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Si.caution,format:e=>$e(e)},{key:`position`,label:`Avg position`,color:li[2],inverted:!0,format:e=>e.toFixed(1)}],dd=25,fd=`canonry:google-oauth-complete`;function pd(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`?`${yn(Math.abs(o)).magnitude} pts`:ve(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:$e(Math.abs(s)),direction:s>0?`up`:`down`,tone:a(s>0),basis:i}}var md=[{key:`google-indexed`,engine:`google`,color:li[0]},{key:`bing-indexed`,engine:`bing`,color:li[6]}];function hd(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 gd(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 _d({projectName:e,refreshNonce:t}){let n=R(),{isAdmin:r}=ji(),i=tt(),[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=U({...io({client:q,path:{name:e},query:j?{surface:`index-coverage`,...j}:{surface:`index-coverage`,window:k}}),staleTime:Fi,placeholderData:z}),[P,F]=(0,Z.useState)([`clicks`,`impressions`]),[I,L]=(0,Z.useState)(!0),[B,ee]=(0,Z.useState)(null),[te,ne]=(0,Z.useState)(0),[V,re]=(0,Z.useState)({startDate:``,endDate:``,query:``,page:``}),[ie,ae]=(0,Z.useState)(0),[oe,se]=(0,Z.useState)(!1),[ce,le]=(0,Z.useState)(0),[ue,de]=(0,Z.useState)(!1),[fe,pe]=(0,Z.useState)(``),[me,he]=(0,Z.useState)(!0),[ge,_e]=(0,Z.useState)(!1),[ve,ye]=(0,Z.useState)(!1),[be,xe]=(0,Z.useState)(!1),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(!1),[Ee,De]=(0,Z.useState)(!1),[W,ke]=(0,Z.useState)(null),[Ae,G]=(0,Z.useState)(!1),[je,Me]=(0,Z.useState)(null),[Ne,Pe]=(0,Z.useState)(!1),[Fe,Ie]=(0,Z.useState)(!1),[Le,Re]=(0,Z.useState)(!1),[ze,Ve]=(0,Z.useState)(!1),[He,We]=(0,Z.useState)(`indexed`),Ge=(0,Z.useId)(),[Ke,qe]=(0,Z.useState)(null),Je=!!(V.query.trim()||V.page.trim()||Ke),Ye=Ke!==null,Xe=(0,Z.useMemo)(()=>{if(!Ke)return d;let{key:e,dir:t}=Ke;return[...d].sort((n,r)=>{let i=e===ui.CTR?Number.isFinite(n.ctr)?n.ctr:0:n[e],a=e===ui.CTR?Number.isFinite(r.ctr)?r.ctr:0:r[e];return t===`asc`?i-a:a-i})},[d,Ke]),Ze=jl({rows:Xe,pageSize:25}),Qe=ue?Ze.rows:Xe,[et,nt]=(0,Z.useState)([]),[rt,K]=(0,Z.useState)(null),[it,at]=(0,Z.useState)(1),ot=(0,Z.useMemo)(()=>{if(et.length<2)return null;let e=et[et.length-1],t=et[et.length-2];return{indexed:e.indexed-t.indexed,notIndexed:e.notIndexed-t.notIndexed}},[et]);(0,Z.useEffect)(()=>{at(1)},[W,He,rt]);let st=(0,Z.useMemo)(()=>rt?(W?.reasonGroups??[]).find(e=>e.reason===rt):void 0,[W,rt]),ct=(0,Z.useMemo)(()=>W?He===`indexed`?W.indexed:He===`deindexed`?W.deindexed:He===`notIndexed`?rt?st?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,He,rt,st]),lt=Math.max(1,Math.ceil(ct.length/dd)),ut=Math.min(Math.max(1,it),lt),dt=(ut-1)*dd,ft=(0,Z.useMemo)(()=>W?.indexed.slice(dt,dt+dd)??[],[W,dt]),pt=(0,Z.useMemo)(()=>W?.notIndexed.slice(dt,dt+dd)??[],[W,dt]),mt=(0,Z.useMemo)(()=>W?.deindexed.slice(dt,dt+dd)??[],[W,dt]),ht=(0,Z.useMemo)(()=>(st?.urls??[]).slice(dt,dt+dd),[st,dt]),[_t,vt]=(0,Z.useState)(!1),[yt,bt]=(0,Z.useState)(null),[xt,St]=(0,Z.useState)(null),[wt,Tt]=(0,Z.useState)(null),[Et,Dt]=(0,Z.useState)(null);function kt(e,t){let n=us(e),r=od(n);r?(St(r),bt(null)):(St(null),bt(n.message||t))}let At=s.find(e=>e.connectionType===`gsc`),jt=(At?.scopes??[]).includes(`https://www.googleapis.com/auth/webmasters`),Mt=U({...Lo({client:q,path:{name:e}}),staleTime:Fi,enabled:!!At?.propertyId&&!i}),Nt=Mt.data?.google?.sitemaps??[],Pt=Nt.filter(e=>e.parentUrl===null),Ft=Pt.filter(e=>e.isIndex).map(e=>e.url),It=Ft.length>0?Ft:Pt.map(e=>e.url),Lt=Ft.length,Rt=Lt===1?`Resubmit sitemap index`:Lt>1?`Resubmit sitemap indexes`:`Resubmit all sitemaps`,zt=d.length>0||h.length>0||_.length>0,Bt=Qs(),Vt=Vs();async function Ht(t,r=!1){if(i)u([]);else if(!t)u([]),S(``);else{ye(!0);try{let{sites:i}=await n.fetchQuery({...Bo({client:q,path:{name:e}}),staleTime:r?0:Fi});u(i),S(t.propertyId??i[0]?.siteUrl??``),St(null)}catch(e){u([]),kt(e,`Failed to load Search Console properties`)}finally{ye(!1)}}}async function Ut(t){Ce(!0);let r=t??ie;try{let t=Je?ld:25,i=Je?0:r,a={limit:String(t)};V.startDate&&(a.startDate=V.startDate),V.endDate&&(a.endDate=V.endDate),V.query&&(a.query=V.query),V.page&&(a.page=V.page),i>0&&(a.offset=String(i)),k&&k!==`all`&&!V.startDate&&(a.window=k);let o=await n.fetchQuery({...Ao({client:q,path:{name:e},query:a}),staleTime:Fi}),s=o.rows;Je?(se(!1),f(s),le(s.length),de(!0)):(se(i+s.length<o.totalMatching),f(s),le(0),de(!1))}catch(e){f([]),se(!1),le(0),bt(e instanceof Error?e.message:`Failed to load GSC performance data`)}finally{Ce(!1)}}async function Wt(){try{let t={};V.startDate&&(t.startDate=V.startDate),V.endDate&&(t.endDate=V.endDate),k&&k!==`all`&&!V.startDate&&(t.window=k);let r=await n.fetchQuery({...$a({client:q,path:{name:e},query:t}),staleTime:Fi});m(r),M(t.startDate||t.endDate?{...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{}}:null)}catch{m(null)}}async function Gt(t=!1){Te(!0);try{let r=fe.trim()||void 0,i={limit:`20`};r&&(i.url=r);let[a,o]=await Promise.all([n.fetchQuery({..._o({client:q,path:{name:e},query:i}),staleTime:t?0:Fi}),n.fetchQuery({...Ro({client:q,path:{name:e}}),staleTime:t?0:Fi})]);g(a),v(o)}catch(e){g([]),v([]),bt(e instanceof Error?e.message:`Failed to load GSC inspection history`)}finally{Te(!1)}}async function Kt(t=!1){G(!0);try{let[r,i]=await Promise.all([n.fetchQuery({...Do({client:q,path:{name:e}}),staleTime:t?0:Fi}),n.fetchQuery({...Ho({client:q,path:{name:e}}),staleTime:t?0:Fi}).catch(()=>[])]);ke(r),nt(i)}catch(e){ke(null),nt([]),bt(e instanceof Error?e.message:`Failed to load coverage data`)}finally{G(!1)}}async function Jt(t){vt(!0),bt(null);try{let{succeeded:n,failed:r,total:i}=(await gt(e,{urls:t})).summary;Ni({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){bt(e instanceof Error?e.message:`Failed to request indexing`)}finally{vt(!1)}}async function Yt(){vt(!0),bt(null);try{let{succeeded:t,failed:n,total:r}=(await gt(e,{urls:[],allUnindexed:!0})).summary;Ni({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){bt(e instanceof Error?e.message:`Failed to request indexing`)}finally{vt(!1)}}async function Xt(t){let n=[];if(!jt||t.length===0)return n;let r=[...new Set(t)];Ie(!0),bt(null),Me({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 Wn(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,Me({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}`,bt(s),Ni({title:`Sitemap resubmission partially completed`,detail:f,tone:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`}),n}}let t=r.length;Ni({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){bt(e instanceof Error?e.message:`Failed to submit sitemap to Google`)}finally{Ie(!1),Me(null),s&&bt(s)}return n}async function Zt(){let e=Nt.filter(e=>!e.isIndex).map(e=>e.url),t=Ft.filter(e=>!Nt.some(t=>t.parentUrl===e));await Xt([...e,...t])}async function Qt(t){Pe(!0),bt(null);try{await Be(e,`gsc`,t),await Pi(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,sitemapUrl:t}:e)),Ni({title:`Default sitemap updated`,detail:t,tone:`positive`,dedupeKey:`gsc:sitemap-default:${e}`,dedupeMode:`replace`})}catch(e){bt(e instanceof Error?e.message:`Failed to set the default sitemap`)}finally{Pe(!1)}}async function en(t){try{await Vt.mutateAsync({projectName:e,projectLabel:e,opts:t?{sitemapUrl:t}:void 0})}catch{}}async function tn(){try{let t=(await n.fetchQuery({...ns({client:q,path:{name:e},query:{kind:Ct[`gsc-sync`],limit:1}}),staleTime:Fi}))[0];Dt(t?.status===Ot.failed&&t.error?`Last saved Search Console sync failed: ${qt(t.error)}`:null)}catch{Dt(`Saved Search Console sync status is unavailable.`)}}async function nn(){he(!0),bt(null);try{let[t,a]=await Promise.all([i||!r?Promise.resolve(null):fn().catch(()=>null),n.fetchQuery({...so({client:q,path:{name:e}}),staleTime:Fi}).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?Ht(s):Promise.resolve(),!i&&s?tn():Promise.resolve(),Ut(),Wt(),Gt(),Kt()])}finally{he(!1)}}(0,Z.useEffect)(()=>{u([]),Re(!1),Dt(null),St(null),Tt(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)(()=>{ae(0),ee(null),re(e=>e.startDate||e.endDate?{...e,startDate:``,endDate:``}:e),ne(e=>e+1),Wt()},[k]);let an=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{an.current?(ae(0),Ze.setPage(1),Ut(0)):an.current=!0},[te]);function on(e){let t=B===e?null:e;ee(t),re(e=>({...e,startDate:t??``,endDate:t??``})),ne(e=>e+1)}let sn=(0,Z.useRef)(!1);(0,Z.useEffect)(()=>{sn.current?(ae(0),Ut(0)):sn.current=!0},[Ye]);async function cn(){if(!a)bt(`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`);else{_e(!0),bt(null),Tt(null);try{let{authUrl:t,redirectUri:r}=await $t(e,`gsc`);if(!t.startsWith(`https://accounts.google.com/`)){bt(`Unexpected OAuth redirect URL. Please try again.`);return}let i=window.open(t,`_blank`,`width=600,height=700`);if(!i){window.location.assign(t);return}let a=r?new URL(r).origin:window.location.origin,o=!1,s=null,c=()=>{s!==null&&window.clearInterval(s),window.removeEventListener(`message`,u)},l=async e=>{if(!o){o=!0,c(),Tt(e?`Google connected. Refreshing access…`:`Refreshing Google connection…`);try{await Pi(n,`google`),await nn()}finally{Tt(null)}}};function u(e){if(e.source!==i||e.origin!==a||!e.data||typeof e.data!=`object`)return;let t=e.data;t.type===fd&&t.connectionType===`gsc`&&l(!0)}window.addEventListener(`message`,u),Tt(`Finish the Google consent flow in the popup. This page will refresh automatically.`),s=window.setInterval(()=>{i.closed&&l(!1)},1e3)}catch(e){bt(e instanceof Error?e.message:`Failed to start OAuth flow`)}finally{_e(!1)}}}async function ln(){bt(null),Tt(null);try{await Ln(e,`gsc`),await Pi(n,`google`),c(e=>e.filter(e=>e.connectionType!==`gsc`)),u([]),S(``)}catch(e){bt(e instanceof Error?e.message:`Failed to disconnect`)}}async function un(){if(x){xe(!0),bt(null);try{await Ue(e,`gsc`,x),await Pi(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,propertyId:x}:e)),Ni({title:`GSC property updated`,detail:`${e} is now linked to ${x}.`,tone:`positive`,dedupeKey:`gsc:property:${e}`,dedupeMode:`drop`})}catch(e){bt(e instanceof Error?e.message:`Failed to save GSC property`)}finally{xe(!1)}}}async function dn(){bt(null),Tt(null);try{await Bt.mutateAsync({projectName:e,projectLabel:e,opts:{days:parseInt(T,10)||void 0,full:D||void 0}}),await Pi(n,`gsc`)}catch{}}async function pn(){if(C.trim()){De(!0),bt(null),Tt(null);try{let t=await ar(e,C.trim());await Pi(n,`gsc`),b(t),w(``),await Gt()}catch(e){bt(e instanceof Error?e.message:`Failed to inspect URL`)}finally{De(!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`})})}),Et&&(0,Q.jsx)(`p`,{role:`status`,className:`mb-3 text-copy-14 text-caution`,children:Et}),xt&&(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:xt.title}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-caution-200/90`,children:xt.message}),(Ys(xt.enableUrl)||Ys(xt.indexingApiUrl))&&(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3`,children:[Ys(xt.enableUrl)&&(0,Q.jsx)(`a`,{href:Ys(xt.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 ↗`}),Ys(xt.indexingApiUrl)&&(0,Q.jsx)(`a`,{href:Ys(xt.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:()=>St(null),children:`×`})]})}),yt&&(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:[yt,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>bt(null),children:`×`})]}),wt&&(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:[wt,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-positive-400 hover:text-positive-200`,onClick:()=>Tt(null),children:`×`})]}),me?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading…`}):(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[At?(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:At.domain}),(0,Q.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Coverage measured`,` `,W?.lastInspectedAt?vi(W.lastInspectedAt):`never`]}),!i&&(0,Q.jsx)(`button`,{type:`button`,className:`ml-auto text-muted transition-colors hover:text-negative-400`,onClick:Mi(ln),children:`Disconnect`})]}):r?(0,Q.jsxs)(rs,{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)(Y,{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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ge,onClick:Mi(cn),children:ge?`Opening…`:`Connect Google Search Console`}):(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,asChild:!0,children:(0,Q.jsx)(H,{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)(rs,{className:`surface-card`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:sd})}),(At||zt)&&(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(rs,{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:`${hd(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 ${ld.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)(ru,{windows:cd,value:k,onChange:e=>{A(e),ae(0),Ze.setPage(1)},label:`Search Console time period`,formatOption:e=>e===`all`?`All`:e}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Se,onClick:()=>{ae(0),Ze.setPage(1),Ut(0),Wt()},children:Se?`Loading…`:`Apply filters`})]})]}),p&&p.daily.length>0&&(()=>{let{totals:e,daily:t,trends:n,periodComparison:r}=p,i=t=>e[t]??null,a=md.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=rr(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=[...ud.filter(e=>P.includes(e.key)).map(e=>({dataKey:e.key,label:e.label,color:e.color,axisId:e.key,inverted:e.inverted,formatValue:e.format,trend:I?n?.[e.key]??null:null})),...a.filter(e=>P.includes(e.key)).map(e=>({dataKey:e.key,label:`${e.label} indexed pages`,color:e.color,axisId:e.key,formatValue:e=>e.toLocaleString(),connectNulls:!0}))],m={key:`performance`,label:`Google search`,basis:r?.comparable?`vs prior ${r.days} ${r.days===1?`day`:`days`}`:void 0,figures:ud.map(e=>{let t=i(e.key);return{key:e.key,label:e.label,color:e.color,value:t===null?`—`:e.format(t),change:pd(r,e.key,e.inverted),interactive:!0,disabled:t===null}})},h=a.length===0?null:{key:`indexed`,label:`Indexed pages`,basis:vu(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:_u(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)(Tu,{name:`Search performance figures`,frame:`none`,mode:`compare`,groups:h?[m,h]:[m],selected:P,onSelect:e=>F(t=>t.includes(e)?t.length===1?t:t.filter(t=>t!==e):[...t,e]),chart:(0,Q.jsx)(di,{data:d,xKey:`date`,series:f,xTickFormatter:fi,labelFormatter:yi,onSelectX:on,selectedX:B}),legendExtra:(0,Q.jsxs)(`label`,{className:`flex min-h-9 cursor-pointer items-center gap-2 pointer-coarse:min-h-11`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:I,onChange:e=>L(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":B===e.date,onClick:()=>on(e.date),children:[yi(e.date),`: `,e.clicks,` clicks, `,e.impressions,` impressions`]},e.date))}),B&&(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 `,yi(B)]}),(0,Q.jsxs)(`button`,{type:`button`,className:`text-link hover:underline`,onClick:()=>on(B),children:[`Show all `,e.days,` days`]})]}),e.position!==null&&(e.positionDays??e.days)<e.days&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Average position covers `,e.positionDays,` of `,e.days,` days. The rest have no property-level position recorded.`]}),(e.position===null||e.position===void 0)&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Average position needs a property-level sync. Run `,(0,Q.jsx)(`code`,{children:`canonry google sync`}),` to record it.`]})]})})(),(0,Q.jsxs)(`div`,{className:`mt-3 grid gap-2 lg:grid-cols-4`,children:[(0,Q.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`Start date`,title:`Start date (inclusive). Leave blank to use the window above.`,value:V.startDate,onChange:e=>re(t=>({...t,startDate:e.target.value}))}),(0,Q.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`End date`,title:`End date (inclusive).`,value:V.endDate,onChange:e=>re(t=>({...t,endDate:e.target.value}))}),(0,Q.jsx)(Ml,{value:V.query,onChange:e=>re(t=>({...t,query:e})),label:`Filter search queries`,placeholder:`Contains query…`}),(0,Q.jsx)(Ml,{value:V.page,onChange:e=>re(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(ui).map(e=>(0,Q.jsx)(`th`,{className:`text-right`,"aria-sort":Ke?.key===e?Ke.dir===`asc`?`ascending`:`descending`:`none`,children:(0,Q.jsxs)(`button`,{type:`button`,className:`w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1`,onClick:()=>{Ze.setPage(1),qe(t=>t?.key===e?t.dir===`desc`?{key:e,dir:`asc`}:null:{key:e,dir:`desc`})},children:[ki[e],Ke?.key===e?Ke.dir===`desc`?` ↓`:` ↑`:``]})},e))]})}),(0,Q.jsx)(`tbody`,{children:Qe.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.date}),(0,Q.jsx)(`td`,{className:`max-w-xs truncate text-strong`,children:e.query}),(0,Q.jsx)(`td`,{className:`max-w-xs text-secondary`,children:(0,Q.jsx)(Al,{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:$e(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)(Nl,{page:ue?Ze.page:Math.floor(ie/25)+1,pageSize:25,visibleRows:Qe.length,totalRows:ue?ce:void 0,hasNextPage:ue?void 0:oe,disabled:Se,itemLabel:ue?`matches`:`rows`,onPageChange:e=>{if(ue){Ze.setPage(e);return}let t=(e-1)*25;ae(t),Ut(t)}}),ue&&ce>=ld?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Results are capped at `,ld.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)(rs,{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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:_t,onClick:()=>void Yt(),children:_t?`Requesting…`:`Request indexing (${W.notIndexed.length})`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Ae,onClick:()=>void Kt(!0),children:Ae?`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:gi.trackSubtle,strokeWidth:`14`}),(0,Q.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Si.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:gi.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:$e(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)(Xc,{id:Ge,label:`Coverage status`,value:He,onChange:e=>{We(e),K(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:`${Ge}-panel`,role:`tabpanel`,"aria-labelledby":`${Ge}-${He}`,tabIndex:0,className:`mt-3 overflow-x-auto`,children:[He===`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:ft.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.verdict??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.crawlTime?e.crawlTime.split(`T`)[0]:`—`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.isMobileFriendly===!0?`Yes`:e.isMobileFriendly===!1?`No`:`—`})]},e.id))})]}),He===`notIndexed`&&!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:()=>K(e.reason),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),K(e.reason))},tabIndex:0,role:`button`,"aria-label":`View ${e.reason} pages`,children:[(0,Q.jsx)(`td`,{className:`text-strong`,children:e.reason}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.count})]},e.reason))})]}),He===`notIndexed`&&!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:pt.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.indexingState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`})]},e.id))})]}),He===`notIndexed`&&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:()=>K(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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:_t,onClick:()=>void Jt(e.urls.map(e=>e.url)),children:_t?`Requesting…`:`Request indexing (${e.count})`})]}),(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Last Crawl`}),(0,Q.jsx)(`th`,{className:`w-8`})]})}),(0,Q.jsx)(`tbody`,{children:ht.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.crawlTime?e.crawlTime.split(`T`)[0]:`—`}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,className:`text-button-14 text-muted hover:text-strong transition-colors`,disabled:_t,onClick:()=>void Jt([e.url]),title:`Request indexing`,children:`Index`})})]},e.id))})]})]}):null})(),He===`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:mt.map((e,t)=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.previousState}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.currentState}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.transitionDate.split(`T`)[0]})]},`${e.url}-${t}`))})]}),(He===`indexed`&&W.indexed.length===0||He===`notIndexed`&&!rt&&W.notIndexed.length===0||He===`deindexed`&&W.deindexed.length===0)&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No URLs in this category.`}),(0,Q.jsx)(Nl,{page:ut,pageSize:dd,visibleRows:Math.min(dd,ct.length-dt),totalRows:ct.length,onPageChange:at,itemLabel:`URLs`})]}),(0,Q.jsxs)(`div`,{className:`mt-4 border-t border-default pt-3`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`flex w-full items-center justify-between text-left text-button-14 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,"aria-expanded":ze,onClick:()=>Ve(e=>!e),children:[(0,Q.jsx)(`span`,{children:`Coverage history`}),(0,Q.jsx)(`span`,{children:ze?`Hide snapshots`:et.length>0?`View ${et.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.`,ot&&(0,Q.jsxs)(Q.Fragment,{children:[` Since the last snapshot: `,ot.indexed>=0?`+`:``,ot.indexed.toLocaleString(),` indexed, `,ot.notIndexed>=0?`+`:``,ot.notIndexed.toLocaleString(),` not indexed.`]})]}),ze&&(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:et.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:et.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.date}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:e.indexed.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.notIndexed.toLocaleString()})]},e.date))})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No saved coverage snapshots yet.`})})]})]}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:Ae?`Loading coverage data…`:`No coverage data yet. Inspect your sitemap to populate this view.`})]}),!i&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(id,{engine:`Google`,data:Mt.isError?null:Mt.isPending&&Mt.fetchStatus!==`idle`?void 0:Mt.data?.google??null,loadError:Mt.isError?Oe(Mt.error):null,label:e=>gd(e,At?.propertyId),canSubmit:jt,submitBlocked:At?(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)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:Mi(cn),children:`Reconnect`})]}):void 0,onSubmit:Xt,submitting:Fe,defaultUrl:At?.sitemapUrl??null,onSetDefault:e=>void Qt(e),settingDefault:Ne,onInspect:e=>void en(e),inspecting:Vt.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:Pt.length>0?(0,Q.jsx)(ad,{label:je?`Submitting ${je.completed} of ${je.total}`:`Resubmit all`,menuLabel:`Resubmit sitemaps to Google`,disabled:!jt||Fe,items:[{key:`primary`,label:Rt,description:Lt>0?`Google rereads every sitemap the index lists.`:`Each sitemap in the list, once.`,disabled:It.length===0,onSelect:()=>void Xt(It)},{key:`files`,label:`Resubmit all files`,description:`Every file inside each index, one by one.`,onSelect:()=>void Zt()}]}):void 0}),(0,Q.jsxs)(rs,{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 pn()}),(0,Q.jsx)(J,{type:`button`,size:`sm`,disabled:Ee||!At?.propertyId||!C.trim(),onClick:Mi(pn),children:Ee?`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:Xr(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:vi(y.crawlTime)})]})]})]})]}),(0,Q.jsxs)(rs,{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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:we,onClick:()=>void Gt(!0),children:we?`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:fe,onChange:e=>pe(e.target.value)})]}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`self-end`,disabled:we,onClick:()=>void Gt(!0),children:`Apply filter`})]}),h.length>0?(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Indexing`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Verdict`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Coverage`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Mobile`}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Inspected`})]})}),(0,Q.jsx)(`tbody`,{children:h.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.indexingState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.verdict??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:Xr(e.isMobileFriendly??null)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:vi(e.inspectedAt)})]},e.id))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No inspection history yet.`})]}),(0,Q.jsxs)(rs,{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:vi(e.transitionDate)})]},`${e.url}:${e.transitionDate}`))})]})}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No deindexed transitions recorded.`})]})]}),At&&!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:()=>{Le||Ht(At),Re(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 ${Le?`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`})]})}),Le&&(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)(rs,{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:ve||l.length===0,onChange:e=>S(e.target.value),children:l.length===0?(0,Q.jsx)(`option`,{value:``,children:ve?`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)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:ve,onClick:()=>void Ht(At,!0),children:ve?`Refreshing…`:`Refresh properties`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,disabled:!x||be,onClick:Mi(un),children:be?`Saving…`:`Save property`})]})]})]}),(0,Q.jsxs)(rs,{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)(J,{type:`button`,size:`sm`,disabled:Bt.isPending||!At.propertyId,onClick:Mi(dn),children:Bt.isPending?`Queueing…`:`Queue sync`}),!At.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`],yd=10,bd=[{key:`clicks`,label:`Clicks`,color:li[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:li[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:Si.caution,format:e=>$e(e)},{key:`position`,label:`Avg position`,color:li[2],inverted:!0,format:e=>e.toFixed(1)}],xd=`bing-indexed`,Sd=`Impression-weighted across the queries Bing names. Bing reports these per week, so the line moves weekly.`,Cd=`Asks Bing directly. Counts against the shared Bing request limit for this key.`;function wd(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:ve(t),direction:t>0?`up`:`down`,tone:t>0?`worse`:`better`,basis:n}}function Td(e){return e==null?`—`:e.toFixed(1)}function Ed(e){return e==null?`—`:Math.round(e).toLocaleString()}function Dd(e){return e.replace(/^https?:\/\//,``).replace(/\/+$/,``)}function Od(e,t){let n=t.replace(/\/+$/,``);return e.startsWith(n)?e.slice(n.length)||`/`:e}function kd(e,t){return e?.find(e=>e.kind===t)}function Ad(e){let t=e?.payload;return t&&typeof t.dailyQuota==`number`&&typeof t.monthlyQuota==`number`?{dailyQuota:t.dailyQuota,monthlyQuota:t.monthlyQuota}:null}function jd(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 Md(e){return Array.isArray(e?.payload)?e.payload.filter(e=>typeof e==`object`&&!!e):null}var Nd=new Set([`entityType`,`requestType`,`type`,`role`]);function Pd(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)?yi(e.slice(0,10)):Nd.has(t)&&/^[a-z]+(?:-[a-z]+)*$/.test(e)?e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`-`,` `):e:JSON.stringify(e)}function Fd({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 Id({projectName:e,refreshNonce:t}){let n=R(),r=U({...vo({client:q,path:{name:e}}),staleTime:Fi}),i=r.data??null,a=U({...Hi({client:q,path:{name:e}}),staleTime:Fi,enabled:!(!i?.connected||i.siteUrl)}),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{t>0&&r.refetch()},[t]);async function f(){if(o.trim()){d(null);try{await Xt(e,o.trim()),s(``),await Pi(n,`bing`)}catch(e){d(Ds(e))}}}async function p(){d(null);try{await Nn(e),l(``),await Pi(n,`bing`)}catch(e){d(Ds(e))}}async function m(){if(c){d(null);try{await an(e,c),await Pi(n,`bing`)}catch(e){d(Ds(e))}}}if(r.isPending)return(0,Q.jsx)(Fd,{children:(0,Q.jsx)(rs,{className:`surface-card`,children:(0,Q.jsx)(`div`,{className:`text-label-14 text-secondary`,children:`Loading Bing data…`})})});if(r.isError)return(0,Q.jsx)(Fd,{children:(0,Q.jsxs)(rs,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load the Bing connection: `,Ds(r.error)]}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void r.refetch(),children:`Retry`})]})});if(!i?.connected)return(0,Q.jsx)(Fd,{children:(0,Q.jsxs)(rs,{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)(Y,{tone:`caution`,children:`Not connected`})]}),G()?(0,Q.jsx)(`p`,{className:`text-copy-14 text-neutral`,children:`Bing Webmaster Tools is not connected for this project.`}):(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 items-center gap-2`,children:[(0,Q.jsx)(`input`,{id:`bing-api-key`,type:`password`,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:`Bing Webmaster Tools API key`,value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&f()}}),(0,Q.jsx)(Rr,{size:`sm`,disabled:!o.trim(),onClick:Mi(f),children:`Connect`})]}),(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`})]})]})]}),u&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:u})]})});if(!i.siteUrl){let e=a.data?.sites??[];return(0,Q.jsx)(Fd,{children:(0,Q.jsxs)(rs,{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)(Y,{tone:`positive`,children:`Connected`}),!G()&&(0,Q.jsx)(Rr,{size:`sm`,variant:`ghost`,onClick:Mi(p),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:i.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. Pick the verified site that should receive 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:i.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:i.updatedAt?vi(i.updatedAt):`—`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Select site`}),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:c,onChange:e=>l(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))]}),!G()&&(0,Q.jsx)(Rr,{size:`sm`,disabled:!c,onClick:Mi(m),children:`Set Site`})]}):(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:a.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.`})]})]}),u&&(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:u})]})})}return(0,Q.jsx)(Ld,{projectName:e,connection:i,siteUrl:i.siteUrl,onDisconnect:p,error:u})}function Ld({projectName:e,connection:t,siteUrl:n,onDisconnect:r,error:i}){let[a,o]=(0,Z.useState)(`30d`),s=tt(),c={name:e},l=U({...ga({client:q,path:c,query:{window:a}}),staleTime:Fi,placeholderData:z,enabled:!s}),u=U({...Sa({client:q,path:c}),staleTime:Fi,enabled:!s}),d=U({...bo({client:q,path:c}),staleTime:Fi,enabled:!s}),f=!s&&!!(l.data?.latestAvailableDate||u.data?.syncedAt||d.data?.syncedAt),p=!l.isPending&&!u.isPending&&!d.isPending,m=[l,u,d].find(e=>e.isError)?.error??null,h=Md(kd(u.data?.snapshots,`blocked-urls`))?.length??0;return(0,Q.jsx)(Fd,{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:Dd(n)}),l.data?.latestAvailableDate&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Data through `,yi(l.data.latestAvailableDate)]})]}),u.data?.syncedAt&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,Q.jsxs)(`span`,{children:[`Synced `,vi(u.data.syncedAt)]})]}),h>0&&(0,Q.jsx)(`span`,{className:`ml-1.5`,children:(0,Q.jsx)(X,{tone:`caution`,label:`${h} blocked URL${h===1?``:`s`}`,text:`Bing is keeping ${h===1?`one URL`:`${h} URLs`} out of its results, which also keeps ${h===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)(y,{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?vi(t.updatedAt):`—`})]}),!G()&&!s&&(0,Q.jsx)(Rr,{size:`sm`,variant:`ghost`,onClick:Mi(r),children:`Disconnect`})]})]}),children:(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[i&&(0,Q.jsx)(`p`,{className:`text-copy-13 text-negative`,children:i}),!s&&(p&&!f&&m?(0,Q.jsxs)(rs,{className:`surface-card`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load Bing data: `,Ds(m)]}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{l.refetch(),u.refetch(),d.refetch()},children:`Retry`})]}):p&&!f?(0,Q.jsx)(Bd,{projectName:e,loadedAt:u.dataUpdatedAt}):(0,Q.jsx)(Vd,{projectName:e,siteUrl:n,range:a,onRangeChange:o})),(0,Q.jsx)(Kd,{projectName:e,siteUrl:n,snapshots:u.data?.snapshots}),f&&(0,Q.jsx)(qd,{projectName:e,siteUrl:n}),f&&(0,Q.jsx)(Wd,{projectName:e}),f&&(0,Q.jsx)(Yd,{siteUrl:n,snapshots:u.data?.snapshots??[]})]})})}var Rd=5e3;function zd(e){return e?.status===Ot.queued||e?.status===Ot.running}function Bd({projectName:e,loadedAt:t}){let n=R(),r=U({...ns({client:q,path:{name:e},query:{kind:Ct[`bing-sync`],limit:1}}),refetchInterval:e=>zd(e.state.data?.[0])?Rd:!1,enabled:!G()}),i=r.data?.[0],a=zd(i),[o,s]=(0,Z.useState)(!1),c=i&&!a&&i.finishedAt?Date.parse(i.finishedAt):0;(0,Z.useEffect)(()=>{c>t&&hs(n,Ct[`bing-sync`],e)},[c,t,n,e]);async function l(){s(!0);try{let t=await Zt(e);ks({id:t.id,projectId:t.projectId,kind:Ct[`bing-sync`],projectLabel:e,sourceAction:`bing-sync`}),await r.refetch(),Ni({title:`Bing sync started`,detail:`Search data appears here when it finishes.`,tone:`neutral`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}catch(t){Ni({title:`Bing sync could not start`,detail:Ds(t),tone:`negative`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}finally{s(!1)}}let u=!a&&i?.status===Ot.failed;return(0,Q.jsxs)(rs,{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===Ot.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?`: ${qt(i.error)}`:`.`]}),!G()&&(0,Q.jsx)(Rr,{className:`mt-3`,size:`sm`,disabled:a||o,onClick:Mi(l),children:a||o?`Sync running…`:u?`Try the sync again`:`Sync Bing data now`})]})}function Vd({projectName:e,siteUrl:t,range:n,onRangeChange:r}){let i={name:e},a=U({...ga({client:q,path:i,query:{window:n}}),staleTime:Fi,placeholderData:z}),o=U({...$i({client:q,path:i,query:{window:n,groupBy:`week`}}),staleTime:Fi,placeholderData:z}),s=U({...io({client:q,path:i,query:{surface:`index-coverage`,window:n}}),staleTime:Fi,placeholderData:z}),[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: `,Ds(a.error)]});else{let r=o.data?.totals?.avgImpressionPosition??null,i=wd(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:bd.map(e=>{if(e.key===`position`)return{key:e.key,label:e.label,help:Sd,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:pd(m,e.key,!1),interactive:!0,disabled:f.rows.length===0}})},_=p?{key:`indexed`,label:`Indexed pages`,basis:vu([p]),figures:[{key:xd,label:`Bing`,color:li[6],value:p.value===null?`—`:p.value.toLocaleString(),change:_u(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?rr(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,[xd]:T.get(e)??null}}):[],D=[...bd.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(xd)&&p?[{dataKey:xd,label:`Bing indexed pages`,color:li[6],axisId:xd,formatValue:e=>e.toLocaleString(),connectNulls:!0}]:[]];h=(0,Q.jsxs)(`div`,{className:`mt-3`,children:[(0,Q.jsx)(Tu,{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)(di,{data:E,xKey:`date`,series:D,xTickFormatter:fi,labelFormatter:yi,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)(Hd,{projectName:e,siteUrl:t,range:n})]})}return(0,Q.jsxs)(rs,{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:`${hd(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:[yi(f.window.startDate),` to `,yi(f.window.endDate)]})]}),(0,Q.jsx)(ru,{windows:vd,value:n,onChange:r,label:`Bing time period`,formatOption:e=>e===`all`?`All`:e})]}),h]})}function Hd({projectName:e,siteUrl:t,range:n}){let[r,i]=(0,Z.useState)(`queries`),a=(0,Z.useId)(),[o,s]=(0,Z.useState)(``),[c,l]=(0,Z.useState)(void 0),[u,f]=(0,Z.useState)(1),[p,m]=(0,Z.useState)(null),h={name:e},g=(u-1)*yd;(0,Z.useEffect)(()=>{let e=o.trim()||void 0;if(e===void 0){l(void 0);return}let t=setTimeout(()=>l(e),300);return()=>clearTimeout(t)},[o]);let _=U({...$i({client:q,path:h,query:{window:n,query:c,limit:yd,offset:g}}),staleTime:Fi,placeholderData:z,enabled:r===`queries`}),v=U({...Pa({client:q,path:h,query:{window:n,page:c,limit:yd,offset:g}}),staleTime:Fi,placeholderData:z,enabled:r===`pages`}),b=r===`queries`?_:v,x=r===`queries`?(_.data?.rows??[]).map(e=>({key:e.query,...e})):(v.data?.rows??[]).map(e=>({key:e.page,...e})),S=b.data?.totalMatching??0,C=r===`queries`?`Query`:`Page`;return(0,Z.useEffect)(()=>{f(1),m(null)},[r,n,c]),(0,Q.jsxs)(`div`,{className:`mt-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3 border-b border-base`,children:[(0,Q.jsx)(Xc,{id:a,label:`Bing search rows`,value:r,onChange:i,className:`flex gap-1`,tabClassName:`border-b-2 px-3 py-1.5 text-button-14 transition-colors`,activeTabClassName:`border-mono-200 text-strong`,inactiveTabClassName:`border-transparent text-muted hover:text-neutral`,options:[[`queries`,`Queries`],[`pages`,`Pages`]]}),(0,Q.jsx)(Ml,{className:`mb-1.5 w-full sm:w-64`,value:o,onChange:s,label:r===`queries`?`Filter Bing queries`:`Filter Bing pages`,placeholder:r===`queries`?`Contains query…`:`Contains page URL…`})]}),(0,Q.jsxs)(`div`,{id:`${a}-panel`,role:`tabpanel`,"aria-labelledby":`${a}-${r}`,tabIndex:0,children:[b.isError?(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing `,r,`: `,Ds(b.error)]}):(0,Q.jsx)(`div`,{className:`mt-2 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`w-7`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,Q.jsx)(`th`,{className:`text-left`,children:C}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`CTR`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Position`})]})}),(0,Q.jsxs)(`tbody`,{children:[x.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:6,className:`py-6 text-center text-secondary`,children:b.isPending?`Loading…`:c?`No ${r} match "${c}" in this window.`:`Bing named no ${r} in this window.`})}),x.map(i=>{let a=p===i.key;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":a,"aria-label":`${a?`Hide`:`Show`} details for ${i.key}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>m(a?null:i.key),children:a?(0,Q.jsx)(y,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,Q.jsx)(`td`,{className:`max-w-md text-strong`,children:r===`pages`?(0,Q.jsx)(Al,{value:Od(i.key,t),title:i.key,className:`font-mono text-label-13`}):(0,Q.jsx)(`span`,{className:`block truncate`,title:i.key,children:i.key})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:i.clicks.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:i.impressions.toLocaleString()}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:$e(i.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Td(i.avgImpressionPosition)})]}),a&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:5,className:`pb-4`,children:(0,Q.jsx)(Ud,{projectName:e,siteUrl:t,range:n,tab:r,rowKey:i.key})})]})]},i.key)})]})]})}),(0,Q.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,Q.jsx)(Nl,{page:u,pageSize:yd,visibleRows:x.length,totalRows:S,disabled:b.isFetching,itemLabel:r,onPageChange:f})})]})]})}function Ud({projectName:e,siteUrl:t,range:n,tab:r,rowKey:i}){let a={name:e},[o,s]=(0,Z.useState)(!1),c=U({...$i({client:q,path:a,query:{window:n,query:i,match:`exact`,groupBy:`week`}}),staleTime:Fi,enabled:r===`queries`}),l=U({...Pa({client:q,path:a,query:{window:n,page:i,match:`exact`,groupBy:`week`}}),staleTime:Fi,enabled:r===`pages`}),u=U({...Xi({client:q,path:a,query:{query:i}}),staleTime:Fi,retry:!1,enabled:o&&r===`queries`}),d=U({...Jo({client:q,path:a,query:{page:i}}),staleTime:Fi,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:yi(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:Td(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&&(G()?(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)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>s(!0),children:[(0,Q.jsx)(O,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Load `,h.toLowerCase(),` from Bing`]}),(0,Q.jsx)(X,{label:`Live`,text:Cd})]})),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:`${Ds(p.error)} Nothing was stored.`}),(0,Q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void p.refetch(),children:[(0,Q.jsx)(g,{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?yi(e.date):`—`}),(0,Q.jsx)(`td`,{className:`max-w-xs`,children:r===`queries`?(0,Q.jsx)(Al,{value:Od(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:Td(e.avgImpressionPosition)})]},`${e.date}:${e.key}:${n}`))})]}))]})]})}function Wd({projectName:e}){let t=U({...Ji({client:q,path:{name:e}}),staleTime:Fi}),[n,r]=(0,Z.useState)(null),i=t.data?.market,a=t.data?.rows??[];return(0,Q.jsxs)(rs,{className:`surface-card`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`h3`,{children:`Search demand`}),i&&(0,Q.jsx)(X,{label:`${i.country.toUpperCase()} · ${i.language}`,text:`Exact-match Bing searches per week for your tracked queries, averaged over the weeks stored. This is demand, not your traffic. Refreshed weekly.`})]}),t.isError?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load search demand: `,Ds(t.error)]}):(0,Q.jsx)(`div`,{className:`overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`w-7`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,Q.jsx)(`th`,{className:`text-left`,children:`Tracked query`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Searches / week`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Latest week`})]})}),(0,Q.jsxs)(`tbody`,{children:[a.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`py-6 text-center text-secondary`,children:t.isPending?`Loading…`:`No search demand stored yet. It is read weekly for tracked queries.`})}),a.map(t=>{let i=n===t.query;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`button`,{type:`button`,"aria-expanded":i,"aria-label":`${i?`Hide`:`Show`} weekly searches for ${t.query}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>r(i?null:t.query),children:i?(0,Q.jsx)(y,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(d,{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:Ed(t.avgWeeklyImpressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Ed(t.latestImpressions)})]}),i&&(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{}),(0,Q.jsx)(`td`,{colSpan:3,className:`pb-4`,children:(0,Q.jsx)(Gd,{projectName:e,query:t.query})})]})]},t.query)})]})]})})]})}function Gd({projectName:e,query:t}){let n=U({...Ji({client:q,path:{name:e},query:{query:t}}),staleTime:Fi}),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:yi(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 Kd({projectName:e,siteUrl:t,snapshots:n}){let r=R(),i=tt(),a={name:e},o=U({...eo({client:q,path:a}),staleTime:Fi}),s=U({...Ma({client:q,path:a}),staleTime:Fi}),c=U({...Zo({client:q,path:a,query:{days:`30`}}),staleTime:Fi,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=Ad(kd(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 wn(e,t)).summary;Ni({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 Pi(r,`bing`)}catch(t){let r=Ds(t);y(r),Ni({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 Zn(e,m.trim());_(t),await Pi(r,`bing`)}catch(e){y(Ds(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:$e(x.percentage,Lt.percent)}]:[],A=jl({rows:l===`not-indexed`?C:l===`unknown`?w:l===`indexed`?T:[],pageSize:yd}),j=jl({rows:E,pageSize:yd}),M=jl({rows:c.data?.rows??[],pageSize:yd}),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=!G()&&!i&&(l===`not-indexed`||l===`unknown`)&&(l===`not-indexed`?C.length:w.length)>0;return(0,Q.jsxs)(rs,{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 ${yi(S.date)}. Crawl by day has the codes.`})]}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:o.data?.lastInspectedAt?`Last inspected ${vi(o.data.lastInspectedAt)}`:`No inspection history yet`})]}),(0,Q.jsx)(`div`,{className:`space-y-4`,children:k.length>0?(0,Q.jsx)(Pu,{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)(Xc,{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)(Rr,{size:`sm`,variant:`outline`,disabled:f,onClick:Mi(()=>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`&&!G()&&!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)(Al,{value:Od(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?vi(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)(Rr,{size:`sm`,variant:`ghost`,disabled:f,onClick:Mi(()=>D({urls:[n.url]},n.url)),children:`Submit`})})})]},n.id))]})]})})(),(l===`not-indexed`||l===`unknown`||l===`indexed`)&&(0,Q.jsx)(Nl,{page:A.page,pageSize:yd,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:[!G()&&!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)(Rr,{size:`sm`,disabled:!m.trim(),onClick:Mi(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)(Al,{value:Od(e.url,t),title:e.url,className:`font-mono text-label-13 text-neutral`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Y,{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:vi(e.inspectedAt)})]},e.id))]})]}),(0,Q.jsx)(Nl,{page:j.page,pageSize:yd,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:yi(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)(Nl,{page:M.page,pageSize:yd,visibleRows:M.rows.length,totalRows:M.totalRows,onPageChange:M.setPage,itemLabel:`days`})]})]})]})}function qd({projectName:e,siteUrl:t}){let{canWrite:n}=ji(),r=U({...Lo({client:q,path:{name:e}}),staleTime:Fi}),[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 en(e,r),n.push(r);let r=n.length;Ni({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){Ni({title:n.length>0?`Bing took ${n.length} of ${t.length}`:`Bing did not take the sitemap`,detail:Ds(r),tone:`negative`,dedupeKey:`bing:submit-sitemap:${e}`,dedupeMode:`replace`})}finally{a(!1)}return n}async function l(t){s(!0);try{await Nt(e,{sitemapUrl:t}),Ni({title:`Checking sitemap URLs in Bing`,detail:`Coverage updates when the check finishes.`,tone:`neutral`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}catch(t){Ni({title:`Sitemap check could not start`,detail:Ds(t),tone:`negative`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}finally{s(!1)}}return(0,Q.jsx)(id,{engine:`Bing`,data:r.isError?null:r.isPending?void 0:r.data.bing,loadError:r.isError?Ds(r.error):null,label:e=>Od(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:G()})}var Jd=`Bing shows this only to the site owner key. Not a failure.`;function Yd({siteUrl:e,snapshots:t}){let n=Ad(kd(t,`url-submission-quota`)),r=Ad(kd(t,`content-submission-quota`)),i=jd(kd(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:Jd};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=kd(t,n),s=Md(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)(Xd,{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)(Al,{value:Od(r,e),title:r,className:`font-mono text-neutral`}):Pd(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)(rs,{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)(Xd,{label:`URL submissions left`,value:l(n),help:`URL submissions Bing will still accept, as of the last sync.`}),(0,Q.jsx)(Xd,{label:`Content submissions left`,value:l(r)}),(0,Q.jsx)(Xd,{label:`Crawl boost`,value:i?i.crawlBoostEnabled?`On`:i.crawlBoostAvailable?`Off`:`Not offered`:`—`}),i&&i.crawlRate.length===24&&(0,Q.jsx)(Xd,{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 Xd({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)(d,{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 Zd=li[0],Qd=li[1],$d=li[2],ef=li[3],tf=li[4],nf=[`both`,`server`,`ga4`],rf=[`days`,`months`],af={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.`},of=e=>new Date(`${e}-01T00:00:00.000Z`),sf=e=>of(e).toLocaleDateString(void 0,{month:`short`,timeZone:`UTC`}),cf=e=>of(String(e)).toLocaleDateString(void 0,{month:`long`,year:`numeric`,timeZone:`UTC`}),lf=e=>Number(e.slice(0,4))*12+Number(e.slice(5,7)),uf={fontSize:12,paddingTop:6},df=e=>typeof e==`number`?De(Math.round(e)):String(e),ff=`Visits, server`,pf=`${ff} (older count)`,mf=`${ff} (part month)`,hf=`Visits, GA4 (part month)`,gf=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function _f(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 vf(e,t){if(!e||t<e.startMonth||t>e.endMonth)return null;let n=lf(e.endMonth)-lf(e.startMonth);return n<=0?null:e.start+(e.end-e.start)*((lf(t)-lf(e.startMonth))/n)}function yf(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 bf(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 xf(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 Sf(e,t,n=!1){return r=>{let{cx:i,cy:a,index:o,key:s}=r,c=o??-1,l=e[c]!=null&&e[c-1]==null&&e[c+1]==null;return e[c]==null||!n&&!l||i===void 0||a===void 0?(0,Q.jsx)(`g`,{},s):n?(0,Q.jsx)(`circle`,{cx:i,cy:a,r:3.2,fill:`none`,stroke:t,strokeWidth:1.6},s):(0,Q.jsx)(`circle`,{cx:i,cy:a,r:2.6,fill:t,stroke:`none`},s)}}function Cf({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=jc(e,{range:d,granularity:`month`,limit:1},{enabled:u}),p=jc(e,{sinceMinutes:t,granularity:`day`,limit:1}),m=Nc(e),h=U({...aa({client:q,path:{name:e}}),enabled:!!e,staleTime:Li}),g=h.data?.connected===!0,_=U({...Aa({client:q,path:{name:e},query:{window:t>=259200?`180d`:t>=129600?`90d`:t>=43200?`30d`:`7d`}}),enabled:!!e&&g,staleTime:Li}),v=U({...Aa({client:q,path:{name:e},query:{startDate:d.since.slice(0,10)}}),enabled:!!e&&g&&u,staleTime:Li}),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)(()=>bf(y),[y]),C=p.data?.series?.coverageStart??null,w=p.data?.series?.aiReferralCountingChangedAt??null,T=(0,Z.useMemo)(()=>xf(y,w?.slice(0,10)),[w,y]),E=p.data?.series?.trends,D=(0,Z.useMemo)(()=>{let e=_f(E?.crawlerContentHits,y.length),t=_f(E?.aiUserFetchHits,y.length),n=_f(E?.aiReferralLandedHits,y.length);return y.map((r,i)=>({...r,crawlerContentHits:r.measured===!1?null:gf(r.crawlerContentHits),aiUserFetchHits:r.measured===!1?null:gf(r.aiUserFetchHits),aiReferralLandedHits:r.measured===!1?null:gf(r.aiReferralLandedHits),ga4Visits:b.get(r.bucket)??null,ga4Trend:yf(x,r.bucket),crawlTrend:e[i],fetchTrend:t[i],visitTrend:n[i]}))},[y,b,x,E]),O=f.data?.series,k=v.data,A=(0,Z.useMemo)(()=>O?.points??[],[O]),j=(0,Z.useMemo)(()=>{let e=new Set(O?.partialBuckets??[]),t=new Map((k?.months??[]).map(e=>[e.month,e])),n=_f(O?.trends?.aiReferralLandedHits,A.length),r=new Map(A.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?gf(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:vf(k?.monthlyTrend,n),recorded:o!==null||(s?.sessions??null)!==null}}),a=i.findIndex(e=>e.recorded);return a>0?i.slice(a):i},[A,O,k]),M=u?j:D,N=(0,Z.useMemo)(()=>{if(o===`ga4`)return null;if(!u)return S;let e=new Set(j.map(e=>e.bucket));return bf(A.filter(t=>e.has(t.bucket)))},[o,u,A,j,S]),P=(0,Z.useMemo)(()=>u?xf(A,O?.aiReferralCountingChangedAt?.slice(0,7)):T,[u,A,O,T]),F=P!==null&&o!==`ga4`,I=(e,t,n)=>{let r=n.payload?.bucket;return P&&t===ff&&r!==void 0&&r<=P.to?[df(e),pf]:df(e)},L=(k?.months??[]).filter(e=>e.complete&&e.sessions!==null).at(-1)??null,R=j.filter(e=>e.aiReferralLandedHits!==null).at(-1)??null,z=o===`server`?R?.bucket??null:o===`ga4`?L?.month??null:L?.month??R?.bucket??null,B=z?j.find(e=>e.bucket===z)?.aiReferralLandedHits??null:null,ee=k?.monthlyTrend??null,te=u&&o!==`ga4`,ne=u&&o!==`server`,V=ne&&g,H=te&&f.isSuccess||V&&v.isSuccess,re=(!te||f.isSuccess)&&(!ne||h.isSuccess&&(!g||v.isSuccess)),he=j.some(e=>te&&(e.aiReferralLandedHits!==null||e.serverPartial!==null)||V&&(e.ga4Visits!==null||e.ga4Partial!==null)),ge=j.find(e=>e.bucket===d.until.slice(0,7)),_e=V?ge?.ga4Partial??null:null,ve=te?ge?.serverPartial??null:null,ye=_e!==null||ve!==null,be=p.data?.totals,xe=be&&{crawlers:gf(be.crawlerContentHits),fetches:gf(be.aiUserFetchHits),visits:gf(be.aiReferralLandedHits)},Se=(0,Z.useMemo)(()=>y.reduce((e,t)=>({crawlers:e.crawlers+gf(t.crawlerContentHits),fetches:e.fetches+gf(t.aiUserFetchHits),visits:e.visits+gf(t.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[y]),Ce=xe??Se,we=Ce.crawlers>0||Ce.fetches>0||Ce.visits>0,Te=null;if(p.isLoading)Te=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading AI traffic history…`});else if(p.isError)Te=(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(!we){let e=m.data?.sources,t=e!==void 0&&e.length===0,n=!t&&C===null;Te=(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:[Te??(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mb-5`,children:(0,Q.jsx)(Pu,{label:`AI traffic totals`,items:[{label:`AI crawlers`,value:De(Ce.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:`AI page fetches`,value:De(Ce.fetches),detail:`reading a page to answer`,tooltip:`An AI engine fetching a page live while answering someone, rather than crawling it for an index.`},{label:`AI visitors`,value:De(Ce.visits),detail:T?`older days may read high`:`arrived from an AI answer`,tooltip:`Visits your server answered that came from an AI engine. Requests answered with a redirect are excluded: a redirect is a hop, not an arrival.`+(T?` Days through ${yi(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:gf(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:gf(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:gf(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`}),`Page fetches`]}),(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)(ce,{width:`100%`,height:206,children:(0,Q.jsxs)(pe,{data:D,margin:{top:4,right:8,left:-18,bottom:0},children:[(0,Q.jsx)(ie,{stroke:`var(--chart-grid, #2e2e2e)`,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`bucket`,tick:xi,stroke:`var(--chart-axis, #2e2e2e)`,tickFormatter:fi,minTickGap:28}),(0,Q.jsx)(de,{tick:xi,stroke:`var(--chart-axis, #2e2e2e)`,width:48,allowDecimals:!1}),(0,Q.jsx)(ae,{contentStyle:Ti.contentStyle,labelStyle:Ti.labelStyle,itemStyle:Ti.itemStyle,labelFormatter:yi,formatter:df}),S&&(0,Q.jsx)(se,{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)`}}),(0,Q.jsx)(ue,{wrapperStyle:uf,iconType:`plainline`,iconSize:14}),(0,Q.jsx)(le,{type:`monotone`,dataKey:`crawlerContentHits`,name:`Pages crawled`,stroke:Zd,fill:Zd,fillOpacity:.22,strokeWidth:1.8}),n&&(0,Q.jsx)(le,{type:`monotone`,dataKey:`aiUserFetchHits`,name:`Page fetches`,stroke:Qd,fill:Qd,fillOpacity:.18,strokeWidth:1.6}),i&&(0,Q.jsx)(fe,{type:`linear`,dataKey:`crawlTrend`,legendType:`none`,name:`Pages crawled trend`,dot:!1,tooltipType:`none`,stroke:Zd,strokeWidth:1.4,strokeDasharray:`5 4`,connectNulls:!0}),i&&n&&(0,Q.jsx)(fe,{type:`linear`,dataKey:`fetchTrend`,legendType:`none`,name:`Page fetches trend`,dot:!1,tooltipType:`none`,stroke:Qd,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)(ru,{windows:rf,value:c,onChange:l,label:`Visits by day or month`,formatOption:e=>e===`months`?`Months`:`Days`}),(0,Q.jsx)(ru,{windows:nf,value:o,onChange:s,label:`Visit measurement source`,formatOption:e=>e===`ga4`?`GA4`:e===`both`?`Both`:`Server`})]})]}),te&&f.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:af.serverLoading}),V&&v.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:af.gaLoading}),ne&&h.isLoading&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:af.gaStatusLoading}),ne&&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:af.gaStatusError}),(0,Q.jsx)(J,{variant:`outline`,size:`sm`,"aria-label":af.retryGaStatus,disabled:h.isFetching,onClick:()=>{h.refetch()},children:`Retry`})]}),te&&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:af.serverError}),(0,Q.jsx)(J,{variant:`outline`,size:`sm`,"aria-label":af.retryServer,disabled:f.isFetching,onClick:()=>{f.refetch()},children:`Retry`})]}),V&&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:af.gaError}),(0,Q.jsx)(J,{variant:`outline`,size:`sm`,"aria-label":af.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:af.connectGa}),H&&re&&!he&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:af.emptyMonths}),u&&z&&(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:cf(z)}),o!==`server`&&L?.month===z&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:De(L.sessions??0)}),`visits, GA4`]}),o!==`ga4`&&B!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:De(B)}),`visits, server`]}),o!==`server`&&ee?.changePct!=null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:[ee.changePct>0?`▲`:ee.changePct<0?`▼`:``,$e(Math.abs(ee.changePct),Lt.percent)]}),`trend since `,sf(ee.startMonth)]}),o!==`server`&&L?.month===z&&L.engines[0]&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:De(L.engines[0].sessions)}),`from `,L.engines[0].label]})]}),ye&&ge&&(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:[cf(ge.bucket),` so far`]}),_e!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong tabular-nums mr-1`,children:De(_e)}),`visits, GA4`]}),ve!==null&&(0,Q.jsxs)(`span`,{children:[(0,Q.jsx)(`span`,{className:`text-heading text-label-13-strong tabular-nums mr-1`,children:De(ve)}),`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?H&&he:!Te)&&(0,Q.jsx)(ce,{width:`100%`,height:176,children:(0,Q.jsxs)(pe,{data:M,margin:{top:4,right:8,left:-18,bottom:0},children:[(0,Q.jsx)(ie,{stroke:`var(--chart-grid, #2e2e2e)`,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`bucket`,tick:xi,stroke:`var(--chart-axis, #2e2e2e)`,tickFormatter:u?sf:fi,minTickGap:u?8:28}),(0,Q.jsx)(de,{tick:xi,stroke:`var(--chart-axis, #2e2e2e)`,width:48,allowDecimals:!1}),(0,Q.jsx)(ae,{contentStyle:Ti.contentStyle,labelStyle:Ti.labelStyle,itemStyle:Ti.itemStyle,labelFormatter:u?cf:yi,formatter:I}),N&&N.from!==N.to&&(0,Q.jsx)(se,{x1:N.from,x2:N.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)`}}),P&&F&&(0,Q.jsx)(se,{x1:P.from,x2:P.to,fill:`var(--color-overlay-hover)`,fillOpacity:.3,stroke:`none`}),P&&F&&(0,Q.jsx)(me,{x:P.to,stroke:tf,strokeDasharray:`4 4`,strokeWidth:1.5}),(0,Q.jsx)(ue,{wrapperStyle:uf,iconType:`plainline`,iconSize:14}),o!==`ga4`&&(0,Q.jsx)(fe,{type:`monotone`,dataKey:`aiReferralLandedHits`,name:ff,stroke:$d,strokeWidth:2,connectNulls:!1,dot:u?Sf(M.map(e=>e.aiReferralLandedHits??null),$d):!1}),u&&o!==`ga4`&&(0,Q.jsx)(fe,{type:`monotone`,dataKey:`serverPartial`,name:mf,legendType:`none`,connectNulls:!1,stroke:$d,strokeWidth:0,activeDot:!1,dot:Sf(M.map(e=>e.serverPartial??null),$d,!0)}),o!==`server`&&(0,Q.jsx)(fe,{type:`monotone`,dataKey:`ga4Visits`,name:`Visits, GA4`,connectNulls:!1,stroke:ef,strokeWidth:1.8,strokeDasharray:`5 3`,dot:Sf(M.map(e=>e.ga4Visits??null),ef)}),u&&o!==`server`&&(0,Q.jsx)(fe,{type:`monotone`,dataKey:`ga4Partial`,name:hf,legendType:`none`,connectNulls:!1,stroke:ef,strokeWidth:0,activeDot:!1,dot:Sf(M.map(e=>e.ga4Partial??null),ef,!0)}),i&&o!==`ga4`&&(0,Q.jsx)(fe,{type:`linear`,dataKey:`visitTrend`,legendType:`none`,name:`Visits trend`,dot:!1,tooltipType:`none`,stroke:$d,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0}),i&&o!==`server`&&(0,Q.jsx)(fe,{type:`linear`,dataKey:`ga4Trend`,legendType:`none`,name:`GA4 visits trend`,dot:!1,tooltipType:`none`,stroke:ef,strokeWidth:1.6,strokeDasharray:`1 4`,strokeLinecap:`round`,connectNulls:!0})]})})]})}function wf(e){return e.replace(/\+/g,` `)}var Tf=Pe,Ef={"7d":10080,"30d":43200,"90d":129600,"180d":259200};function Df(e){return Ol(e.landingPage)}var Of=25,kf=10,Af={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0,byEngine:{series:[],otherCount:0,days:[]}},jf={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`,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 Mf(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 Nf(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Pf(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 Ff({projectName:e}){let{data:t,isLoading:n,isError:r}=Mc(e),i=t?.sources??[];return(0,Q.jsxs)(`section`,{"aria-labelledby":`server-activity-heading`,children:[(0,Q.jsx)(Au,{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:!G()&&i.length>0?(0,Q.jsx)(H,{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.`,` `,!G()&&(0,Q.jsx)(H,{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)(Iu,{label:`Source`,align:`left`}),(0,Q.jsx)(Iu,{label:`Status`,align:`left`}),(0,Q.jsx)(Iu,{label:`Crawler hits`,align:`right`}),(0,Q.jsx)(Iu,{label:`AI hits`,align:`right`}),(0,Q.jsx)(Iu,{label:`AI sessions`,align:`right`}),(0,Q.jsx)(Iu,{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)(Y,{tone:Pc(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:Lc(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?Mf(t.lastSyncedAt):`never`}),(0,Q.jsx)(`td`,{className:`py-2 pl-3 text-right`,children:!G()&&(0,Q.jsx)(H,{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 If({projectName:e}){let[t,n]=(0,Z.useState)(`30d`);return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(Ff,{projectName:e}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsx)(Gf,{projectName:e,window:t,periodControl:(0,Q.jsx)(ru,{windows:Tf,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)(Au,{id:`ai-traffic-history-heading`,title:`AI traffic history`,tooltip:jf.aiHistoryTooltip}),(0,Q.jsx)(Cf,{projectName:e,sinceMinutes:Ef[t]})]})]})})]})}var Lf={session:`Session`,first_user:`First visit`,manual_utm:`UTM`},Rf={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)`},zf=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Attribution`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}],Bf=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}];function Vf(e){return e.engine===null}function Hf({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:Rf[e.sourceDimension]??``,children:Lf[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:$e(e.share)})]})}function Uf({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:wf(e.source)}),(0,Q.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:wf(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:$e(e.share)})]})}function Wf(e,t){let n=R(),[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)(Af),[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({...aa({client:q,path:{name:e}}),staleTime:Li});if(r.current)return;if(i(a),!a.connected){o(null),v(Af),b([]),S(null),c(!1);return}let s=t===`all`?void 0:t,[l,u,d,f]=await Promise.all([n.fetchQuery({...La({client:q,path:{name:e},query:s?{window:s}:void 0}),staleTime:Li}),n.fetchQuery({...Aa({client:q,path:{name:e},query:s?{window:s}:void 0}),staleTime:Li}).catch(()=>Af),n.fetchQuery({...za({client:q,path:{name:e},query:s?{window:s}:void 0}),staleTime:Li}).catch(()=>[]),n.fetchQuery({...es({client:q,path:{name:e},query:{window:qn(t)?t:`30d`}}),staleTime:Li}).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 En(e,qn(t)?He[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 Pi(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 pn(e),await Pi(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 Pi(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 Gf({projectName:e,window:t,periodControl:n,between:r}){let i=Wf(e,t??`30d`);return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Kf,{ga:i,projectName:e,periodControl:n}),r,(0,Q.jsx)(qf,{ga:i,projectName:e})]})}function Kf({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&&!G()&&!tt(),d=i?Pf(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)(Ju,{overview:e.overview,refreshing:e.loading}):i?(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(Pu,{label:`Site traffic`,items:[{label:`Total sessions`,value:Nf(i.totalSessions),detail:i.totalSessions.toLocaleString()},{label:`Organic sessions`,value:Nf(i.totalOrganicSessions),detail:`${i.organicSharePctDisplay} of total`},{label:`Total users`,value:i.totalUsers===null?`n/a`:Nf(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.`}),!G()&&!tt()&&(0,Q.jsxs)(J,{variant:`outline`,size:`sm`,disabled:a,onClick:Mi(s),children:[(0,Q.jsx)(g,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),`Sync from GA4`]})]}):G()||tt()?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Google Analytics 4 property connected.`}):(0,Q.jsx)(np,{projectName:t,onConnected:()=>{e.handleConnected()}}),(0,Q.jsxs)(`section`,{"aria-labelledby":`site-traffic-heading`,children:[(0,Q.jsx)(Au,{id:`site-traffic-heading`,title:`Site traffic`,tooltip:e.overview?jf.siteTrafficTooltip:d?`${jf.siteTrafficFallbackTooltip} Data covers ${d}.`:jf.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)(J,{variant:`outline`,size:`sm`,disabled:a,onClick:Mi(s),children:[(0,Q.jsx)(g,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),a?`Syncing…`:`Sync`]}),(0,Q.jsxs)(J,{variant:`ghost`,size:`sm`,className:`text-negative-400 hover:text-negative`,disabled:o,onClick:Mi(c),children:[(0,Q.jsx)(h,{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 qf({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=jl({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=>Ol(e.landingPage),pageSize:kf}),u=jl({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:Df,pageSize:Of}),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?Pf(n.windowStart,n.windowEnd):null,h=n?.channelBreakdown,g=n?.paidAiSessionsBySession??0,_=n?.aiEngines??[],v=n?.socialPlatforms??[],y=v[0]??null,b=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)(Au,{id:`traffic-by-channel-heading`,title:`Traffic by channel`,tooltip:jf.channelTooltip,meta:m}),(0,Q.jsx)(Pu,{label:`Sessions by channel`,items:[{label:`Organic search`,value:h.organic.sharePctDisplay,detail:`${h.organic.sessions.toLocaleString()} sessions`,tooltip:jf.organicTooltip},{label:`Social`,value:h.social.sharePctDisplay,detail:`${h.social.sessions.toLocaleString()} sessions`,tooltip:jf.socialTooltip},{label:`Direct`,value:h.direct.sharePctDisplay,detail:`${h.direct.sessions.toLocaleString()} sessions`,tooltip:jf.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:jf.aiTooltip},{label:`Other channels`,value:h.other.sharePctDisplay,detail:`${h.other.sessions.toLocaleString()} sessions`,tooltip:jf.otherTooltip}]}),(0,Q.jsxs)(ju,{children:[(0,Q.jsx)(Mu,{label:jf.aiChartLabel,meta:r.days.length>0?Jf(r.totalSessions,`session`):jf.noneInPeriod,children:r.days.length>0?(0,Q.jsx)(Vu,{input:r.byEngine,baseline:d,baselineLabel:`Total sessions`,label:jf.aiChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jf.noAiReferrals})}),(0,Q.jsx)(Mu,{label:`Where AI visitors came from`,meta:_.length>0?`${Jf(_.filter(e=>e.engine!==null).length,`engine`)} · ${Jf(n.aiReferrals.length,`source`)}`:jf.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)(zu,{groups:_,groupLabel:`Engine`,caption:`AI referral sessions by engine`,childColumns:zf,childRowKey:e=>`${e.source}:${e.medium}:${e.sourceDimension}:${e.trafficClass}`,renderChildCells:e=>(0,Q.jsx)(Hf,{row:e}),pinLast:Vf})}),(0,Q.jsx)(X,{text:jf.aiEnginesTooltip})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jf.noAiReferrals})}),(0,Q.jsx)(Mu,{label:`Pages AI visitors landed on`,meta:b??jf.noneInPeriod,children:n.aiReferralLandingPages.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ml,{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)(Fu,{label:`Landing page`,sortKey:`landingPage`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(Fu,{label:`Source`,sortKey:`source`,current:s.key,dir:s.dir,onSort:p,align:`left`}),(0,Q.jsx)(Iu,{label:`Attribution`,align:`left`}),(0,Q.jsx)(Fu,{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)(ip,{row:e},`${e.landingPage}:${e.source}:${e.medium}:${e.sourceDimension}`))})]})}),(0,Q.jsx)(Nl,{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)(J,{variant:`outline`,size:`sm`,onClick:()=>u.setQuery(``),children:`Clear filter`})]})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jf.noAiLandingPages})})]})]}),(0,Q.jsx)(`div`,{className:`page-section-divider`}),(0,Q.jsxs)(`section`,{"aria-labelledby":`social-heading`,children:[(0,Q.jsx)(Au,{id:`social-heading`,title:`Social`,tooltip:jf.socialTooltip2,meta:m}),(0,Q.jsx)(Pu,{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:jf.platformsTooltip},{label:`Paid social`,value:(n.paidSocialSessions??0).toLocaleString(),detail:`${$e(n.paidSocialShare??0)} of social`,tooltip:jf.paidSocialTooltip},{label:`Top platform`,value:y?.label??`None`,detail:y?`${y.sessions.toLocaleString()} sessions`:void 0}]}),(0,Q.jsxs)(ju,{children:[(0,Q.jsx)(Mu,{label:jf.socialChartLabel,meta:v.length>0?Jf(n.socialSessions,`session`):jf.noneInPeriod,children:v.length>0?(0,Q.jsx)(Vu,{input:n.socialPlatformDaily,label:jf.socialChartLabel}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jf.noSocial})}),(0,Q.jsx)(Mu,{label:`Social platforms`,meta:v.length>0?`${Jf(v.length,`platform`)} · ${Jf(n.socialReferrals.length,`source`)}`:jf.noneInPeriod,children:v.length>0?(0,Q.jsx)(zu,{groups:v,groupLabel:`Platform`,caption:`Social sessions by platform`,childColumns:Bf,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,Q.jsx)(Uf,{row:e})}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:jf.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)(Au,{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)(Ml,{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)(Fu,{label:`Landing page`,sortKey:`landingPage`,current:a.key,dir:a.dir,onSort:f,align:`left`}),(0,Q.jsx)(Fu,{label:`Sessions`,sortKey:`sessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(Fu,{label:`Organic`,sortKey:`organicSessions`,current:a.key,dir:a.dir,onSort:f,align:`right`}),(0,Q.jsx)(Iu,{label:`Organic share`,align:`right`})]})}),(0,Q.jsx)(`tbody`,{children:l.rows.map(e=>(0,Q.jsx)(rp,{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)(Nl,{page:l.page,pageSize:l.pageSize,visibleRows:l.rows.length,totalRows:l.totalRows,onPageChange:l.setPage,itemLabel:l.hasQuery?`matches`:`pages`})]})]}),(0,Q.jsx)(tp,{projectName:t}),(0,Q.jsx)(`p`,{className:`mt-6 text-copy-13 text-secondary`,children:n?.lastSyncedAt?`Last synced ${Mf(n.lastSyncedAt)}`:`Never synced`})]})}function Jf(e,t){return`${e.toLocaleString()} ${e===1?t:`${t}s`}`}var Yf=25,Xf=`n/a`,Zf={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 Qf(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 $f(e){return e===null?Xf:e.toFixed(1)}function ep(e){return e===null?Xf:$e(e)}function tp({projectName:e}){let[t,n]=(0,Z.useState)(`28d`),[r,i]=(0,Z.useState)(`clicks`),[a,o]=(0,Z.useState)(`desc`),s=U({...Gi({client:q,path:{name:e},query:{window:t,limit:zn}}),staleTime:Li}),c=s.data,l=jl({rows:(0,Z.useMemo)(()=>[...c?.rows??[]].sort((e,t)=>{let n=Qf(e,r),i=Qf(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=>Ol(Jt(e.landingPage)),pageSize:Yf});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=!G()&&!tt();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:Zf.heading}),(0,Q.jsx)(X,{text:Zf.tooltip})]}),c?.windowStart&&c.windowEnd&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[we(c.windowStart),` to `,we(c.windowEnd),c.timeZone?` (${c.timeZone})`:``]})]}),(0,Q.jsx)(ru,{windows:ze,value:t,onChange:e=>{l.setPage(1),n(e)},label:Zf.windowLabel})]}),s.isPending?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary py-6 text-center`,children:Zf.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:Zf.loadError}),(0,Q.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>{s.refetch()},children:Zf.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)(Y,{tone:`caution`,children:Zf.notLinkedBadge}),(0,Q.jsx)(X,{text:Zf.notLinked(c.searchConsoleLink?.searchConsoleImpressions??0)})]}),c.status===`error`&&(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,Q.jsx)(Y,{tone:`negative`,children:Zf.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)(Y,{tone:`caution`,children:Zf.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)(Y,{tone:`caution`,children:Zf.thresholdedBadge}),(0,Q.jsx)(X,{text:Zf.thresholded})]}),c.status!==`ready`&&d&&c.syncedAt&&(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[Zf.previousSnapshot,` `,Mf(c.syncedAt),`.`]}),c.status===`unavailable`&&d&&(0,Q.jsx)(`p`,{className:`w-full text-copy-14 text-secondary`,children:Zf.unavailableAction})]}),d?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Ml,{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)(Fu,{label:`Landing page`,sortKey:`landingPage`,current:r,dir:a,onSort:u,align:`left`}),(0,Q.jsx)(Fu,{label:`Clicks`,sortKey:`clicks`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(Fu,{label:`Impressions`,sortKey:`impressions`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(Fu,{label:`CTR`,sortKey:`ctr`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(Fu,{label:`Avg. position`,sortKey:`position`,current:r,dir:a,onSort:u,align:`right`}),(0,Q.jsx)(Fu,{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:[Zf.totalLabel,` `,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:Zf.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:ep(d.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:$f(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:Jt(e.landingPage),children:Jt(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:ep(e.organicGoogleSearchClickThroughRate)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:$f(e.organicGoogleSearchAveragePosition)}),(0,Q.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.activeUsers.toLocaleString()})]},e.landingPage))]})]})}),!ge(d)&&!f&&(0,Q.jsxs)(`div`,{className:`text-label-14 text-secondary mt-3 space-y-1`,children:[(0,Q.jsx)(`p`,{children:Zf.noSearchTraffic}),(0,Q.jsx)(`p`,{children:c.searchConsoleLink?.state===`no-search-data`?Zf.noSearchTrafficConfirmed:Zf.noSearchTrafficAction})]}),l.totalRows===0&&l.hasQuery&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-3`,children:c.totalRows>c.rows.length?Zf.noFilterMatchInLoaded(c.rows.length):Zf.noFilterMatch}),(0,Q.jsx)(Nl,{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 `,Mf(c.syncedAt)]})]}):(0,Q.jsx)(rs,{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:Zf.unavailable}),(0,Q.jsx)(`p`,{children:Zf.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:Zf.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:Zf.neverSynced}),p&&(0,Q.jsx)(`p`,{children:Zf.neverSyncedAction})]})})]})]})]})}function np({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 nr(e,{propertyId:n.trim(),keyJson:o});try{await En(e)}catch{}t()}catch(e){d(e instanceof Error?e.message:`Failed to connect GA4`)}finally{l(!1)}}}return(0,Q.jsxs)(rs,{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)(J,{variant:`default`,size:`sm`,disabled:c||!n.trim()||!o,onClick:Mi(m),children:c?`Connecting & syncing…`:`Connect GA4`})]})}function rp({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:$e(e.organicShare)})]})}function ip({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)(Al,{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:Rf[e.sourceDimension]??``,children:Lf[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 ap=new Set([`gbp-listing-discrepancy`,`gbp-lodging-gap`,`gbp-cta-gap`,`gbp-metric-drop`,`gbp-keyword-drop`]);function op({projectName:e,projectId:t}){let n=R(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(null),[s,c]=(0,Z.useState)(!1),l=U(so({client:q,path:{name:e}})),u=l.data?.find(e=>e.connectionType===`gbp`),d=!!u,f=r?{locationName:r}:void 0,p=U({...ra({client:q,path:{name:e}}),enabled:d}),m=U({...Ga({client:q,path:{name:e},query:f}),enabled:d}),h=U({...Va({client:q,path:{name:e},query:f}),enabled:d}),g=U({...fa({client:q,path:{name:e},query:f}),enabled:d}),_=U({...Po({client:q,path:{name:e},query:f}),enabled:d}),v=U({...ua({client:q,path:{name:e},query:f}),enabled:d}),y=U({queryKey:[`gbp-section-insights`,e],queryFn:()=>Fe(e),enabled:d});function b(){Pi(n,`gbp`)}let x=re({...Yi(),onSuccess:n=>{ks({id:n.runId,projectId:t,kind:Ct[`gbp-sync`],projectLabel:e,sourceAction:`gbp-sync`}),Ni({title:`Business Profile sync started`,detail:`${e} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`gbp-sync:${e}`,dedupeMode:`replace`})}}),S=(0,Z.useSyncExternalStore)(Ts,tc,tc),C=Object.values(S.runs).some(e=>e.kind===Ct[`gbp-sync`]&&e.projectId===t),w=x.isPending||C,T=re({...ca(),onSuccess:()=>b()});if((0,Z.useEffect)(()=>{if(!r||!p.data)return;let e=p.data.locations.filter(e=>e.selected);(e.length<=1||!e.some(e=>e.locationName===r))&&i(null)},[r,p.data]),(0,Z.useEffect)(()=>{a&&p.data&&((r?[r]:p.data.locations.filter(e=>e.selected).map(e=>e.locationName)).includes(a)||o(null))},[a,p.data,r]),l.isLoading)return null;if(!u){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`]})]})}];return(0,Q.jsx)(`section`,{className:`page-section`,children:(0,Q.jsxs)(rs,{className:`surface-card`,children:[(0,Q.jsx)(`h2`,{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.`}),(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`}),(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))})]})]})})}let E=m.data,D=p.data?.locations??[],O=D.filter(e=>e.selected),k=h.data?.keywords??[],A=g.data?.lodging??[],j=_.data?.placeActions??[],M=v.data?.places??[],N=D.length>0?D[0].accountName:u.domain,P=r?D.find(e=>e.locationName===r)?.displayName??null:null,F=r?D.filter(e=>e.locationName===r):O,I=new Set(F.map(e=>e.locationName)),L=A.filter(e=>I.has(e.locationName)),z=j.filter(e=>I.has(e.locationName)),B=M.filter(e=>I.has(e.locationName)),ee=new Set(O.map(e=>e.locationName)),te=r?k:k.filter(e=>ee.has(e.locationName)),ne=!r&&O.length>1,V=(y.data??[]).filter(e=>!e.dismissed&&ap.has(e.type)&&(!P||e.query===P||e.query===r||e.title.startsWith(P)));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)(Y,{tone:`positive`,children:`Connected`}),!G()&&(0,Q.jsx)(Rr,{type:`button`,variant:`outline`,size:`sm`,disabled:w,onClick:()=>x.mutate({client:q,path:{name:e},body:{}}),children:w?`Syncing…`:`Sync`})]})]}),(0,Q.jsxs)(`p`,{className:`mb-4 text-copy-13 text-muted`,children:[N?(0,Q.jsxs)(Q.Fragment,{children:[`Account `,(0,Q.jsx)(`span`,{className:`font-mono text-secondary`,children:N}),` · `]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:`Loading locations…`]}),O.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`}),O.map(e=>(0,Q.jsx)(`option`,{value:e.locationName,children:e.displayName},e.id))]})]}),O.length===0?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-muted`,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:[V.length>0&&(0,Q.jsxs)(`div`,{className:`mb-6 grid gap-2`,children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Needs attention`}),V.map(e=>(0,Q.jsx)(`div`,{className:[`surface-card insight-card`,Cp(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))]}),E&&(0,Q.jsx)(jp,{performance:E.performance,freshness:E.freshness,timeseries:E.timeseries}),E?.profileCompleteness&&(0,Q.jsx)(sp,{summary:E.profileCompleteness}),F.length>0&&(0,Q.jsx)(cp,{locations:F,lodging:L,places:B,placeActions:z,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`}),h.data&&h.data.total>0&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-faint`,children:[$e(h.data.thresholdedPct,Lt.percent),` privacy-thresholded`]})]}),te.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No keyword impressions stored yet.`}):(0,Q.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-left`,children:`Search term`}),ne&&(0,Q.jsx)(`th`,{className:`text-left`,children:`Location`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,Q.jsx)(`th`,{className:`text-right`,children:`Window`})]})}),(0,Q.jsx)(`tbody`,{children:te.slice(0,25).map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-neutral`,children:e.keyword}),ne&&(0,Q.jsx)(`td`,{className:`text-muted`,children:D.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 (`,D.length,`)`]}),s&&(0,Q.jsx)(`div`,{className:`mt-3`,children:D.length===0?(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`}),!G()&&(0,Q.jsx)(`th`,{className:`text-right`,children:`Action`})]})}),(0,Q.jsx)(`tbody`,{children:D.map(t=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-strong`,children:t.displayName}),(0,Q.jsx)(`td`,{className:`text-muted`,children:t.storefrontAddress??`—`}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Y,{tone:t.selected?`positive`:`neutral`,children:t.selected?`Tracked`:`Not tracked`})}),!G()&&(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(Rr,{type:`button`,variant:`outline`,size:`sm`,disabled:T.isPending,onClick:()=>T.mutate({client:q,path:{name:e,locationName:t.locationName},body:{selected:!t.selected}}),children:t.selected?`Untrack`:`Track`})})]},t.id))})]})})]})]})})}function sp({summary:e}){if(e.locationCount===0)return null;let t=e.locationCount,n=[{label:`Description`,value:`${e.withDescription}/${t}`,tone:xp(e.withDescription,t,`caution`)},{label:`Hours`,value:`${e.withHours}/${t}`,tone:xp(e.withHours,t,`caution`)},{label:`Phone`,value:`${e.withPrimaryPhone}/${t}`,tone:xp(e.withPrimaryPhone,t,`caution`)},{label:`Service area`,value:`${e.withServiceArea}/${t}`,tone:xp(e.withServiceArea,t,`neutral`)},{label:`Secondary categories`,value:`${e.withSecondaryCategories}/${t}`,detail:`${e.secondaryCategoryTotal} total`,tone:xp(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 ${Sp(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 cp({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:G()?`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)(Y,{tone:e.selected?`positive`:`neutral`,children:e.selected?`Tracked`:`Not tracked`}),e.openStatus&&e.openStatus!==`OPEN`&&(0,Q.jsx)(Y,{tone:e.openStatus===`CLOSED_PERMANENTLY`?`negative`:`caution`,children:Tp(e.openStatus)})]})]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(up,{location:e})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(dp,{lodging:t})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(pp,{place:n,mapsUri:e.mapsUri})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(hp,{actions:r})}),(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(J,{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)(vp,{location:e,lodging:t,place:n,placeActions:r})})})]},e.id)})})]})})]})}function lp(e){return[{label:`Description`,tone:wp(e.description)?`positive`:`neutral`,value:wp(e.description)?`set`:`not returned`},{label:`Hours`,tone:e.regularHours?`positive`:`neutral`,value:e.regularHours?`set`:`not returned`},{label:`Phone`,tone:wp(e.primaryPhone)?`positive`:`neutral`,value:wp(e.primaryPhone)?`set`:`not returned`},{label:`Website`,tone:wp(e.websiteUri)?`positive`:`neutral`,value:wp(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 up({location:e}){let t=lp(e);return(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>(0,Q.jsxs)(Y,{tone:e.tone,children:[e.label,` `,e.value]},e.label))})}function dp({lodging:e}){return(0,Q.jsx)(_p,{...fp(e)})}function fp(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 pp({place:e,mapsUri:t}){return(0,Q.jsx)(_p,{...mp(e,t)})}function mp(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 hp({actions:e}){return(0,Q.jsx)(_p,{...gp(e)})}function gp(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 _p({tone:e,label:t,detail:n}){return(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(Y,{tone:e,children:t}),(0,Q.jsx)(`p`,{className:`mt-1.5 text-copy-13 text-faint`,children:n})]})}function vp({location:e,lodging:t,place:n,placeActions:r}){let i=t?kp(t.attributes):[];return(0,Q.jsxs)(`div`,{className:`grid gap-5 text-label-12 lg:grid-cols-3`,children:[(0,Q.jsxs)(yp,{title:`Owner profile · Business Information`,children:[(0,Q.jsx)(bp,{label:`Primary category`,value:e.primaryCategoryDisplayName??`Not returned`}),(0,Q.jsx)(bp,{label:`Secondary categories`,value:e.additionalCategories.length>0?e.additionalCategories.join(`, `):`Not returned`}),(0,Q.jsx)(bp,{label:`Description`,value:wp(e.description)?e.description:`Not returned`}),(0,Q.jsx)(bp,{label:`Hours`,value:e.regularHours?`Returned by Google`:`Not returned`}),(0,Q.jsx)(bp,{label:`Service area`,value:e.serviceArea?`Returned by Google`:`Not returned`}),(0,Q.jsx)(bp,{label:`Phone`,value:e.primaryPhone??`Not returned`}),(0,Q.jsx)(bp,{label:`Website`,value:e.websiteUri??`Not returned`}),(0,Q.jsx)(bp,{label:`Open status`,value:Tp(e.openStatus)}),(0,Q.jsx)(bp,{label:`Opening date`,value:e.openingDate??`Not returned`})]}),(0,Q.jsx)(yp,{title:`Hotel data · Lodging API`,children:t?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(bp,{label:`Last checked`,value:Op(t.syncedAt)}),(0,Q.jsx)(bp,{label:`Groups returned`,value:String(t.populatedGroupCount)}),(0,Q.jsx)(bp,{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)(yp,{title:`Public listing + CTAs`,children:[n?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(bp,{label:`Places tier`,value:n.tier}),(0,Q.jsx)(bp,{label:`Last checked`,value:Op(n.syncedAt)}),(0,Q.jsx)(bp,{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:[Ep(e.placeActionType),e.isPreferred?` · preferred`:``]}),(0,Q.jsxs)(`span`,{className:`text-faint`,children:[Ep(e.providerType),e.uri?` · ${Dp(e.uri)}`:``]})]},e.placeActionLinkName))})})]})]})}function yp({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 bp({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 xp(e,t,n){return e===t?`positive`:e===0?n:`caution`}function Sp(e){switch(e){case`positive`:return`text-positive`;case`caution`:return`text-caution`;case`negative`:return`text-negative`;case`neutral`:return`text-neutral`}}function Cp(e){return e===`critical`||e===`high`?`insight-card-negative`:e===`medium`?`insight-card-caution`:``}function wp(e){return typeof e==`string`&&e.trim().length>0}function Tp(e){return e?Ep(e):`Not returned`}function Ep(e){return e?e.toLowerCase().split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `):`Unknown`}function Dp(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function Op(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}function kp(e){return Object.entries(e).filter(([e,t])=>e!==`name`&&e!==`metadata`&&Ap(t)).map(([e])=>Ep(e.replace(/([a-z])([A-Z])/g,`$1_$2`)))}function Ap(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e!=`object`||Object.keys(e).length>0}function jp({performance:e,freshness:t,timeseries:n}){let r=e.totals,i=Tn.filter(e=>(r[e]??0)>0),a=on.filter(e=>(r[e]??0)>0),o=Object.keys(r).filter(e=>(r[e]??0)>0&&tn(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 ${yi(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)(Mp,{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:[Mt(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)(Mp,{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=>Mt(e)).join(`, `)]})]})}function Mp({data:e,metrics:t,kind:n,firstPending:r,lastDate:i}){return(0,Q.jsx)(`div`,{className:`h-48 w-full`,children:(0,Q.jsx)(ce,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(pe,{data:e,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ie,{stroke:wi,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`date`,tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:fi,minTickGap:24}),(0,Q.jsx)(de,{tick:xi,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,Q.jsx)(ae,{...Ti,labelFormatter:yi,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),Mt(String(t??``))]}),(0,Q.jsx)(ue,{wrapperStyle:{fontSize:12,color:gi.text},formatter:e=>Mt(e)}),r&&i&&(0,Q.jsx)(se,{x1:r,x2:i,fill:gi.surface,fillOpacity:.55,stroke:`none`,label:{value:`pending`,position:`insideTopRight`,fill:gi.textDim,fontSize:12}}),t.map((e,t)=>n===`line`?(0,Q.jsx)(fe,{type:`monotone`,dataKey:e,stroke:li[t%li.length],strokeWidth:2,dot:!1,isAnimationActive:!1},e):(0,Q.jsx)(le,{type:`monotone`,dataKey:e,stackId:`reach`,stroke:li[t%li.length],fill:li[t%li.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},e))]})})})}var Np=25;function Pp(e){return typeof window>`u`?e:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,``)??``}${e}`}function Fp(e){return e.toLocaleString()}function Ip(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 Lp(e){let t=e.filter(e=>e.kind===Ct[`backlink-extract`]&&!Cs(e.status));return t.length===0?null:t.reduce((e,t)=>e.createdAt>t.createdAt?e:t)}function Rp(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 zp({projectName:e}){let t=tt(),[n,r]=(0,Z.useState)(null),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(null),[u,d]=(0,Z.useState)(null),[f,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,c]=await Promise.all([yt().catch(()=>null),We(e,{excludeCrawlers:!0}).catch(()=>null),Le(e,{limit:Np,offset:b,excludeCrawlers:!0}).catch(e=>{if(e instanceof Pt&&e.code===`NOT_FOUND`)return null;throw e}),Mn(e,{surface:cn.backlinks}).catch(()=>null),Ve(e).catch(()=>[])]);d(t),r(n),a(i),s(o);let l=Lp(c);h(l)}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(!f)return;let e=f.id,t=!1,n=async()=>{try{let n=await St(e);if(t)return;Cs(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)}},[f,O]),(0,Z.useEffect)(()=>{if(!f)return;let e=window.setInterval(()=>y(Date.now()),1e3);return()=>window.clearInterval(e)},[f]),(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 Wt(e);h(t)}catch(e){e instanceof Pt&&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 j=i?.rows??[],M=i?.total??0,N=n?.excludedLinkingDomains??0,P=Math.floor(b/Np)+1;return(0,Z.useEffect)(()=>{b>0&&b>=M&&x(0)},[b,M]),(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Backlinks`}),(0,Q.jsx)(`h2`,{children:`Referring domains`})]})}),E&&(0,Q.jsx)(rs,{className:`surface-card p-4 mb-4 bg-negative-soft`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:E})}),f&&(0,Q.jsx)(rs,{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)(Y,{tone:`neutral`,children:f.status}),(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:[Rp(f.startedAt??null,f.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&&!f&&(0,Q.jsx)(rs,{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:Qr(g.error)}):g.status===`failed`?null:(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`Backlinks refreshed from the cached release.`})]})]})}),F()]});function F(){return S?(0,Q.jsx)(rs,{className:`surface-card p-6`,children:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading backlinks…`})}):I()}function I(){let e=n!==null&&n.totalLinkingDomains>0,r=g?.status===`failed`,i=n!==null&&n.totalLinkingDomains===0&&!r,a=u?.status===`ready`,o=u?.status===`failed`,s=u&&(u.status===`downloading`||u.status===`querying`||u.status===`queued`);return e?L((0,Q.jsxs)(Q.Fragment,{children:[!G()&&!t&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:w||f!==null,onClick:Mi(k),children:[(0,Q.jsx)(p,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),f?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsx)(xc,{label:`About re-running`,children:`Re-queries the current release for this project without downloading it again.`})]}),!G()&&!t&&(0,Q.jsx)(J,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Pp(`/backlinks`),children:`Open admin`})})]})):(0,Q.jsx)(rs,{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:[!u&&(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.`}),!G()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Pp(`/backlinks`),children:`Set up backlinks`})})})]}),s&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Sync in progress`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-muted mt-1`,children:[`A workspace release sync is running (`,u.status,u.phaseDetail?` — ${u.phaseDetail}`:``,`). Backlinks will appear here once it finishes.`]}),!G()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(J,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Pp(`/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:u.error??`The workspace release sync failed. Retry from the Backlinks admin page.`}),!G()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Pp(`/backlinks`),children:`Go to Backlinks admin`})})})]}),a&&!s&&!i&&!r&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No backlinks yet for this project`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[`Release `,(0,Q.jsx)(`code`,{className:`text-neutral`,children:u.release}),` is ready. Run an extract for this project.`]}),!G()&&!t&&(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,Q.jsxs)(J,{type:`button`,size:`sm`,disabled:w||f!==null,onClick:Mi(k),children:[(0,Q.jsx)(A,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),f?`Extract running…`:w?`Queuing…`:`Run extract`]}),(0,Q.jsx)(xc,{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.`}),!G()&&!t&&(0,Q.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:(0,Q.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Pp(`/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.`]}),!G()&&!t&&(0,Q.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,Q.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,Q.jsx)(`a`,{href:Pp(`/backlinks`),children:`Go to Backlinks admin`})}),(0,Q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:w||f!==null,onClick:Mi(k),children:[(0,Q.jsx)(A,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),f?`Extract running…`:w?`Queuing…`:`Re-run extract`]}),(0,Q.jsxs)(xc,{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 L(e){if(!n)return null;let t=`release`;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Bp,{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 `,Ip(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)(rs,{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:[j.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:Fp(e.numHosts)})]},e.linkingDomain)),j.length===0&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{className:`px-4 py-4 text-label-14 text-muted`,colSpan:2,children:N>0&&M===0?`Every referring domain in this ${t} was a crawler/proxy host (${N} hidden).`:`No referring domains in this ${t}.`})})]})]})}),(0,Q.jsx)(Nl,{page:P,pageSize:Np,visibleRows:j.length,totalRows:M,onPageChange:e=>x((e-1)*Np)})]}),(0,Q.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:e})]})}}function Bp({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?_u(o.change,o.unit):void 0,series:o?yu(o):void 0,formatValue:i,allowDecimals:o?.unit===`fraction`}},s=[o(`referring-domains`,`Referring domains`,`Unique domains linking to ${e.targetDomain}.`,e.totalLinkingDomains,Fp),o(`hosts`,`Total linking hosts`,`Aggregate linking hosts across referring domains.`,e.totalHosts,Fp),o(`top-10-concentration`,`Top-10 concentration`,`Share of linking hosts from the 10 largest linking domains.`,Number(e.top10HostsShare),e=>$e(e))],c=s.some(uu),l=a.get(`referring-domains`)?.series??[],u=l[0],d=l.at(-1);return(0,Q.jsx)(Tu,{name:`Backlinks figures`,groups:[{key:`backlinks`,label:`Every release`,basis:i?vu(i.figures):void 0,figures:s}],selected:c?[n]:[],onSelect:r,cadence:`release`,span:c&&u&&d?bu(u,d):void 0,emptyChartMessage:t?`One release so far. The trend starts with the next one.`:`Release history could not be loaded.`})}var Vp={[K[`keyword-metrics`]]:`Search demand`,[K[`domain-intelligence`]]:`Domain comparison`,[K[`ranked-keywords`]]:`Searches you rank for`,[K[`market-rankings`]]:`Market rankings`,[K[`competitor-discovery`]]:`Organic competitors`,[K[`keyword-gaps`]]:`Search gaps`},Hp={[Yt.shared]:`Shared`,[Yt.missing]:`Missing`,[Yt.outranked]:`Competitor ahead`},Up=`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.`,Wp={[Gn.queued]:`Queued`,[Gn.running]:`Refreshing`,[Gn.completed]:`Completed`,[Gn.partial]:`Partial results`,[Gn.failed]:`Failed`,[Gn.cancelled]:`Cancelled`,[Gn[`reconciliation-required`]]:`Needs review`},Gp=25,Kp=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:1}),qp=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}),Jp=Intl.DateTimeFormat().resolvedOptions().timeZone,Yp=`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`,Xp=`px-4 py-3 text-right align-top tabular-nums whitespace-nowrap`,Zp=`min-w-56 px-4 py-3 text-left align-top text-label-14`,Qp=`Position on the page, counting maps and other blocks`;function $p(e){return e?.status===Gn.queued||e?.status===Gn.running}function em({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?qp.format(e):Kp.format(e)})}function tm({status:e}){let t=e===Gn.completed?`positive`:e===Gn.failed?`negative`:e===Gn.partial||e===Gn[`reconciliation-required`]?`caution`:`neutral`;return(0,Q.jsx)(Y,{tone:t,children:Wp[e]})}function nm(e){let t=Gt(e).split(`/`).at(-1)??e,n=Xn.safeParse(t.replaceAll(`_`,`-`));return n.success?Vp[n.data]:t.replaceAll(/[-_]/g,` `)}function rm(e){return e===`mobile`?`phone results`:e===`desktop`?`computer results`:`device not specified by source`}function im(e){return e.capabilities.includes(K[`market-rankings`])?`Market locations`:`Location ${e.locationCode}`}function am(e){return e.capabilities.includes(K[`market-rankings`])?`searches`:`tasks`}function om(e){return e.capability!==K[`market-rankings`]||![Gn.queued,Gn.running,Gn.completed].includes(e.status)}function sm(e,t){let n=e.capabilities.includes(K[`market-rankings`]);return`${t} ${t===1?n?`search`:`task`:am(e)}`}function cm(e,t){return Number.isFinite(Date.parse(e))?ut(ft(e,t)):null}var lm={[Gn.failed]:`Latest refresh failed`,[Gn.cancelled]:`Latest refresh cancelled`,[Gn[`reconciliation-required`]]:`Latest refresh needs review`};function um(e,t){let n=e&&e.id!==t?.id?lm[e.status]:void 0;if(e&&n)return{label:n,text:`${n}. ${e.error??`Open Activity for refresh details.`}${t?` Showing the refresh before it.`:``}`};if(!t)return null;if(t.failedTasks>0){let e=`${sm(t,t.failedTasks)} failed`,n=t.capabilities.includes(K[`market-rankings`])?`Their queries show as Failed.`:`Open Activity for details.`;return{label:e,text:`${e}: ${t.failedTasks} of ${sm(t,t.taskCount)} in this refresh returned no results. ${n}`}}return t.status===Gn.partial?{label:`Partial results`,text:`Partial results: ${t.error??`some ${am(t)} returned only part of their results or did not run. Open Activity for details.`}`}:null}function dm({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:nm(e.dataset)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Search engine`}),(0,Q.jsxs)(`dd`,{children:[`Google · `,rm(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:hn(e.collectedAt,Jp)})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`dt`,{className:`text-muted`,children:`Source updated`}),(0,Q.jsx)(`dd`,{children:e.sourceUpdatedAt?we(e.sourceUpdatedAt):`Not supplied`})]})]})}function fm({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)(d,{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)(dm,{source:t})]})]})}function pm({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:Ds(e)}),(0,Q.jsx)(J,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:t,children:`Retry`})]})}function mm({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 hm({projectName:e}){let{isAdmin:t}=ji(),n=te({strict:!1}),r=ee(),i=U(Ha({client:q,path:{name:e}})),a=U(Ja({client:q,path:{name:e}})),s=U({...Vi({client:q,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=n.seoProfileId??s.data?.profileId,p=f?a.data?.profiles.find(e=>e.id===f):n.seoRunId?void 0:a.data?.profiles[0],m=t=>{l(null),r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoProfileId:t,seoRunId:void 0,seoRegion:void 0,seoMarket:void 0,seoShow:void 0,seoSort:void 0,seoQ:void 0})})},h=i.data?.access.canWrite===!0&&!G()&&!tt(),g=()=>{l(null),u.current?.focus()};if((0,Z.useEffect)(()=>{!n.seoProfileId&&p&&r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoProfileId:p.id}),replace:!0})},[r,e,n.seoProfileId,p]),i.error)return(0,Q.jsx)(pm,{error:i.error,retry:()=>{i.refetch()}});if(a.error)return(0,Q.jsx)(pm,{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 _=i.data.available&&i.data.connections.some(e=>e.capabilities.length>0),v=_&&i.data.connections.some(e=>e.capabilities.some(e=>i.data.scopes.some(t=>t.capabilities?.includes(e)??!0))),y=p&&i.data.scopes.find(e=>e.kind===p.scope.kind&&e.key===(p.scope.key??null)),b=t&&!G()&&!tt()?(0,Q.jsx)(J,{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;return(0,Q.jsxs)(`section`,{"aria-label":`SEO`,className:`min-w-0 space-y-5`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:`SEO`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Search demand and organic rankings.`})]}),h&&v&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[p&&(0,Q.jsx)(J,{variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:e=>{u.current=e.currentTarget,l({profile:p,id:p.id})},children:`Edit profile`}),(0,Q.jsxs)(J,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:e=>{u.current=e.currentTarget,l({id:crypto.randomUUID()})},children:[(0,Q.jsx)(o,{"aria-hidden":`true`,className:`size-4`}),`New profile`]})]})]}),a.data.profiles.length>0&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-5 gap-y-3 border-y border-subtle py-3`,children:[(0,Q.jsxs)(`label`,{className:`flex min-w-0 flex-1 items-center gap-3 sm:flex-none`,children:[(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`Profile`}),(0,Q.jsxs)(`select`,{ref:d,"aria-label":`SEO profile`,value:p?.id??``,onChange:e=>m(e.target.value),className:`${Yp} min-w-0 sm:w-64`,children:[!p&&(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))]})]}),p&&(0,Q.jsxs)(`div`,{className:`min-w-0 text-label-13 text-secondary`,children:[(0,Q.jsx)(`p`,{className:`break-words text-copy-13-strong text-primary`,children:y?.label??`${p.scope.kind}${p.scope.key?`: ${p.scope.key}`:``}`}),(0,Q.jsxs)(`p`,{children:[p.rankings?`${p.rankings.locations.length} search location${p.rankings.locations.length===1?``:`s`}`:`Location ${p.locationCode}`,` · `,p.languageCode]})]})]}),c&&(0,Q.jsx)(Qm,{projectName:e,context:i.data,profile:c.profile,id:c.id,onClose:g,onSaved:e=>{m(e),requestAnimationFrame(()=>d.current?.focus())}},c.id),!tt()&&!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)(pm,{error:s.error,retry:()=>{s.refetch()}}),p?(0,Q.jsx)(J,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:()=>m(p.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…`}):p&&s.data&&s.data.profileId!==p.id?(0,Q.jsxs)(mm,{title:`Refresh belongs to another profile`,children:[`Choose the refresh’s profile, or return to the selected profile’s latest data.`,(0,Q.jsx)(J,{variant:`secondary`,className:`mt-4 pointer-coarse:min-h-11`,onClick:()=>m(p.id),children:`View latest data`})]}):p?(0,Q.jsx)(gm,{projectName:e,profile:p,context:i.data,selectedRunId:n.seoRunId,onLatest:()=>m(p.id)},`${p.id}:${p.revision}:${n.seoRunId??``}`):!v&&a.data.profiles.length===0?(0,Q.jsx)(mm,{title:_?`SEO scope unavailable`:`Configure an SEO data provider`,action:_?void 0:b,children:_?i.data.scopes.find(e=>e.reason)?.reason??`No datasets are available for this project’s measurement scopes.`:b?`SEO sources are configured on the Canonry server.`:`Ask your Canonry administrator to connect an SEO data source.`}):f?(0,Q.jsx)(mm,{title:`Profile unavailable`,children:`This saved profile is no longer available. Select another profile to view its data.`}):!c&&(0,Q.jsx)(mm,{title:`No SEO data yet`,children:h?`Create a profile to choose the scope, source, and searches to measure.`:`An SEO profile is needed before data can be collected.`})]})}function gm({projectName:e,profile:t,context:n,selectedRunId:r,onLatest:i}){let a=R(),[o,s]=(0,Z.useState)(r?`activity`:t.capabilities.includes(K[`ranked-keywords`])?K[`ranked-keywords`]:t.capabilities.at(0)??`activity`),[l,u]=(0,Z.useState)(null),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m={name:e},h=U({...Wa({client:q,path:m,query:{profileId:t.id,runId:r}}),refetchInterval:e=>$p(e.state.data?.latestRun)?2e3:!1}),_=re({..._a({client:q}),meta:{skipGlobalErrorToast:!0}}),v=re({...Ea({client:q}),meta:{skipGlobalErrorToast:!0}}),y=h.data?.latestRun,b=h.data?.evidenceRun,x=h.data?.evidenceRun?.capabilities??t.capabilities,S=o===`activity`||x.includes(o)?o:x.at(0)??`activity`,C=$p(y),w=_.isPending||v.isPending,T=n.access.canRun&&!G()&&!tt(),E=n.connections.find(e=>e.id===t.connectionId),D=n.scopes.find(e=>e.kind===t.scope.kind&&e.key===(t.scope.key??null)),O=U({...qi({client:q,path:m,query:{kind:Ee[`seo-sync`]}}),retry:!1}),k=!O.isError&&O.data?.enabled&&O.data.nextRunAt?O.data.nextRunAt:null,A=k?cm(k,O.data?.timezone??`UTC`):null,j=b?.finishedAt&&(b.status===Gn.completed||b.status===Gn.partial)?cm(b.finishedAt,Jp):null,M=C?null:um(y,b);return(0,Z.useEffect)(()=>{y&&($p(y)?p.current=y.id:p.current===y.id&&(p.current=null,Pi(a,`seo`,{projectName:e,profileId:t.id})))},[y,t.id,e,a]),(0,Q.jsxs)(`div`,{className:`space-y-5`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-label-14 text-secondary`,children:[(0,Q.jsx)(`div`,{"aria-live":`polite`,children:C&&y?(0,Q.jsxs)(`p`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(c,{className:`size-4 animate-spin`,"aria-hidden":`true`}),y.cancelRequested?`Cancellation requested`:Wp[y.status],` · `,y.completedTasks,` of `,y.taskCount,` `,am(y),` completed`]}):(0,Q.jsxs)(`p`,{children:[j&&b?.finishedAt?(0,Q.jsxs)(Q.Fragment,{children:[`Updated `,(0,Q.jsx)(`time`,{dateTime:b.finishedAt,title:hn(b.finishedAt,Jp)??void 0,children:j})]}):`No completed refresh`,A&&k&&(0,Q.jsxs)(Q.Fragment,{children:[` · Next refresh `,(0,Q.jsx)(`time`,{dateTime:k,children:A})]})]})}),M&&(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:M.label,text:M.text})]}),r?(0,Q.jsx)(J,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:i,children:`View latest data`}):T&&(0,Q.jsxs)(J,{className:`pointer-coarse:min-h-11`,disabled:w||C||!n.available||!E,onClick:Mi(async()=>{if(!(!T||r||C||w)){u(null);try{if(!f.current){let e=await _.mutateAsync({path:m,body:{profileId:t.id}});if(e.availability!==kt.ready){u(e.reason??`This profile cannot be refreshed. Review its scope and source.`);return}f.current={quoteToken:e.token,idempotencyKey:crypto.randomUUID()}}let e=await v.mutateAsync({path:m,body:f.current});f.current=null,$p(e)&&(p.current=e.id),await a.fetchQuery(Wa({client:q,path:m,query:{profileId:t.id}}))}catch(e){us(e).code===`VALIDATION_ERROR`&&(f.current=null),u(Ds(e))}}}),children:[(0,Q.jsx)(g,{"aria-hidden":`true`,className:`size-4 ${w?`animate-spin`:``}`}),w?`Starting refresh…`:C?`Refresh in progress`:f.current?`Retry refresh`:`Refresh data`]})]}),l&&(0,Q.jsxs)(`p`,{role:`alert`,className:`rounded-md border border-default p-4 text-copy-14 text-secondary`,children:[l,f.current&&` Retry uses the same request, so it will not start a duplicate refresh.`]}),r&&(0,Q.jsxs)(`p`,{className:`break-all text-copy-13 text-secondary`,children:[`Viewing saved refresh `,r,`.`]}),h.data?.evidenceRun&&h.data.evidenceRun.profileRevision!==t.revision&&(0,Q.jsxs)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:[`Saved data uses profile revision `,h.data.evidenceRun.profileRevision,` · `,im(h.data.evidenceRun),` · `,h.data.evidenceRun.languageCode,`. The current profile has changed.`]}),!tt()&&D&&!D.supported&&(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:D.reason??`This scope is not supported for domain data.`}),h.error?(0,Q.jsx)(pm,{error:h.error,retry:()=>{h.refetch()}}):h.data?.summary&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`p`,{className:`mb-3 break-words text-copy-13 text-secondary`,children:[h.data.summary.target.value,h.data.summary.target.includeSubdomains?` · includes subdomains`:` · exact host`]}),(0,Q.jsxs)(`dl`,{className:`grid grid-cols-1 gap-5 border-b border-subtle pb-5 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-2 text-heading-32 tabular-nums text-heading`,children:(0,Q.jsx)(em,{value:h.data.summary.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-2 text-heading-32 tabular-nums text-heading`,children:(0,Q.jsx)(em,{value:h.data.summary.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. This is not measured site traffic.`})]}),(0,Q.jsx)(`dd`,{className:`mt-2 text-heading-32 tabular-nums text-heading`,children:(0,Q.jsx)(em,{value:h.data.summary.estimatedOrganicTraffic})})]})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-x-5 border-b border-subtle`,"aria-label":`SEO views`,children:[...x,`activity`].map(e=>(0,Q.jsx)(`button`,{type:`button`,"aria-pressed":S===e,className:`min-h-11 border-b-2 text-button-14 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${S===e?`border-strong text-primary`:`border-transparent text-secondary hover:text-primary`}`,onClick:()=>s(e),children:e===`activity`?`Activity`:Vp[e]},e))}),S===`activity`?(0,Q.jsx)(Zm,{projectName:e,profileId:t.id,canRun:T,selectedRunId:r}):h.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`py-8 text-copy-14 text-secondary`,children:`Loading saved data…`}):h.data&&(0,Q.jsx)(_m,{projectName:e,profileId:t.id,runId:h.data.evidenceRunId,view:S,active:C,nextRefresh:A},`${t.id}:${S}:${h.data.evidenceRunId??`empty`}`)]}),(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)(d,{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: `,tt()?`Fictional demo data`:E?.label??`Source unavailable`,`. Google; `,rm(t.rankings?.device??`unspecified`),`.`]}),h.data?.evidenceRun&&(0,Q.jsxs)(`p`,{children:[`Saved evidence: `,h.data.evidenceRun.scope.kind,h.data.evidenceRun.scope.key?` · ${h.data.evidenceRun.scope.key}`:``,h.data.evidenceRun.scope.expectedPlanRevision===void 0?``:` · plan revision ${h.data.evidenceRun.scope.expectedPlanRevision}`,`. `,im(h.data.evidenceRun),` · `,h.data.evidenceRun.languageCode,` · profile revision `,h.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,`.`]}),h.data?.summary&&(0,Q.jsx)(dm,{source:h.data.summary.provenance})]})]})]})}function _m({projectName:e,profileId:t,runId:n,view:r,active:i,nextRefresh:a}){return r===K[`market-rankings`]?n?(0,Q.jsx)(Vm,{projectName:e,profileId:t,runId:n,active:i}):(0,Q.jsx)(mm,{title:`No market rankings yet`,children:a?`First refresh ${a}`:`Refresh this profile to rank its tracked queries in each market.`}):(0,Q.jsx)(vm,{projectName:e,profileId:t,runId:n,view:r,active:i})}function vm({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:q,path:{name:e},query:{profileId:t,runId:n??void 0,limit:Gp,offset:(a-1)*Gp}},m=U({...ka(p),enabled:!!n&&r===K[`ranked-keywords`]}),h=U({...Fo(p),enabled:!!n&&r===K[`keyword-metrics`]}),g=U({...ia(p),enabled:!!n&&r===K[`domain-intelligence`]}),_=U({...Ra({...p,query:{...p.query,sort:l}}),placeholderData:z,enabled:!!n&&r===K[`competitor-discovery`]}),v=U({...pa({...p,query:{...p.query,kind:s||void 0,sort:d}}),placeholderData:z,enabled:!!n&&r===K[`keyword-gaps`]}),y=r===K[`ranked-keywords`]?m:r===K[`keyword-metrics`]?h:r===K[`competitor-discovery`]?_:r===K[`keyword-gaps`]?v:g;return n?(0,Q.jsxs)(`div`,{className:`space-y-3 pt-4`,children:[r===K[`keyword-gaps`]&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsxs)(`label`,{className:`flex items-center gap-3 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Show`}),(0,Q.jsxs)(`select`,{"aria-label":`Show search gaps`,className:`${Yp} w-auto`,value:s,onChange:e=>{c(e.target.value),o(1)},children:[(0,Q.jsx)(`option`,{value:``,children:`All comparisons`}),(0,Q.jsx)(`option`,{value:Yt.missing,children:`Missing`}),(0,Q.jsx)(`option`,{value:Yt.shared,children:`Shared`}),(0,Q.jsx)(`option`,{value:Yt.outranked,children:`Competitor ahead`})]})]}),(0,Q.jsx)(X,{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===K[`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)(pm,{error:y.error,retry:()=>{y.refetch()}}):y.data?y.data.items.length===0?(0,Q.jsx)(mm,{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 Activity before changing the profile.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`relative overflow-x-auto material-base`,role:`region`,"aria-label":`${Vp[r]} table`,"aria-busy":y.isFetching,tabIndex:0,children:[r===K[`ranked-keywords`]&&m.data&&(0,Q.jsx)(Cm,{rows:m.data.items}),r===K[`keyword-metrics`]&&h.data&&(0,Q.jsx)(wm,{rows:h.data.items}),r===K[`domain-intelligence`]&&g.data&&(0,Q.jsx)(Tm,{rows:g.data.items}),r===K[`competitor-discovery`]&&_.data&&(0,Q.jsx)(xm,{rows:_.data.items,sort:l,onSort:e=>{u(e),o(1)}}),r===K[`keyword-gaps`]&&v.data&&(0,Q.jsx)(Sm,{rows:v.data.items,sort:d,onSort:e=>{f(e),o(1)}})]}),(0,Q.jsx)(Nl,{page:a,pageSize:Gp,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 `,Vp[r].toLowerCase(),`…`]})]}):(0,Q.jsxs)(mm,{title:`No saved data yet`,children:[`Refresh this profile to collect `,Vp[r].toLowerCase(),` for its saved scope.`]})}function ym({value:e}){return e===null?(0,Q.jsx)(em,{value:null}):(0,Q.jsxs)(Q.Fragment,{children:[e>0?`+`:``,Kp.format(e)]})}function bm({label:e,sort:t,ascending:n,descending:r,align:i=`right`,onSort:a,help:o}){return(0,Q.jsx)(Bm,{label:e,align:i,sorted:t===n?`ascending`:t===r?`descending`:null,onSort:()=>a(t===n?r:n),help:o,showUnsorted:!0})}function xm({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)(bm,{label:`Competitor`,align:`left`,sort:t,ascending:he.domain,descending:he[`-domain`],onSort:n}),(0,Q.jsx)(bm,{label:`Shared searches`,sort:t,ascending:he.shared,descending:he[`-shared`],onSort:n}),(0,Q.jsx)(bm,{label:`Avg. position`,sort:t,ascending:he.position,descending:he[`-position`],onSort:n}),(0,Q.jsx)(bm,{label:`Est. organic traffic`,sort:t,ascending:he.traffic,descending:he[`-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:Zp,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:Xp,children:(0,Q.jsx)(em,{value:e.sharedKeywords})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.averagePosition})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(fm,{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)(em,{value:e.organicKeywords})]}),(0,Q.jsxs)(`p`,{children:[`Target: `,e.target.value,` · includes subdomains`]})]})})]},`${e.target.value}:${e.domain}:${t}`))})]})}function Sm({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)(bm,{label:`Search`,align:`left`,sort:t,ascending:Jn.keyword,descending:Jn[`-keyword`],onSort:n}),(0,Q.jsx)(bm,{label:`Comparison`,align:`left`,sort:t,ascending:Jn.kind,descending:Jn[`-kind`],onSort:n}),(0,Q.jsx)(bm,{label:`Your rank`,sort:t,ascending:Jn[`target-rank`],descending:Jn[`-target-rank`],onSort:n}),(0,Q.jsx)(bm,{label:`Competitor rank`,sort:t,ascending:Jn[`competitor-rank`],descending:Jn[`-competitor-rank`],onSort:n}),(0,Q.jsx)(bm,{label:`Rank gap`,sort:t,ascending:Jn[`rank-gap`],descending:Jn[`-rank-gap`],onSort:n,help:Up}),(0,Q.jsx)(bm,{label:`Monthly searches`,sort:t,ascending:Jn.volume,descending:Jn[`-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:Zp,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)(Y,{tone:e.kind===Yt.shared?`neutral`:`caution`,children:Hp[e.kind]})}),(0,Q.jsx)(`td`,{className:Xp,children:e.kind===Yt.missing?(0,Q.jsx)(`span`,{className:`text-secondary`,children:`Not found`}):(0,Q.jsx)(em,{value:e.targetRankOrganic})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.competitorRankOrganic})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(ym,{value:e.rankGap})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(fm,{label:`${e.keyword} against ${e.competitor.value}`,source:e.provenance,children:[(0,Q.jsxs)(`p`,{children:[`Your ranking page: `,e.targetUrl?(0,Q.jsx)(rc,{url:e.targetUrl}):`Not supplied`]}),(0,Q.jsxs)(`p`,{children:[`Competitor’s ranking page: `,e.competitorUrl?(0,Q.jsx)(rc,{url:e.competitorUrl}):`Not supplied`]}),(0,Q.jsxs)(`p`,{children:[`Difficulty /100: `,(0,Q.jsx)(em,{value:e.keywordDifficulty})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(em,{value:e.cpcUsd,currency:!0})]})]})})]},`${e.target.value}:${e.competitor.value}:${e.keyword}:${t}`))})]})}function Cm({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:`${Xp} text-label-13-strong`,children:`Position`}),(0,Q.jsx)(`th`,{className:`${Xp} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Xp} text-label-13-strong`,children:`Est. traffic`}),(0,Q.jsx)(`th`,{className:`${Xp} 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:Zp,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)(Al,{value:e.url??e.target.value})})]}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.rankOrganic})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.estimatedTraffic})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.keywordDifficulty})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsxs)(fm,{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:[Qp,`: `,(0,Q.jsx)(em,{value:e.rankAbsolute})]}),(0,Q.jsxs)(`p`,{children:[`CPC: `,(0,Q.jsx)(em,{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 wm({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:`${Xp} text-label-13-strong`,children:`Monthly searches`}),(0,Q.jsx)(`th`,{className:`${Xp} text-label-13-strong`,children:`CPC`}),(0,Q.jsx)(`th`,{className:`${Xp} 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:`${Zp} text-primary`,children:e.keyword}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.searchVolume})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.cpcUsd,currency:!0})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{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)(fm,{label:e.keyword,source:e.provenance,children:[(0,Q.jsxs)(`p`,{children:[`Ad competition: `,e.adCompetition===null?`Not supplied`:$e(e.adCompetition,Lt.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)(em,{value:e.searchVolume})})]},`${e.year}-${e.month}`))})]})})]},`${e.keyword}:${t}`))})]})}function Tm({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:`${Xp} text-label-13-strong`,children:`Searches ranked for`}),(0,Q.jsx)(`th`,{className:`${Xp} 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:Zp,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:Xp,children:(0,Q.jsx)(em,{value:e.organicKeywords})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.estimatedOrganicTraffic})}),(0,Q.jsx)(`td`,{className:`px-4 align-top`,children:(0,Q.jsx)(fm,{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)(em,{value:e.top1})}),(0,Q.jsx)(`dt`,{children:`Positions 2–3`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(em,{value:e.top2To3})}),(0,Q.jsx)(`dt`,{children:`Positions 4–10`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(em,{value:e.top4To10})}),(0,Q.jsx)(`dt`,{children:`Positions 11–20`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(em,{value:e.top11To20})}),(0,Q.jsx)(`dt`,{children:`Est. traffic value`}),(0,Q.jsx)(`dd`,{children:(0,Q.jsx)(em,{value:e.estimatedOrganicTrafficValueUsd,currency:!0})})]})})})]},`${e.target.value}:${t}`))})]})}var Em=5,Dm=10,Om=`all`;function km(e){return e===Om?Om:Qt.safeParse(e).data??null}var Am={column:`ranks11To20`,descending:!0},jm={3:`sm:grid-cols-3`,4:`sm:grid-cols-4`,5:`sm:grid-cols-5`},Mm=`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`,Nm=`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 Pm(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 Fm(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 Im(e){let t=e.filter(e=>e.kind===Hn.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 Lm(e,t){return e.counts[t]}function Rm(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*(Lm(e,n)-Lm(r,n))||dt(e.label,r.label)||dt(e.key,r.key)}function zm(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 Bm({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:`${Mm} ${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 Vm({projectName:e,profileId:t,runId:n,active:r}){let i=te({strict:!1}),a=ee(),o=i.seoRegion,s=i.seoMarket,c=km(i.seoShow),l=In.safeParse(i.seoSort).data??jn.rank,u=t=>{a({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...t}),replace:!0})},d=(0,Z.useId)(),f=U(Ka({client:q,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)(pm,{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)(Um,{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)(mm,{title:`No rankings here`,children:[`This refresh has no rankings for this `,s===void 0?`region`:`market`,`.`]}):(0,Q.jsx)(mm,{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 Activity before changing the profile.`})]});let y=wt(m,p),b=c??(p.needsWork>0?kn[`needs-work`]:Om),x=h.length>1||h.some(e=>e.kind===Hn.region),S=[`${Kp.format(p.queries)} ${p.queries===1?`query`:`queries`}`,...p.partlyChecked>0?[`${Kp.format(p.partlyChecked)} partly checked`]:[],...p.failed>0?[`${Kp.format(p.failed)} failed`]:[],...p.cancelled>0?[`${Kp.format(p.cancelled)} not searched`]:[]].join(` · `);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:S})]}),(0,Q.jsxs)(`dl`,{className:`grid grid-cols-2 gap-5 border-b border-subtle pb-5 ${jm[y.length+1]??`sm:grid-cols-5`}`,children:[y.map(e=>(0,Q.jsx)(Hm,{label:e.label,help:Pm(e,m),value:p[e.count]},e.count)),(0,Q.jsx)(Hm,{label:`Rival ahead`,help:Fm(m),value:p.rivalAhead,className:`sm:border-l sm:border-subtle sm:pl-5`})]})]}),x&&(0,Q.jsx)(Wm,{projectName:e,groups:h,bands:y},`groups\u0000${g}`),(0,Q.jsx)(Gm,{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===jn.rank?void 0:e}),urlQ:i.seoQ??``,onQ:e=>u({seoQ:e||void 0}),onClear:()=>u({seoShow:Om,seoQ:void 0})},`queries\u0000${g}`)]})}function Hm({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:Kp.format(n)})]})}function Um({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)(H,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoRegion:void 0,seoMarket:void 0}),className:Nm,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)(H,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoMarket:void 0}),className:Nm,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 Wm({projectName:e,groups:t,bands:n}){let r=ee(),[i,a]=(0,Z.useState)(null),[o,s]=(0,Z.useState)(1),c=Im(t),l=(i===null?t:[...t].sort(Rm(i))).slice((o-1)*Em,o*Em),u=i??(n.some(e=>e.count===Am.column)?Am:null),f=[{column:`queries`,label:`Queries`},...n.map(e=>({column:e.count,label:e.label})),{column:`rivalAhead`,label:`Rival ahead`}],p=e=>{let t=i??Am;a(t.column===e?{column:e,descending:!t.descending}:{column:e,descending:e!==`label`}),s(1)},m=e=>u?.column===e?u.descending?`descending`:`ascending`:null,h=e=>e.kind===Hn.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)(Bm,{label:c.label,align:`left`,sorted:m(`label`),onSort:()=>p(`label`)}),f.map(e=>(0,Q.jsx)(Bm,{label:e.label,align:`right`,sorted:m(e.column),onSort:()=>p(e.column)},e.column)),(0,Q.jsx)(`th`,{className:`px-4`,children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Open`})})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:l.map(t=>(0,Q.jsxs)(`tr`,{className:`cursor-pointer hover:bg-surface-hover`,onClick:n=>{n.target.closest(`a, button`)||r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:h(t)})},children:[(0,Q.jsx)(`th`,{scope:`row`,className:`min-w-36 px-4 py-3 text-left align-top text-label-14`,children:(0,Q.jsx)(H,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:h(t),className:`rounded-sm text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:t.label})}),f.map(e=>(0,Q.jsx)(`td`,{className:Xp,children:Kp.format(t.counts[e.column])},e.column)),(0,Q.jsx)(`td`,{className:`px-4 py-3 text-right align-top`,children:(0,Q.jsx)(d,{"aria-hidden":`true`,className:`ml-auto size-4 text-muted`})})]},`${t.kind}:${t.key}`))})]})}),(0,Q.jsx)(Nl,{page:o,pageSize:Em,visibleRows:l.length,totalRows:t.length,onPageChange:s,itemLabel:c.plural,className:`text-label-13 [&_button]:min-h-11`})]})}function Gm({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=zm(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=U({...da({client:q,path:{name:e},query:{profileId:t,runId:n,regionKey:r,marketKey:i,outcome:c===Om?void 0:c,q:v||void 0,sort:u,limit:Dm,offset:(C-1)*Dm}}),placeholderData:z}),T=[{value:kn[`needs-work`],label:`Needs work`,count:a.needsWork},...o.map(e=>({value:e.filter,label:e.label,count:a[e.count]})),{value:kn[`rival-ahead`],label:`Rival ahead`,count:a.rivalAhead},{value:kn[`partly-checked`],label:`Partly checked`,count:a.partlyChecked},{value:kn.failed,label:`Failed`,count:a.failed},{value:kn.cancelled,label:`Not searched`,count:a.cancelled},{value:Om,label:`All`,count:a.queries}],E=[kn[`partly-checked`],kn.failed,kn.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===jn.rank?`ascending`:u===jn[`-rank`]?`descending`:null,A=u===jn.query?`ascending`:u===jn[`-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`:`${Kp.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:`Show`}),(0,Q.jsx)(`select`,{"aria-label":`Show queries`,value:c,onChange:e=>l(e.target.value),className:`${Yp} min-w-0 sm:w-56`,children:D.map(e=>(0,Q.jsxs)(`option`,{value:e.value,children:[e.label,` (`,Kp.format(e.count),`)`]},e.value))})]}),(0,Q.jsx)(Ml,{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)(pm,{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)(J,{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)(Bm,{label:`Query`,align:`left`,sorted:A,onSort:()=>d(u===jn.query?jn[`-query`]:jn.query)}),(0,Q.jsx)(Bm,{label:`Google rank`,align:`right`,sorted:k,onSort:()=>d(u===jn.rank?jn[`-rank`]:jn.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:`${Xp} text-label-13-strong`,children:`Rival rank`}),(0,Q.jsx)(`th`,{className:`${Xp} text-label-13-strong`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Rank gap`,(0,Q.jsx)(X,{text:Up,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)(Km,{row:e,requested:s},`${e.marketKey}\u0000${e.queryId??e.queryText}\u0000${t}`))})]})}),(0,Q.jsx)(Nl,{page:C,pageSize:Dm,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 Km({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:Zp,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:Xp,children:(0,Q.jsx)(Jm,{row:e,requested:t})}),(0,Q.jsx)(`td`,{className:`px-4 py-3 align-top text-label-13`,children:(0,Q.jsx)(Ym,{row:e})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(em,{value:e.topCompetitor?.rankOrganic??null})}),(0,Q.jsx)(`td`,{className:Xp,children:(0,Q.jsx)(ym,{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)(Xm,{row:e,requested:t})})})]})}function qm(e){return e.outcome===dn.failed||e.outcome===dn.cancelled}function Jm({row:e,requested:t}){return e.outcome===dn.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===dn.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===dn[`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 Ym({row:e}){if(qm(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)(Y,{tone:`caution`,children:`Ahead`})]}):(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`None in top `,e.depth]})}function Xm({row:e,requested:t}){let n=`text-muted`,r=`mt-0.5 text-primary`,i=e.outcome===dn.failed?`No result: the search failed`:e.outcome===dn.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)(rc,{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:Qp}),(0,Q.jsx)(`p`,{className:`${r} tabular-nums`,children:(0,Q.jsx)(em,{value:e.rankAbsolute})})]}),e.searchStatus===Ft.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}`]})]}),!qm(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)(dm,{source:e.provenance})})]})}function Zm({projectName:e,profileId:t,canRun:n,selectedRunId:r}){let[i,a]=(0,Z.useState)(r??null),[o,s]=(0,Z.useState)(null),c=U({...oo({client:q,path:{name:e},query:{profileId:t}}),refetchInterval:e=>e.state.data?.runs.some($p)?2e3:!1}),l=U({...Vi({client:q,path:{name:e,id:i??``}}),enabled:!!i,refetchInterval:e=>$p(e.state.data)?2e3:!1}),u=re({...ba({client:q}),meta:{skipGlobalErrorToast:!0}}),d=async t=>{if(n&&!u.isPending){s(null);try{await u.mutateAsync({path:{name:e,id:t}})}catch(e){s(Ds(e))}}};if(c.error)return(0,Q.jsx)(`div`,{className:`py-4`,children:(0,Q.jsx)(pm,{error:c.error,retry:()=>{c.refetch()}})});if(!c.data)return(0,Q.jsx)(`p`,{role:`status`,className:`py-8 text-copy-14 text-secondary`,children:`Loading activity…`});let f=l.data&&!c.data.runs.some(e=>e.id===l.data.id)?[l.data,...c.data.runs]:c.data.runs;return f.length?(0,Q.jsxs)(`div`,{className:`divide-y divide-subtle`,children:[o&&(0,Q.jsx)(`p`,{role:`alert`,className:`py-3 text-copy-14`,children:o}),f.map(e=>(0,Q.jsxs)(`div`,{className:`py-4`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(tm,{status:e.status}),(0,Q.jsx)(`span`,{className:`text-label-14`,children:hn(e.createdAt,Jp)})]}),(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[e.completedTasks,` of `,e.taskCount,` `,am(e),` completed`,e.failedTasks>0?` · ${e.failedTasks} failed`:``]})]}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsxs)(J,{variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-expanded":i===e.id,"aria-controls":`seo-run-${e.id}`,onClick:()=>a(i===e.id?null:e.id),children:[`Details`,(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` for refresh `,e.id]})]}),n&&$p(e)&&(0,Q.jsx)(J,{variant:`secondary`,className:`pointer-coarse:min-h-11`,disabled:u.isPending||e.cancelRequested,onClick:Mi(()=>d(e.id)),children:e.cancelRequested?`Cancellation requested`:`Cancel refresh`})]})]}),i===e.id&&(0,Q.jsxs)(`div`,{id:`seo-run-${e.id}`,className:`mt-4 space-y-3 rounded-md bg-surface p-4 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,` · `,im(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}),l.error?(0,Q.jsx)(pm,{error:l.error,retry:()=>{l.refetch()}}):l.data?l.data.tasks.some(om)&&(0,Q.jsx)(`ul`,{className:`space-y-3`,children:l.data.tasks.filter(om).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:[Vp[e.capability],e.searchText===null?e.target?` · ${e.target.value}`:``:` · “${e.searchText}” from ${e.locationLabel??`its market`}`,e.comparison?` · ${e.comparison.competitor.value} · ${Hp[e.comparison.mode]} searches`:``,e.retried?` · retried once`:``]}),(0,Q.jsx)(tm,{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…`})]})]},e.id))]}):(0,Q.jsx)(mm,{title:`No refreshes yet`,children:`Refresh this profile to collect its first saved results.`})}function Qm({projectName:e,context:t,profile:n,id:r,onClose:i,onSaved:a}){let o=R(),[s,c]=(0,Z.useState)(n?.name??``),[l,u]=(0,Z.useState)(n?.connectionId??t.connections.at(0)?.id??``),[d,f]=(0,Z.useState)(n?.capabilities??[K[`ranked-keywords`]]),[p,m]=(0,Z.useState)(n?.targets??[{kind:Cn.domain,value:``,includeSubdomains:!0}]),[h,g]=(0,Z.useState)(n?.competitors?.map(e=>e.value).join(`
|
|
3
|
+
`)??``),[_,v]=(0,Z.useState)(n?.keywords.join(`
|
|
4
|
+
`)??``),[y,b]=(0,Z.useState)(n?.locationCode.toString()??``),[x,S]=(0,Z.useState)(n?.languageCode??`en`),[C,T]=(0,Z.useState)(n?.limit.toString()??`100`),[E,D]=(0,Z.useState)(n?`${n.scope.kind}:${n.scope.key??``}`:`${Vt.project}:`),[O,k]=(0,Z.useState)(null),A=re({...Ki({client:q}),meta:{skipGlobalErrorToast:!0}}),j=t.connections.find(e=>e.id===l),M=t.scopes.find(e=>`${e.kind}:${e.key??``}`===E),N=j?.capabilities.filter(e=>M?.capabilities?.includes(e)??!0)??[],P=d.filter(e=>N.includes(e)),F=P.includes(K[`keyword-gaps`]),I=F||P.includes(K[`competitor-discovery`]),L=P.some(e=>e!==K[`keyword-metrics`]),z=P.includes(K[`ranked-keywords`])||I,B=(0,Z.useId)(),ee=P.includes(K[`market-rankings`]),te=e=>e===K[`market-rankings`]?!n?.rankings||P.some(e=>e!==K[`market-rankings`]):ee,ne=N.includes(K[`market-rankings`])?n?.rankings?`Market rankings use their own profile.`:`Set up market rankings with the CLI or API.`:null,V=async()=>{if(!t.access.canWrite||G()||tt()||A.isPending)return;if(!M){k(`Choose a measurement scope.`);return}if(I&&p.some(e=>e.kind!==Cn.domain||!e.includeSubdomains)){k(`Organic competitors and search gaps require whole-domain targets including subdomains.`);return}let i={name:s,connectionId:l,capabilities:P,targets:L?p:[],keywords:_.split(`
|
|
5
|
+
`).map(e=>e.trim()).filter(Boolean),locationCode:Number(y),languageCode:x,limit:z?Number(C):n?.limit??100,scope:{kind:M.kind,...M.key?{key:M.key}:{},...M.planRevision===void 0?{}:{expectedPlanRevision:M.planRevision}},...P.includes(K[`market-rankings`])&&n?.rankings?{rankings:n.rankings}:{},...F?{competitors:h.split(`
|
|
6
|
+
`).map(e=>e.trim()).filter(Boolean).map(e=>({kind:Cn.domain,value:e,includeSubdomains:!0}))}:{}},c=Dn.safeParse(i);if(!c.success)k(c.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(` `));else{k(null);try{await A.mutateAsync({path:{name:e,id:r},body:c.data}),await o.fetchQuery(Ja({client:q,path:{name:e}})),a(r)}catch(e){k(Ds(e))}}},H=(e,t)=>m(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:`space-y-5 rounded-md border border-default p-4 sm:p-5`,onSubmit:e=>{e.preventDefault(),V()},children:[(0,Q.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:n?`Edit profile`:`New profile`}),(0,Q.jsx)(J,{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)(w,{className:`size-4`,"aria-hidden":`true`})})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Profile name`}),(0,Q.jsx)(`input`,{className:Yp,required:!0,maxLength:120,value:s,onChange:e=>c(e.target.value),autoFocus:!0})]}),(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:`Source`}),(0,Q.jsxs)(`select`,{className:Yp,required:!0,value:l,onChange:e=>{let n=t.connections.find(t=>t.id===e.target.value);u(e.target.value),f(e=>e.filter(e=>n?.capabilities.includes(e)))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Select a source`}),t.connections.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14 sm:col-span-2`,children:[(0,Q.jsx)(`span`,{children:`Measurement scope`}),(0,Q.jsxs)(`select`,{className:Yp,required:!0,value:M?E:``,onChange:e=>{let n=t.scopes.find(t=>`${t.kind}:${t.key??``}`===e.target.value);D(e.target.value),f(e=>e.filter(e=>n?.capabilities?.includes(e)??!0))},children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Select a scope`}),t.scopes.map(e=>(0,Q.jsx)(`option`,{value:`${e.kind}:${e.key??``}`,children:e.label},`${e.kind}:${e.key}`))]}),M?.reason?(0,Q.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:M.reason}):M&&!M.supported&&(0,Q.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:`Domain data is not supported for this scope.`})]})]}),(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{className:`mb-2 text-label-14`,children:`Collect`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-2`,children:Object.values(K).map(e=>{let t=te(e);return(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:P.includes(e),disabled:!N.includes(e)||t,"aria-describedby":t&&ne?B:void 0,onChange:t=>f(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))}),Vp[e]]},e)})}),M?.capabilities&&(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`Available datasets follow this scope and source. Changing scope clears unsupported selections.`}),ne&&(0,Q.jsx)(`p`,{id:B,className:`mt-1 text-copy-13 text-secondary`,children:ne})]}),L&&(0,Q.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,Q.jsx)(`legend`,{className:`mb-2 text-label-14`,children:`Targets`}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:ee?`Market rankings report the Google rank of one target: one of this project’s own domains.`:I?`Organic competitors and search gaps compare whole domains, including subdomains.`:`Domain comparison requires a domain including its subdomains. Exact hosts are supported only by compatible datasets.`}),p.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:Yp,value:e.value,placeholder:`example.com`,"aria-label":`Target ${t+1}`,onChange:e=>H(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:Yp,"aria-label":`Target ${t+1} kind`,value:e.kind,onChange:e=>H(t,{kind:e.target.value,includeSubdomains:e.target.value===Cn.domain}),children:[(0,Q.jsx)(`option`,{value:Cn.domain,children:`Domain + subdomains`}),(0,Q.jsx)(`option`,{value:Cn.host,children:`Exact host`})]})]}),(0,Q.jsx)(J,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>m(e=>e.filter((e,n)=>n!==t)),"aria-label":`Remove target ${t+1}`,children:`Remove`})]},t)),(0,Q.jsx)(J,{type:`button`,variant:`secondary`,className:`pointer-coarse:min-h-11`,disabled:p.length>=(ee?1:20),onClick:()=>m(e=>[...e,{kind:Cn.domain,value:``,includeSubdomains:!0}]),children:`Add target`})]}),F&&(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:`${Yp} min-h-24`,value:h,onChange:e=>g(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.`})]}),P.includes(K[`keyword-metrics`])&&(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:`${Yp} min-h-28`,value:_,onChange:e=>v(e.target.value),placeholder:`One search per line`}),(0,Q.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:`Up to 700 searches to measure, each at most 10 words and 80 characters.`})]}),(0,Q.jsxs)(`div`,{className:`grid gap-4 ${z?`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:Yp,type:`number`,min:1,step:1,required:!0,value:y,onChange:e=>b(e.target.value)}),(0,Q.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:ee?`Used only when the project has no markets or locations.`:`The source’s location identifier.`})]}),(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:Yp,required:!0,minLength:2,maxLength:10,value:x,onChange:e=>S(e.target.value)})]}),z&&(0,Q.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,Q.jsx)(`span`,{children:I?`Result limit`:`Ranked searches per target`}),(0,Q.jsx)(`input`,{className:Yp,type:`number`,min:1,max:1e3,step:1,required:!0,value:C,onChange:e=>T(e.target.value)}),I&&(0,Q.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:F?`For each gap comparison, shared and missing searches each have this limit. Other datasets use it per target.`:`Maximum rows per target and dataset.`})]})]}),O&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-secondary`,children:O}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(J,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:A.isPending||!j||!P.length,children:A.isPending?`Saving…`:`Save profile`}),(0,Q.jsx)(J,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:i,children:`Cancel`})]})]})}var $m=[{value:`7`,label:`7d`},{value:`30`,label:`30d`},{value:`90`,label:`90d`},{value:`180`,label:`180d`}],eh=[{value:`1`,label:`1h`},{value:`24`,label:`24h`},{value:`168`,label:`7d`},{value:`720`,label:`30d`}],th=20,nh=12,rh=20,ih=50,ah=3,oh=`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`,sh=`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,ch=`inline-flex w-fit cursor-pointer list-none items-center gap-1 rounded text-label-14 text-secondary hover:text-heading ${sh} [&::-webkit-details-marker]:hidden`,lh=`inline-flex items-center gap-1.5 rounded text-left ${sh}`,uh={ai:`AI referral`,search:`Search`,social:`Social`,paid:`Paid`,referral:`Referral`,direct:`Direct`},dh={cloudflare:`Cloudflare`,vercel:`Vercel`,"cloud-run":`Cloud Run`,wordpress:`WordPress`},fh={[bn.matched]:`Matched`,[bn.unmatched]:`No URL match`,[bn.ambiguous]:`Ambiguous URL match`,[bn[`unknown-host`]]:`Host not recorded`,[bn.redacted]:`URL redacted`,[bn[`not-configured`]]:`No Property plan`},ph={[Je.verified]:`text-positive`,[Je.likely_real]:`text-heading`,[Je.unknown]:`text-secondary`},mh=`This project's traffic source logs no IP address, so one person can't be told from another. AI-referred visits are still counted.`,hh=`Each row is everyone on one browser version, so its visits are not one person's.`,gh=(e,t)=>`${e.toLocaleString()} ${t}${e===1?``:`s`}`,_h=e=>e.entryName??uh[e.entryClass],vh=e=>{if(!e.entryName)return e.paid&&e.entryClass!==`paid`?`Paid`:null;let t=e.paid&&e.entryClass!==`paid`?`${uh[e.entryClass]}, paid`:uh[e.entryClass];return t===_h(e)?null:t},yh=e=>ri(e,e),bh=e=>e&&e.toUpperCase()!==`GET`?e.toUpperCase():null;function xh(){let e=te({strict:!1}),t=ee(),n=V({select:e=>e.location.pathname});return{search:e,update:e=>{t({to:n,search:t=>({...t,...e}),replace:!0})}}}function Sh({projectName:e}){let{account:t}=ji(),{search:n,update:r}=xh();if(G()||t?.role===et.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&&(Re(`other`),r({journeyView:e.value===`visitors`?void 0:e.value}))},className:`-mb-px border-b-2 pb-2 text-label-14 transition-colors ${sh} ${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)(Oh,{projectName:e},`visitors:${e}`):(0,Q.jsx)(Lh,{projectName:e},`agents:${e}`)]})}function Ch({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 ${sh} ${e.value===t?`bg-surface-active text-heading`:`text-secondary hover:text-heading`}`,children:e.label},e.value))})}function wh({summary:e,children:t}){let[n,r]=(0,Z.useState)(!1);return(0,Q.jsxs)(`details`,{open:n,onToggle:e=>r(e.currentTarget.open),className:`text-copy-14 text-secondary`,children:[(0,Q.jsxs)(`summary`,{className:ch,children:[n?(0,Q.jsx)(y,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(d,{className:`size-3.5`,"aria-hidden":`true`}),e]}),(0,Q.jsx)(`div`,{className:`mt-3`,children:t})]})}function Th({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,`. `,Ds(t)]}),(0,Q.jsx)(J,{size:`sm`,variant:`outline`,onClick:n,children:`Retry`})]})}function Eh({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 Dh({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)(E,{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 `,dh[t.sourceType]??t.sourceType,`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:t.reason}),(0,Q.jsx)(H,{to:`/traffic/$projectName/$sourceId`,params:{projectName:e,sourceId:t.sourceId},className:`rounded text-link underline-offset-4 hover:underline ${sh}`,children:`Review source`})]},t.sourceId))})}function Oh({projectName:e}){let{search:t,update:n}=xh(),r=$m.some(e=>e.value===t.journeyDays)?t.journeyDays:`30`,i=t.journeyEngine??``,a=t.journeyReturned===`true`||t.journeyReturned===`false`?t.journeyReturned:``,o=t.journeyMatching===_n.ua?_n.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=U({...Za({client:q,path:{name:e},query:u}),staleTime:3e4}),f={...u,engine:i||void 0,returned:a||void 0,keyBasis:o||_n[`ip-ua`],limit:th,offset:s},p=U({...po({client:q,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)(Th,{what:`the visitor summary`,error:d.error,retry:()=>{d.refetch()}}):(0,Q.jsx)(kh,{summary:d.data}),(0,Q.jsx)(Ch,{label:`First AI visit within`,options:$m,value:r,onChange:e=>{Re(`window`),l(new Date().toISOString()),n({journeyDays:e===`30`?void 0:e,journeyOffset:void 0,journeyVisitor:void 0})}})]}),m&&(0,Q.jsx)(Dh,{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)(Th,{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:mh}),(0,Q.jsx)(J,{className:`mt-3`,size:`sm`,variant:`outline`,onClick:()=>{Re(`other`),n({journeyMatching:_n.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)(H,{to:`/projects/$projectName/traffic`,params:{projectName:e},className:`mt-2 inline-block text-link hover:underline`,children:`Review traffic sources`})]}):m?(0,Q.jsx)(jh,{projectName:e,data:m,engines:d.data?.byEngine.map(e=>e.engine)??[],engine:i,returned:a,matching:o,openKey:h,onToggle:e=>{e&&Ne(`journeys.visitor_open`),n({journeyVisitor:e??void 0})},onFilter:e=>{Re(`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)(wh,{summary:`About this data`,children:(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[d.data&&(0,Q.jsx)(Fh,{summary:d.data}),m&&(0,Q.jsx)(Ih,{data:m})]})})]})}function kh({summary:e}){let t=(0,Q.jsx)(Eh,{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)(Eh,{label:`Visitors and returns`,help:mh,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:$e(e.returnRate,Lt.fraction),i=e.keyBasis.ua>0?`${gh(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)(Eh,{label:`AI-referred visitors`,help:i,children:e.aiVisitors.toLocaleString()}),(0,Q.jsxs)(Eh,{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)(Eh,{label:`Median time to return`,children:e.medianDaysToReturn===null?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not available`}):Qn(e.medianDaysToReturn)}),(0,Q.jsx)(Eh,{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:[uh[e],` `,(0,Q.jsx)(`span`,{className:`tabular-nums text-secondary`,children:t.toLocaleString()})]},e))})})]})}function Ah({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=`${_h(e)}${e.paid?` (paid)`:``}`,n=r.at(-1);n?.label===t?n.visits++:r.push({label:t,visits:1})}let i=r.slice(0,ah),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 jh({projectName:e,data:t,engines:n,engine:r,returned:i,matching:o,openKey:s,onToggle:c,onFilter:l,onPage:u}){let f=!!(r||i||o),p=o===_n.ua,m=t.totalVisitors===0?0:t.offset+1,h=t.offset+t.visitors.length,g=s!==null&&!t.visitors.some(e=>e.visitorKey===s);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 `,h.toLocaleString(),` of `,gh(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 ${sh} [&::-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:[r,i===`true`?`Came back`:i===`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:oh,value:r,onChange:e=>l({journeyEngine:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`All engines`}),r&&!n.includes(r)&&(0,Q.jsx)(`option`,{value:r,children:r}),n.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e))]})]}),(0,Q.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Came back`,(0,Q.jsxs)(`select`,{className:oh,value:i,onChange:e=>l({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:oh,value:o,onChange:e=>l({journeyMatching:e.target.value||void 0}),children:[(0,Q.jsx)(`option`,{value:``,children:`Network and browser`}),(0,Q.jsx)(`option`,{value:_n.ua,children:`Browser only (groups)`})]})]}),f&&(0,Q.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>l({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)(E,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),hh]}),s&&g&&(0,Q.jsxs)(`div`,{className:`rounded-md border border-default bg-surface-subtle px-4 py-4 sm:px-8`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsx)(`p`,{className:`text-label-13 text-secondary`,children:`This visitor is not on this page of the list.`}),(0,Q.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>c(null),children:`Close`})]}),(0,Q.jsx)(Mh,{projectName:e,visitorKey:s,partialSources:t.partialSources})]}),t.visitors.length===0?(0,Q.jsx)(`p`,{className:`rounded-md border border-default p-5 text-copy-14 text-secondary`,children:`No visitors match these filters.`}):(0,Q.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`w-full min-w-[42rem]`,"aria-label":`AI-referred visitors`,children:[(0,Q.jsx)(`thead`,{className:`bg-surface-subtle text-left text-label-13 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`py-2 pl-3 pr-2 font-normal`,children:`First AI visit`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-2 font-normal`,children:`Landing page`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-2 font-normal`,children:`Came back through`}),(0,Q.jsx)(`th`,{scope:`col`,className:`px-2 py-2 text-right font-normal`,children:`Visits`}),(0,Q.jsx)(`th`,{scope:`col`,className:`py-2 pl-2 pr-3 text-right font-normal`,children:`Last seen`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:t.visitors.map(n=>{let r=n.visitorKey===s,i=n.visits.find(e=>e.entryClass===`ai`),a=`journey-visitor-${n.visitorKey}`;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:r?`bg-surface-active`:`hover:bg-surface-hover`,children:[(0,Q.jsx)(`td`,{className:`py-2.5 pl-3 pr-2 align-top`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":r?a:void 0,"aria-label":`${n.firstAiEngine} visitor, first AI visit ${ri(n.firstAiAt)}`,onClick:()=>c(r?null:n.visitorKey),className:`${lh} whitespace-nowrap`,children:[r?(0,Q.jsx)(y,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(d,{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:Zr(n.firstAiAt)})]})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 align-top`,children:i?(0,Q.jsx)(`span`,{className:`block max-w-[18rem] truncate text-label-13-mono text-heading`,title:i.landingPath,children:zc(i.landingPath)}):(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not kept`})}),(0,Q.jsx)(`td`,{className:`px-2 py-2.5 align-top text-label-14`,children:(0,Q.jsx)(Ah,{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:Zr(n.lastSeenAt)})})]}),r&&(0,Q.jsx)(`tr`,{id:a,children:(0,Q.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-8`,children:(0,Q.jsx)(Mh,{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)(J,{variant:`outline`,size:`sm`,disabled:t.offset===0,onClick:()=>u(Math.max(0,t.offset-t.limit)),children:`Previous`}),(0,Q.jsx)(J,{variant:`outline`,size:`sm`,disabled:t.offset+t.limit>=t.totalVisitors,onClick:()=>u(t.offset+t.limit),children:`Next visitors`})]})]})}function Mh({projectName:e,visitorKey:t,partialSources:n}){let[r,i]=(0,Z.useState)(0),[a,o]=(0,Z.useState)(ye.pages),[s,c]=(0,Z.useState)(null),l=U({...ho({client:q,path:{name:e,visitorKey:t},query:{limit:nh,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)(Th,{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:gh(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===_n.ua?`Matched by browser only`:`Matched by network and browser`,(0,Q.jsx)(X,{placement:`bottom`,text:d.keyBasis===_n.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)(E,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`text-heading`,children:[`Some requests are missing on `,gh(d.cappedDays,`day`),`.`]}),(0,Q.jsx)(X,{placement:`bottom`,text:`At most ${300 .toLocaleString()} requests per visitor are kept each day.`})]}),(0,Q.jsx)(Nh,{visits:u.visits,openId:s,events:u.events,loading:l.isFetching,onToggle:e=>{e&&Ne(`journeys.visit_open`),c(e)},onToggleEvents:()=>o(a===ye.pages?ye.all:ye.pages)}),m&&(0,Q.jsxs)(`p`,{className:`text-label-13 text-secondary`,children:[`Later visits are not recorded by `,dh[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)(J,{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)(J,{variant:`outline`,size:`sm`,disabled:f||l.isFetching,onClick:()=>{i(u.offset+u.limit),c(null)},children:`Later visits`})]}),(0,Q.jsx)(wh,{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:vi(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 Nh({visits:e,openId:t,events:n,loading:r,onToggle:i,onToggleEvents:a}){return(0,Q.jsxs)(`table`,{className:`w-full`,"aria-label":`Visits in time order`,children:[(0,Q.jsx)(`thead`,{className:`text-left text-label-12 text-secondary`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`When`}),(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`Came from`}),(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`Landing page`}),(0,Q.jsx)(`th`,{scope:`col`,className:`pb-1.5 text-right font-normal`,children:`Pages`})]})}),(0,Q.jsx)(`tbody`,{className:`divide-y divide-default`,children:e.map(e=>{let o=e.id===t,s=vh(e);return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`whitespace-nowrap py-2 pr-4 align-top`,children:(0,Q.jsxs)(`button`,{type:`button`,"aria-expanded":o,onClick:()=>i(o?null:e.id),className:`${lh} text-label-14 text-heading`,children:[o?(0,Q.jsx)(y,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(d,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,Q.jsx)(`time`,{dateTime:e.startedAt,children:ri(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:_h(e)}),s&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` · `,s]})]}),(0,Q.jsx)(`td`,{className:`py-2 pr-4 align-top`,children:(0,Q.jsx)(`span`,{className:`block max-w-[22rem] truncate text-label-13-mono text-heading`,title:e.landingPath,children:zc(e.landingPath)})}),(0,Q.jsx)(`td`,{className:`py-2 text-right align-top text-label-14 tabular-nums text-heading`,children:e.pageCount.toLocaleString()})]}),o&&(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`pb-3 pl-6`,children:(0,Q.jsx)(Ph,{visit:e,events:n,loading:r,onToggleEvents:a})})})]},e.id)})})]})}function Ph({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===ye.pages?`No pages recorded for this visit.`:`No requests recorded for this visit.`}):(0,Q.jsx)(`ol`,{"aria-label":`${_h(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:yh(e.ts)}),(0,Q.jsxs)(`span`,{className:`min-w-0 break-all text-label-13-mono text-heading`,children:[bh(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[bh(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 ${sh}`,children:t===ye.pages?`Show all ${gh(e.requestCount,`request`)}`:`Show fewer requests`})]})}function Fh({summary:e}){return(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[gh(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: `,gh(e.keyBasis.ipUa,`visitor`),` by network and browser, `,gh(e.keyBasis.ua,`visitor`),` by browser only. Visitor figures count only the first: one browser version can be many people.`]})]})}function Ih({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 `,ri(e.windowStart),` to `,ri(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:[dh[e.sourceType]??e.sourceType,`:`]}),` `,e.reason]},e.sourceId))]})}function Lh({projectName:e}){let{search:t,update:n}=xh(),r=eh.some(e=>e.value===t.agentHours)?t.agentHours:`24`,[i,o]=(0,Z.useState)(()=>new Date().toISOString()),[s,c]=(0,Z.useState)(``),[l,u]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[g,_]=(0,Z.useState)(``),[v,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(i)-Number(r)*36e5).toISOString(),until:i,sourceId:s||void 0,agentId:l?.id,trust:f||void 0,targetKey:m||void 0},D=U({...ko({client:q,path:{name:e},query:{...E,limit:rh,offset:v}}),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===s),N=()=>{b(0),S(null)},P=!!(s||f||m||l);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)(Rh,{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 ${sh} [&::-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:oh,value:s,onChange:e=>{Re(`other`),c(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:oh,value:f,onChange:e=>{Re(`other`),p(e.target.value),N()},children:[(0,Q.jsx)(`option`,{value:``,children:`All trust levels`}),Object.values(Je).filter(e=>e!==Je.likely_fake).map(e=>(0,Q.jsx)(`option`,{value:e,children:Ic[e]},e))]})]}),k.length>0&&(0,Q.jsxs)(`details`,{ref:T,className:`relative`,children:[(0,Q.jsxs)(`summary`,{className:`${oh} 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:g,onChange:e=>_(e.target.value),placeholder:`Find a property`,className:`${oh} 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(g.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 ${sh}`,onClick:()=>{Re(`other`),h(e.key),N(),T.current&&(T.current.open=!1,T.current.querySelector(`summary`)?.focus())},children:e.label},e.key))})]})]}),P&&(0,Q.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>{Re(`other`),c(``),p(``),h(``),u(null),N()},children:`Clear filters`})]})]}),(0,Q.jsx)(Ch,{label:`Period`,options:eh,value:r,onChange:e=>{Re(`window`),o(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:[s&&(0,Q.jsxs)(`span`,{children:[`Source: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:M?.label??s})]}),f&&(0,Q.jsxs)(`span`,{children:[`Trust: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:Ic[f]})]}),m&&(0,Q.jsxs)(`span`,{children:[`Property: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:j?.label??m})]}),l&&(0,Q.jsxs)(`span`,{children:[`Agent: `,(0,Q.jsx)(`span`,{className:`text-heading`,children:l.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)(Th,{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 ${ri(t.startedAt)}`,onClick:()=>{n||Ne(`journeys.agent_open`),S(n?null:t.id)},className:`${lh} text-label-14-strong text-heading`,children:[n?(0,Q.jsx)(y,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,Q.jsx)(d,{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 ${ph[e]}`,children:Ic[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:ri(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:gh(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)(zh,{projectName:e,journey:t,selection:{...E,since:O.windowStart,until:O.windowEnd},onSelectAgent:()=>{Re(`other`),u({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)(J,{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)(J,{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)(wh,{summary:`About this data`,children:(0,Q.jsx)(Vh,{context:O})})]}):null]})}function Rh({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)(Eh,{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)(Eh,{label:`Requests`,children:e.observedRequests.toLocaleString()}),t!==null&&t>0&&(0,Q.jsx)(Eh,{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)(E,{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)(E,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Some requests are missing: a source reached its daily limit.`]})]})}function zh({projectName:e,journey:t,selection:n,onSelectAgent:r}){let[i,a]=(0,Z.useState)(0),o=U({...Qa({client:q,path:{name:e,journeyId:t.id},query:{...n,limit:ih,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)(Bh,{operator:t.operator,events:o.data.events}):(0,Q.jsx)(`span`,{}),(0,Q.jsxs)(J,{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)(Th,{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:[bh(e.method)&&(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[bh(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:fh[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)(J,{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)(J,{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 Bh({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:ph[t],children:Ic[t]}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`: `,[...n].map(t=>Fc(t,e)).join(` · `)]})]},t))})}function Vh({context:e}){return(0,Q.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[(0,Q.jsxs)(`p`,{children:[ri(e.windowStart),` to `,ri(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 Hh={"non-brand":`Non-brand`,branded:`Branded`,unknown:`Unclassified`},Uh={"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":ei.label};function Wh({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?`—`:$e(e.rate,Lt.fraction),(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` · `,Hh[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:Uh[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 Gh({projectName:e,revision:t}){let n=(0,Z.useId)(),[r,i]=(0,Z.useState)(`non-brand`),a=lo({client:q,path:{name:e},query:{queryClass:`all`,limit:1}}),o=U({...a,queryKey:[{...a.queryKey[0],tags:[t??`no-sweep`]}],staleTime:Ii}),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: `,Ds(o.error)]}),(0,Q.jsx)(J,{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 `,Hh[l.queryClass].toLowerCase(),` queries in this check.`]}):l&&(f=(0,Q.jsxs)(`table`,{className:`engine-comparison`,"aria-label":`By engine, ${Hh[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)(Ac,{provider:e.provider})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wh,{value:e.mentionCoverage,queryClass:l.queryClass})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Wh,{value:e.citationCoverage,queryClass:l.queryClass})})]},e.provider))})]})):f=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:mt()?ms:`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:[Hh[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 `,ri(d),s?.selection.measurement.state===`partial`?` · incomplete`:``]}):null,c.length>1?(0,Q.jsx)(nc,{label:`Query type`,className:`flex-wrap`,options:c.map(e=>({value:e.queryClass,label:Hh[e.queryClass]})),value:l.queryClass,onChange:i}):null]})]}),(0,Q.jsx)(`div`,{className:`av-card-body`,children:f})]})}var Kh={[Ot.queued]:{word:`queued`,tone:`text-secondary`},[Ot.running]:{word:`running`,tone:`text-info-300`},[Ot.completed]:{word:`completed`,tone:`text-secondary`},[Ot.partial]:{word:`partial`,tone:`text-caution-400`},[Ot.failed]:{word:`failed`,tone:`text-negative-400`},[Ot.cancelled]:{word:`cancelled`,tone:`text-secondary`}};function qh({runs:e,projectName:t,collapsed:n=!1}){let r=(0,Z.useId)(),i=(0,Z.useId)(),a=new Set(e.map(e=>e.location??``)).size>1,o=e.some(e=>e.kind!==Ct[`answer-visibility`]),s=e.map(e=>`${e.startedAt}: ${e.summary}.${e.statusDetail?` ${e.statusDetail}`:``}`);return(0,Q.jsx)(`section`,{className:`overview-brief`,"aria-labelledby":r,children:(0,Q.jsxs)(`details`,{className:`av-history`,open:!n||void 0,children:[(0,Q.jsxs)(`summary`,{className:`av-card-head`,"aria-labelledby":r,"aria-describedby":e.length>0?i:void 0,children:[(0,Q.jsx)(`h2`,{id:r,className:`av-card-title`,children:`Past checks`}),(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[e.length>0?(0,Q.jsxs)(`span`,{id:i,className:`av-card-meta`,children:[e.length,` recent`]}):null,(0,Q.jsx)(y,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,Q.jsx)(`div`,{className:`av-card-body`,children:e.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No checks yet.`}):(0,Q.jsxs)(`table`,{className:`av-grid av-grid-dense av-grid-sweeps`,"aria-labelledby":r,children:[(0,Q.jsx)(`thead`,{className:`sr-only`,children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`col`,children:`Started`}),o?(0,Q.jsx)(`th`,{scope:`col`,children:`Type`}):null,(0,Q.jsx)(`th`,{scope:`col`,children:`Trigger`}),a?(0,Q.jsx)(`th`,{scope:`col`,children:`Location`}):null,(0,Q.jsx)(`th`,{scope:`col`,children:`Duration`}),(0,Q.jsx)(`th`,{scope:`col`,children:`Status`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>{let n=Kh[e.status],r=e.status===Ot.partial||e.status===Ot.failed;return(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,className:`av-row-label tabular-nums`,children:(0,Q.jsx)(as,{run:e,projectName:t,className:`av-link`,label:e.opensSeoWorkspace?`View SEO refresh from ${e.startedAt}`:`View the ${e.startedAt} check`,children:e.startedAt})}),o?(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.kindLabel}):null,(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.triggerLabel}),a?(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.location??`No location`}):null,(0,Q.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.duration}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(`span`,{className:`av-status ${n.tone}`,children:n.word}),r&&e.statusDetail?(0,Q.jsx)(`span`,{className:`ml-2 text-label-13 text-secondary`,children:e.statusDetail}):null]})]},e.id)})})]})}),(0,Q.jsx)(il,{items:s})]})})}var Jh=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],Yh=`Measured answers`,Xh=`Close answers`,Zh={"non-brand":`Non-brand queries`,branded:`Branded queries`,unknown:`Unclassified queries`},Qh={"non-brand":`non-brand queries`,branded:`branded queries`,unknown:`unclassified queries`},$h={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.`},eg={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.`},tg=`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.`,ng=`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 rg(e){return e.kind===`project`?`Whole site`:e.kind===`group`?`${e.label} · Group`:e.kind===`market`?`${e.label} · Market`:e.label}function ig(e){return e.reason===`identity-ambiguous`?Yr.ambiguous:e.reason===`not-applicable`?`Not applicable`:`Not measured`}function ag({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:[ig(e),(0,Q.jsx)(X,{text:ai})]});if(e.rate===null)return(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:ig(e)});let n=oi(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:$e(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 og({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 sg(e,t){if(!e||e.state===`unavailable`)return null;let n=e[t];if(n.state===`unavailable`)switch(n.reason){case On[`previous-unavailable`]:return{text:$h.previousUnavailable,tone:`text-secondary`};case On[`current-unavailable`]:case On[`not-applicable`]:return null}let{direction:r,magnitude:i}=yn(n.delta);switch(r){case`up`:return{text:$h.up(i),tone:`text-positive`};case`down`:return{text:$h.down(i),tone:`text-negative`};case`none`:return{text:$h.none,tone:`text-secondary`}}}function cg(e,t){let n=hi(e);return t!==null&&mi(n)===mi(hi(t))?Ci(n):pi(n)}function lg(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 ug(e,t){if(!e)return null;if(e.state===`unavailable`){let n=e.previousRun?cg(e.previousRun.createdAt,t):null;switch(e.reason){case Kn[`no-selected-run`]:return null;case Kn[`no-previous-run`]:return $h.noPreviousRun;case Kn[`definition-changed`]:return $h.definitionChanged(n);case Kn[`model-changed`]:return $h.modelChanged(n);case Kn[`legacy-unknown`]:return $h.legacyUnknown;case Kn[`partial-run`]:return $h.partialRun;case Kn[`scoped-run`]:return $h.scopedRun}}return $h.comparedWith(cg(e.previousRun.createdAt,t))}function dg(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 fg({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=oi(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:[ig(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:$e(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 pg={otherQueries:`Other queries`},mg={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 hg(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(` · `)||pg.otherQueries;return r.sort((e,t)=>e.marketLabel.localeCompare(t.marketLabel)||e.query.localeCompare(t.query))}var gg={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 _g({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?gg.savedCite(r.citedAnswers,r.answers,r.citedTargetKeys.map(i).join(`, `)):gg.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:gg.partlySaved(r.answers)}):null,(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:a})]})}function vg({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)(k,{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)(ag,{value:e,signal:t}),o?(0,Q.jsx)(_g,{row:o,targetLabels:a??new Map,showCount:e.rate===null}):null]}),o?(0,Q.jsx)(X,{text:gg.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 yg({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 bg({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)(Os,{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)(yg,{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:fr(e.provider)}),(!e.model||e.model!==Xe(e.provider))&&(0,Q.jsx)(`span`,{className:`block break-words text-label-14 text-secondary`,title:e.model??void 0,children:e.model?Xe(e.provider)?mr(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)(yg,{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)(ec,{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)(vg,{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)(vg,{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)(J,{variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`View answers for ${e.query} · ${fr(e.provider)}`,onClick:t=>a(e,t.currentTarget),children:[e.answerCount===1?`View answer`:`View answers`,(0,Q.jsx)(d,{size:16,"aria-hidden":`true`})]})})]},JSON.stringify([e.provider,e.model,e.location])))]})}var xg=`Cited counts only answers whose sources could be checked.`,Sg=[{key:`mentioned`,label:`Mentioned`,color:li[1],dashed:!1},{key:`cited`,label:`Cited`,color:Si.positive,dashed:!0}],Cg=`var(--chart-tooltip-bg)`;function wg({population:e}){let t=(0,Z.useId)(),[n,r]=(0,Z.useState)({mentioned:!0,cited:!0}),i=Sg.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)?[xg]:[],...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`}),Sg.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?Cg: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":`${Zh[e.queryClass]} mention and citation trend`,children:(0,Q.jsx)(ce,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(pe,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ie,{stroke:wi,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`createdAt`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:e=>new Date(Number(e)).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),minTickGap:24}),(0,Q.jsx)(de,{domain:[0,1],tick:xi,tickLine:!1,axisLine:!1,width:48,tickFormatter:e=>$e(Number(e))}),(0,Q.jsx)(ae,{...Ti,formatter:e=>typeof e==`number`?$e(e):`Not measured`,labelFormatter:e=>new Date(Number(e)).toLocaleDateString()}),c.map(e=>(0,Q.jsxs)(Z.Fragment,{children:[n.mentioned?(0,Q.jsx)(fe,{type:`linear`,dataKey:`mentioned-${e}`,name:`Mentioned`,stroke:li[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:li[1]}}):null,n.cited?(0,Q.jsx)(fe,{type:`linear`,dataKey:`cited-${e}`,name:`Cited`,stroke:Si.positive,strokeWidth:2,strokeDasharray:`6 4`,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Cg,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":`${Zh[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)(ag,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(ag,{value:e.citationCoverage,signal:`cited`})}),(0,Q.jsx)(`td`,{children:e.continuity.state.replaceAll(`-`,` `)})]},e.runId))})]})]})]})}function Tg(e,t){return t?e?.populations.find(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===t)):void 0}function Eg(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=Tg(r,t)??Tg(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 Dg={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: ${fr(e)}`,model:e=>`Model: ${e.includes(`/`)?mr(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(` `)},Og={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},kg=`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 Ag(e,t){return e&&t?Dg.dateRange(e.slice(0,4)===t.slice(0,4)?Di(e):yi(e),yi(t)):e?Dg.dateFrom(yi(e)):t?Dg.dateThrough(yi(t)):null}function jg(e,t){let n=[];e.provider&&n.push({key:`engine`,label:Dg.engine(e.provider),patch:{measurementProvider:void 0}}),e.model&&n.push({key:`model`,label:Dg.model(e.model),patch:{measurementModel:void 0}}),e.location&&n.push({key:`location`,label:e.location===`none`?Dg.noLocation:Dg.location(e.location),patch:{measurementLocation:void 0}});let r=Ag(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?Dg.resultsFrom(pi(hi(r.createdAt))):Dg.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Mg(e,t,n){return t===``||e.some(e=>e.value===t)?e:[...e,{value:t,label:n}]}function Ng({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=Eg(e,t.queryKey,t.answer),_=t.queryClass===`all`?g.queryClass:t.queryClass,v=jg(t,e),y=t.measurementScope===`property`?t.measurementScopeKey:void 0,b=y?i?.({id:y,label:Kc(e.scopeOptions,t)?.label??y}):null,x=t.provider??``,S=t.model??``,C=t.location??``,T=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:ng,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:ng,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:Dg.queryType}),(0,Q.jsxs)(`select`,{"aria-label":Dg.queryType,className:kg,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)(Y,{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:pi(hi(h.completedAt))}):null]})]}),(0,Q.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{ref:u,type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,"aria-expanded":c,"aria-controls":f,onClick:()=>l(e=>!e),children:Dg.filters(v.length)}),v.map(e=>(0,Q.jsxs)(J,{type:`button`,variant:`outline`,className:`visibility-filter-token pointer-coarse:min-h-11 rounded-md text-button-14`,"aria-label":Dg.removeFilter(e.label),onClick:()=>{n(e.patch),D()},children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label}),(0,Q.jsx)(w,{size:16,className:`shrink-0`,"aria-hidden":`true`})]},e.key)),b,r?(0,Q.jsx)(J,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:r,children:Dg.manageQueries}):null]})]}),(0,Q.jsxs)(`div`,{id:f,role:`group`,"aria-label":Dg.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,Mg([{value:``,label:`All engines`},...p.providers.map(e=>({value:e,label:fr(e)}))],x,fr(x))),O(`Requested search location`,`measurementLocation`,C,Mg([{value:``,label:`All requested locations`},...p.locations.flatMap(e=>e.kind===`exact`?[{value:e.value,label:e.value}]:e.kind===`none`?[{value:`none`,label:Dg.noLocation}]:[])],C,C===`none`?Dg.noLocation:C)),O(`AI model`,`measurementModel`,S,Mg([{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(`/`)?mr(e):e}))],S,S.includes(`/`)?mr(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`,T,Mg([{value:``,label:`Latest saved check`},...[...g.trend].reverse().map(e=>({value:e.runId,label:new Date(e.createdAt).toLocaleString()}))],T,`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)(J,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:v.length===0,onClick:()=>{n({...Og}),D()},children:Dg.clearFilters})})]}),E?(0,Q.jsx)(`p`,{role:`status`,className:`border-b border-default py-3 text-copy-14 text-secondary`,children:Dg.trackingChanged(a?Ci(hi(a)):null,h.completedAt?Ci(hi(h.completedAt)):null,o??null)}):null]})}function Pg({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=Eg(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="${Yh}"]`);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=rg(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)(J,{variant:`outline`,onClick:()=>n({queryClass:`all`,measurementQueryKey:void 0}),children:`View all saved results`})]}):null,[g].map(t=>{let s=hg(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=Qh[t.queryClass],_=ug(t.comparison,lg(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.`:$h.explanation;return(0,Q.jsxs)(`section`,{"aria-label":Zh[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:Zh[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:dg(t.summary,_)}),(0,Q.jsx)(X,{text:v})]})]}),(0,Q.jsxs)(`dl`,{className:`report-headline mt-3`,"data-columns":m?3:2,"aria-label":`${Zh[t.queryClass]} headline results`,children:[(0,Q.jsx)(fg,{label:m?`Answers mentioning a property`:`Mentioned answers`,help:x.mode===`advanced`?eg.advancedMention:eg.simpleMention,value:t.summary.mentionCoverage,signal:`mentioned`,unit:`answers`,classNoun:g,change:sg(t.comparison,`mentionCoverage`)}),(0,Q.jsx)(fg,{label:m?`Answers citing a property`:`Cited answers`,help:x.mode===`advanced`?eg.advancedCitation:eg.simpleCitation,value:t.summary.citationCoverage,signal:`cited`,unit:`answers`,classNoun:g,change:sg(t.comparison,`citationCoverage`)}),m?(0,Q.jsx)(fg,{label:`Properties mentioned`,help:eg.propertyReach,value:t.summary.propertyReach,signal:`mentioned`,unit:`properties`,classNoun:g,change:sg(t.comparison,`propertyReach`)}):null]}),(0,Q.jsx)(ws,{queryClass:x.queryClass,manage:!0}),(0,Q.jsx)(wg,{population:t}),m&&(t.breakdown.groups.length>0||t.breakdown.properties.length>0)?(0,Q.jsx)(Fg,{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":`${Zh[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:gg.outcomes(t.summary.notMeasuredUnchecked)}):null,t.summary.notMeasuredNoSources?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:gg.outcomesNoSources(t.summary.notMeasuredNoSources)}):null]}),(0,Q.jsx)(X,{text:tg})]})]}):null,(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"data-query-results":t.queryClass,"aria-label":`${Zh[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 ${Zh[t.queryClass]}`,placeholder:`Search queries`,className:`${ng} 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":`${Zh[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)(bg,{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)(J,{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":Yh,"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)(J,{variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:T,children:Xh})]}),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)(J,{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:fr(e.provider)}),e.model&&e.model!==Xe(e.provider)?(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.model,children:Xe(e.provider)?mr(e.model):e.model}):null,(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.location===null?Dg.noLocation:Dg.location(e.location)}),(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:new Date(e.createdAt).toLocaleDateString()}),(0,Q.jsx)(Y,{tone:`neutral`,children:e.mentioned===null?e.mentionUnavailableReason===`identity-ambiguous`?Yr.ambiguous:`Mention not checked`:e.mentioned?`Mentioned`:`Not mentioned`}),(0,Q.jsx)(Y,{tone:`neutral`,children:e.cited===null?e.citationUnavailableReason===`citation-not-measured`?ei.label:`Citation not checked`:e.cited?`Cited`:`Not cited`})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Ks,{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:[mc,` (`,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)(rc,{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)(J,{variant:`outline`,onClick:()=>f(w(t).nextCursor),children:`Next answers`}):null]})]}):null]})]}),(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":`${Zh[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)(ag,{value:e.mentionCoverage,signal:`mentioned`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(ag,{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 Fg({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=jl({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)(J,{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:`${ng} 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)(ag,{value:e.mentionCoverage,signal:`mentioned`}),(0,Q.jsx)(og,{value:e.mentionCoverage})]}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(ag,{value:e.citationCoverage,signal:`cited`}),(0,Q.jsx)(og,{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)(Nl,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function Ig(e,t,{enabled:n}){return U({...lo({client:q,path:{name:e},query:qs(t)}),enabled:n,staleTime:Ri,retry:!1,placeholderData:z})}function Lg(e,t){return t&&e.selection.mode===`simple`&&e.selection.measurement.state===`not-measured`}function Rg({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=R(),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=U({...lo({client:q,path:{name:e},query:{...qs(t),cursor:a,search:s||void 0}}),staleTime:Ri,retry:!1,placeholderData:z}),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=U({...lo({client:q,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&&!Tg(p.data,t.queryKey)&&!g.data)return;let r=Eg(p.data,t.queryKey,t.answer,g.data);if(!a&&!s){let{queryKey:n}=lo({client:q,path:{name:e},query:qs({...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&&Lg(p.data,i))return(0,Q.jsx)(Q.Fragment,{children:r});if(p.error){let e=un(zt(p.error)),t=e?.reason===Vn[`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?mg.retiredMarket:e?mg.retiredScope:Oe(p.error)}),t?(0,Q.jsx)(J,{variant:`outline`,onClick:()=>{o(void 0),n({measurementMarketKey:void 0})},children:mg.showAllMarkets}):e?(0,Q.jsx)(J,{variant:`outline`,onClick:()=>{o(void 0),n({measurementScope:`project`,measurementScopeKey:void 0})},children:mg.showWholeSite}):(0,Q.jsx)(J,{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)(Pg,{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?Oe(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 zg({projectName:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,fallback:s,showUnmeasuredFallback:c=!1}){let l=Ig(e,t,{enabled:!0}),u=l.error?void 0:l.data,d=!l.isPlaceholderData&&u?.selection.availability.state===`available`?u.selection.run.id:null;bs(d,null);let f=!(!u||u.selection.availability.state!==`available`||Lg(u,c));return(0,Q.jsxs)(Q.Fragment,{children:[f?(0,Q.jsx)(Ng,{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)(Ss,{})}):null,(0,Q.jsx)(Rg,{projectName:e,selection:t,onSelectionChange:n,fallback:s,showUnmeasuredFallback:c},`${e}:${JSON.stringify({...t,queryKey:void 0,answer:void 0})}`)]})}var Bg=[{value:`byProvider`,label:`By engine`},{value:`overall`,label:`All engines`}],Vg=[{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.`}],Hg=[{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.`}],Ug=li[2],Wg=li[4],Gg=`var(--chart-tooltip-bg)`,Kg={up:`text-positive-400`,down:`text-negative-400`,none:`text-muted`};function qg({direction:e,magnitude:t}){switch(e){case`up`:return`up ${t} points`;case`down`:return`down ${t} points`;case`none`:return`no change`}}function Jg(e){return e.direction===`none`?`no change over the period`:`${qg(e)} over the period`}function Yg(e){return e===`__cited__`||e===`__mentioned__`||e===`__mentionShare__`}function Xg(e){return e===`__cited__`?`Cited`:e===`__mentioned__`?`Mentioned`:e===`__mentionShare__`?`Mention share`:fr(e)}function Zg(e,t){return e===`__cited__`?Si.positive:e===`__mentioned__`?li[1]:e===`__mentionShare__`?Ug:ci(Kr(e),t)}function Qg(e){return e===`non-brand`?`non-brand answers`:`all answers`}function $g(e){return e===`cited`?`Cited`:e===`mentionShare`?`Mention share`:`Mentioned`}function e_(e,t){return e===`mentionShare`?`Mention share in ${Qg(t)}`:$g(e)}function t_(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 n_={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 r_(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 i_(e,t,n){let r=e.byProvider[t];return r?r_(r,n):null}function a_(e){return e.rate===null?n_.point:`${e.count} of ${e.total}`}function o_(e,t){let n=$g(t).toLowerCase();return e.rate===null?`${n} ${n_.point}`:`${$e(e.rate)} ${n}, ${e.count} of ${e.total} answers`}function s_(e,t){if(t===`mentionShare`){let{projectMentionSnapshots:t,competitorMentionSnapshots:n}=e.mentionShare;return`${t} of ${t+n} tracked-brand mentions`}let n=r_(e,t);return n.rate===null?n_.point:`${n.count} of ${n.total} answers`}function c_(e,t){if(t===void 0)return null;let n=String(t);return e.find(e=>e.startDate===n)??null}function l_(e){let t=Pr(e);return t===null?[]:Object.entries(t).sort(([e],[t])=>Kr(e).localeCompare(Kr(t))).map(([e,t])=>`${fr(e)}: ${Lr(t)}`)}function u_(e,t){return new Date(e).toDateString()===new Date(t).toDateString()}function d_(e){return`${e} ${e===1?`query`:`queries`}`}function f_(e){let{added:t,removed:n}=e;return[...t.length>0?[`${d_(t.length)} added`]:[],...n.length>0?[`${t.length>0?n.length:d_(n.length)} removed`]:[]].join(`, `)}function p_(e,t){let n=_r(e),r=Ar(e),i=Gr(e,t);if(!n||!r||!i)return null;let a=yr(i.moves),o=u_(n.start,n.end),s=e=>ri(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 m_(e,t,n){let r=p_(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?`, `:``,f_(e),` `,(0,Q.jsx)(`strong`,{children:Mr(hi(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 h_=`Queries changed`;function g_(e){let t=yr(e.moves);return t?`${h_}: ${t} between the first and latest points, so the change compares different queries.`:`${h_}: the first and latest points have answers for ${e.firstCount} and ${e.latestCount} queries, so the change compares different queries.`}function __(e){return e.replace(/ /g,`\xA0`)}function v_({state:e,from:t=!1}){return(0,Q.jsx)(`span`,{className:t?`av-model av-model-from`:`av-model`,children:Lr(e)})}function y_(e,t){return e.reroute?`Same preset, answered with a different model.`:jr(e.provider,e.to)?e.served?`Preset picks its own model. Answered with ${Lr(e.served.to)} (was ${Lr(e.served.from)}).`:t&&t.length>0?`Preset picks its own model. Answered with ${t.map(e=>e.includes(`/`)?mr(e):e).join(`, `)}.`:`Preset picks its own model.`:null}function b_({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=>Mr(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:f_(e)}),toHelp:null}))});let p=[...new Set(n.map(e=>e.provider))].sort((e,t)=>fr(e).localeCompare(fr(t)));for(let e of p){let t=r[e]?.latestServedModelIds??null,a=n.filter(t=>t.provider===e);f.push({key:e,label:fr(e),rows:a.map((n,r)=>{let a=d.get(e)===n?i.get(e).text:null,o=[y_(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)(v_,{state:n.from,from:!0}),to:(0,Q.jsx)(v_,{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?Ar(l):null;for(let[e,t]of Object.entries(l?Pr(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 `,fr(e),` models: `,Br(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)??[],fr(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: `,Tr(t)]}):`Changed before this date range: ${Tr(t)}`);for(let e of a)h.push(`${fr(e.provider)}: most recent ${e.shown} of ${e.total} changes`);for(let e of o)h.push(`${fr(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:[fr(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])=>fr(e).localeCompare(fr(t)))){let n=t.latestServedModelIds??[],r=n.length>0?n.map(e=>e.includes(`/`)?mr(e):e).join(`, `):Lr(t.latestObservation.state);h.push((0,Q.jsxs)(Q.Fragment,{children:[fr(e),` last answered with `,(0,Q.jsx)(`strong`,{children:r}),` on `,(0,Q.jsx)(`strong`,{children:u(hi(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=>ri(e,e));y+=` ${t} = the ${Tr(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=Jr(r[0],c,e,o);s&&(y+=` Check before: ${u(s)}.`)}let b=wr({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 ${__(u(t.at))}`:__(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)(il,{items:h})]}):(0,Q.jsx)(`ul`,{className:`av-details-list`,children:h.map((e,t)=>(0,Q.jsx)(`li`,{children:e},t))})})]})}function x_({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:fr(e)}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`selected `,(0,Q.jsx)(v_,{state:t.configured}),` · answered `,(0,Q.jsx)(v_,{state:t.served})]}),(0,Q.jsx)(`span`,{className:`av-status text-caution-400`,children:`substituted`})]},e))})}function S_({active:e,label:t,payload:n,metric:r,mode:i,buckets:a,basketChanges:o}){if(!e)return null;let s=c_(a,t);if(!s)return null;let c=_r(s),l=c!==null&&u_(c.start,c.end)?c.start:null,u=zr(s,o),d=l_(s),f=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`trend-tooltip-label`,children:Ur(s)}),u.map(e=>(0,Q.jsxs)(`p`,{className:`trend-tooltip-detail trend-tooltip-note`,children:[f_(e),` `,ri(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:Ug},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-tooltip-name`,children:e_(`mentionShare`,s.mentionShare.scope)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:$e(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`?Vr:Nr}];return(0,Q.jsxs)(`div`,{className:`trend-tooltip`,children:[f,m.map((e,t)=>{let n=String(e.dataKey??e.name??``),a=(i===`byProvider`?i_(s,n,r):null)??r_(s,r),o=e.color??Zg(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:Xg(n)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-value`,children:a.rate===null?n_.value:$e(a.rate)}),(0,Q.jsx)(`span`,{className:`trend-tooltip-count`,children:a_(a)})]})},`${n}-${t}`)}),p]})}function C_({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:[e_(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=Qg(e.mentionShare.scope);i=n>0?`${$e(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=i_(e,n,t);return r?`${fr(n)} ${o_(r,t)}`:`${fr(n)} no data`}).join(`; `):o_(r_(e,t),t);let a=l_(e);return a.length>0&&(i+=`; models: ${a.join(`; `)}`),(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{scope:`row`,children:Ur(e)}),(0,Q.jsx)(`td`,{children:i})]},e.startDate)})})]})})}function w_({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)(()=>Ir(t,n),[t,n]),b=U({queryKey:[`analytics-metrics`,e,c,y,r,h],queryFn:()=>je(e,c,h),staleTime:Ii}),x=b.data??null,S=b.error,C=u===`mentionShare`?`overall`:g,w=(0,Z.useMemo)(()=>x?Hr(x,u,C):null,[x,u,C]),T=x?vr(x):null,E=(0,Z.useMemo)(()=>Sr(T??{}),[T]),D=(0,Z.useMemo)(()=>lr(T??{}),[T]),O=(0,Z.useMemo)(()=>Object.entries(T??{}).filter(([,e])=>e.anchorUnavailable).map(([e])=>e).sort(),[T]),k=(0,Z.useMemo)(()=>x?hr(x):{},[x]),A=(0,Z.useMemo)(()=>x?xr(pr(x)):[],[x]),j=(0,Z.useMemo)(()=>x?cr(x):[],[x]),M=(0,Z.useMemo)(()=>x?dr(x):[],[x]),N=(0,Z.useMemo)(()=>Dr(T??{},k),[T,k]),P=(0,Z.useMemo)(()=>x?br(x):{},[x]),F=(0,Z.useMemo)(()=>Rt(P,{engineName:fr}),[P]),I=(0,Z.useMemo)(()=>{let e=new Map;for(let[t,n]of Object.entries(P).sort(([e],[t])=>e.localeCompare(t))){let r=Rt({[t]:n},{engineName:fr});r?.kind===`no-known-change`&&e.set(t,{text:`${r.text} ${r.detail}`,modelIds:n.modelIds??[]})}return e},[P]),L=(0,Z.useMemo)(()=>{let e=new Map(i.map(e=>[st(e),e]));return t=>e.get(st(t))??t},[i]),R=u!==`mentionShare`&&C===`byProvider`,z=x?.buckets??[],B=z[z.length-1]?.mentionShare.scope??x?.mentionShareScope??`pooled`,ee=e_(u,B),te=R?gi.textDim:u===`cited`?Si.positive:u===`mentionShare`?Ug:li[1],ne=(0,Z.useMemo)(()=>{let e=new Map(z.map(e=>[e.startDate,kr(e)]));return t=>e.get(String(t))??``},[z]),V=u===`mentionShare`?z.filter(e=>typeof e.mentionShare.rate==`number`&&Number.isFinite(e.mentionShare.rate)):u===`cited`?z.filter(e=>e.citationRate!==null):z,H=V.at(-1),re=(x?ur(x,u):[]).at(-1)??null,se=x?qr(x,u):null,le=Fr(V,j),ue=gr(le,u,B,a),he=re!==null&&se!==null?yn(se.delta):null,ge=he!==null&&!ue,_e=t.length,ve=[];if(re!==null&&H&&ve.push((0,Q.jsxs)(Q.Fragment,{children:[`Latest point: `,(0,Q.jsx)(`strong`,{children:s_(H,u)})]})),H&&se!==null&&le&&!ue&&ve.push(m_(le,H,j)),H&&V.length===1){let e=p_(H,j);e&&!gr(Gr(H,j),u,B,a)&&ve.push(e)}if(he!==null&&V[0]){let e=Ar(V[0]);e&&ve.push((0,Q.jsxs)(Q.Fragment,{children:[`Base: `,(0,Q.jsx)(`strong`,{children:e}),` point`]}))}if(R&&re!==null){let e=u===`cited`&&H&&H.citationNotMeasured>0?`all answers with sources`:`all answers`;ve.push((0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`strong`,{children:$e(re)}),` pools `,e,`; not an average of engines`]}))}let ye=[...new Set([...E.buckets.map(e=>e.bucketStartDate),...z.filter(e=>zr(e,j).length>0).map(e=>e.startDate)])].sort(),be=re!==null&&H&&(0,Q.jsxs)(`div`,{className:`visibility-trend-current`,children:[(0,Q.jsx)(`span`,{className:`visibility-trend-current-dot`,style:{backgroundColor:te},"aria-hidden":`true`}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-label`,children:[ee,!m&&u!==`mentionShare`?` · ${h} queries`:``]}),(0,Q.jsxs)(`span`,{className:`visibility-trend-current-value`,children:[$e(re),m?(0,Q.jsxs)(`span`,{className:`sr-only`,children:[` · `,h,` queries`]}):null]}),w?.rows.length===1&&(0,Q.jsx)(X,{text:`This view has one measurement point. A trend needs at least two comparable points.`,placement:`bottom`}),he!==null&&(0,Q.jsx)(`span`,{className:`visibility-trend-current-delta ${ge?`text-muted`:Kg[he.direction]}`,children:qg(he)}),ge&&le?(0,Q.jsx)(X,{tone:`caution`,label:`Queries changed`,text:g_(le)}):null]}),xe=(0,Q.jsxs)(`div`,{className:`visibility-trend-controls`,children:[(0,Q.jsx)(nc,{options:Hg,value:u,onChange:d,label:`Metric`,className:`visibility-trend-metric-control`}),u!==`mentionShare`&&(0,Q.jsx)(nc,{options:Bg,value:g,onChange:_,label:`Series`}),(0,Q.jsx)(nc,{options:Jh,value:c,onChange:l,label:`Time window`,className:`sm:ml-auto`})]}),Se;if(S)Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative-400`,children:Oe(S)});else if(b.isLoading&&!x)Se=(0,Q.jsx)(`div`,{className:`visibility-trend-chart animate-pulse rounded-md bg-bg-elevated/40`,"aria-hidden":`true`});else if(u===`mentionShare`&&_e===0)Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Add tracked competitors to measure mention share over time.`});else if(!x||!w)Se=null;else{let{rows:e,series:t,hasData:n}=w;if(!n)Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:u===`mentionShare`?`No answer-text brand mentions for you or tracked competitors in ${Qg(B)} in this window yet.`:h===`all`?mt()?ms:`Run a check to start tracking citations and mentions over time.`:`No ${h} answers in this window.`});else if(u===`cited`&&!Or(x))Se=(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:n_.window});else if(R&&t.length===0)Se=(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`No per-engine breakdown for this data yet. Switch to `,(0,Q.jsx)(`span`,{className:`text-strong`,children:`All engines`}),` to see the trend.`]});else{let n=`${ee} rate${h===`all`?``:` in ${h} answers`} across ${e.length} ${e.length===1?`check`:`checks`}. Latest ${$e(re)}${he===null?``:`, ${Jg(he)}${ge?`, not the same queries`:``}`}.`;Se=(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`p`,{className:`sr-only`,children:n}),(0,Q.jsx)(C_,{buckets:z,metric:u,mode:C,series:t,mentionShareScope:B}),R&&t.length>0&&(0,Q.jsx)(`ul`,{className:`trend-legend`,"aria-label":`Engines`,children:t.map((e,t)=>{let n=Wr(x,e,u);return(0,Q.jsxs)(`li`,{className:`trend-legend-item`,children:[(0,Q.jsx)(`span`,{className:`trend-legend-swatch`,style:{backgroundColor:Zg(e,t)},"aria-hidden":`true`}),(0,Q.jsx)(`span`,{className:`trend-legend-name`,children:Xg(e)}),n===null?u===`cited`&&Cr(x,e)&&(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:n_.value}):(0,Q.jsx)(`span`,{className:`trend-legend-value`,children:$e(n)})]},e)})}),(0,Q.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"aria-label":`${ee} trend chart over ${e.length} ${e.length===1?`point`:`points`}`,children:(0,Q.jsx)(ce,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(pe,{data:e,margin:{top:8,right:20,bottom:0,left:0},children:[(0,Q.jsx)(ie,{stroke:wi,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`date`,tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:ne,minTickGap:24}),(0,Q.jsx)(de,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:e=>$e(e,Lt.percent),tick:xi,tickLine:!1,axisLine:!1,width:48}),(0,Q.jsx)(ae,{cursor:{stroke:Ei,strokeWidth:1},content:(0,Q.jsx)(S_,{metric:u,mode:C,buckets:z,basketChanges:j})}),ye.map(e=>(0,Q.jsx)(me,{x:e,stroke:Wg,strokeDasharray:`4 4`,strokeWidth:1.5,ifOverflow:`extendDomain`},`setup-change-${e}`)),t.map((e,t)=>(0,Q.jsx)(fe,{type:`monotone`,dataKey:e,name:e,stroke:Zg(e,t),strokeDasharray:e===`__mentionShare__`?`5 4`:void 0,strokeWidth:Yg(e)?2.5:2,dot:e===`__mentionShare__`?{r:2.75,fill:`var(--chart-tooltip-bg)`,stroke:Zg(e,t),strokeWidth:1.5}:{r:2.5,fill:Zg(e,t),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Gg},connectNulls:e!==Er,isAnimationActive:!1},e))]})})}),ye.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:t_(B)})]}),H?(0,Q.jsx)(`p`,{className:`av-card-meta`,children:Ur(H)}):null]}),(0,Q.jsxs)(`div`,{className:`visibility-trend-body`,children:[F?.kind===`change`&&(0,Q.jsx)(`p`,{className:`mb-3 rounded-md border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-copy-13 text-secondary`,children:F.text}),m&&(0,Q.jsx)(`div`,{className:`mb-3`,children:(0,Q.jsx)(nc,{options:Vg,value:f,onChange:p,label:`Query type`})}),be,xe,Se]}),(0,Q.jsx)(il,{items:ve})]}),x&&!S?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(b_,{buckets:z,queryChanges:M,modelRows:N,served:k,pointerNotices:I,truncated:D,incompleteHistory:O,queryName:L,sweepTimes:o}),(0,Q.jsx)(x_,{substitutions:A})]}):null]})}var T_=new Set([er.queued,er.running]),E_={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 D_({projectName:e,onReviewForTracking:t,scopeOptions:n,planRevision:r,selectedScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c=[],viewerResearchConfig:l=null}){let u=R(),{account:d,canWrite:f}=ji(),p=d?.role===`viewer`&&l!==null,m=!f,h=tt(),[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=U({...So({client:q,path:{name:e}}),staleTime:6e4}),k=U({...Ko({client:q}),enabled:!m&&!h,staleTime:6e4}),A={client:q,path:{name:e},query:{limit:20}},j=B({...la(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=>T_.has(e.status)))?3e3:!1}),M=j.isError&&!j.isFetchNextPageError,N=j.data?.pages.at(-1),P=M?[]:[...new Map((j.data?.pages.flatMap(e=>e.runs)??[]).map(e=>[e.id,e])).values()],F=N?.access?.canRun??(f||p),I=N?.access?N.access.dailyRunLimit:p?l.viewerDailyRunLimit:null;(0,Z.useEffect)(()=>{!b&&P[0]&&x(P[0].id)},[P,b]);let L=P.find(e=>e.id===b)??null,z=U({...na({client:q,path:{name:e,runId:b??``}}),enabled:!M&&!!b,refetchInterval:L&&T_.has(L.status)?3e3:!1}),ee=M||z.isError?null:z.data??null,te=O.data?.locations??[],ne=(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=ds(e),r=new Map((k.data?.providers??[]).filter(e=>e.configured).map(e=>[e.name,e])),i=[...r.values()].filter(e=>!Es(e.name,n)&&!mn(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=>ls(e,Fs)&&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=>mn(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(mn).flatMap(n=>{let r=Xe(n);if(!r)return[];let i=t.get(n),a=s.get(n),c=i??(o?{...o,name:n,displayName:fr(n,[...e,...s.values()]),modelConfigurable:!1,defaultModel:r,knownModels:o.knownModels.filter(e=>e.id===r)}:a);return c?[{name:n,displayName:fr(n,[...e,...s.values()]),configured:!0,defaultModel:r,catalog:c}]:[]});return[...i,...c,...a]},[N?.providers,m,O.data?.providers,k.data]),V=!(m?j.isPending:k.isPending)&&ne.length===0,H=ne.find(e=>e.name===g)??null;(0,Z.useEffect)(()=>{if(!g&&O.data&&!O.isError&&!k.isError){let e=ne.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,ne,O.data,O.isError,k.isError]);let ie=H?.catalog.modelConfigurable??!1,ae=m?H?.catalog.defaultModel:(H?O.data?.providerModels[H.name]:``)||H?.catalog.defaultModel,oe=(ie?v.trim():``)||ae,se=H?[...new Map([{id:H.catalog.defaultModel,displayName:mr(H.catalog.defaultModel)},...v.trim()?[{id:v.trim(),displayName:mr(v.trim())}]:[],...H.catalog.knownModels].map(e=>[e.id,e])).values()]:[],ce=re({...yo(),onSuccess:async e=>{w.current=null,D(e=>e+1),C(e.runs),x(e.runs[0]?.id??null),await U_(u),Ni({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=>{Ni({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)(rs,{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)(A_,{projectName:e,canWrite:f,researchAllowed:F&&!M,limitedAccess:m,isEmbed:G(),scopeOptions:n??[],planRevision:r??i?.planRevision??null,initialScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c,locations:te,defaultLocation:O.data?.defaultLocation??null,providerOptions:ne,provider:g,onProviderChange:e=>{_(e),y(``)},resolvedModel:oe,visibilityModel:ae,configurableModel:ie,model:v,onModelChange:y,modelOptions:se,settingsReady:m?!j.isPending&&!M:!k.isPending&&!k.isError&&!k.isFetching,projectReady:!O.isPending&&!O.isError&&!O.isFetching,isPending:ce.isPending,errorMessage:ce.isError?`The request could not be confirmed.`:void 0,onSubmit:(t,n)=>{!F||M||G()||T.current||(w.current?.fingerprint!==n&&(w.current={fingerprint:n,key:crypto.randomUUID()}),T.current=!0,ce.mutate({client:q,path:{name:e},body:{...t,idempotencyKey:w.current.key}}))}},`${e}:${E}`),I!==null&&(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Up to `,I,` destination runs per project per day.`]}),!m&&k.isError?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load API providers.`}),(0,Q.jsx)(J,{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)(J,{variant:`outline`,onClick:()=>{O.refetch()},children:`Retry locations`})]}):null,!(m?M:k.isError)&&V&&(0,Q.jsx)(`p`,{className:`rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-copy-14 text-caution`,children:m?`No research engines are available. Ask your Canonry team to configure one.`:`Configure an API provider in Settings before starting research. Browser engines are not available for this workflow.`}),S.length>0&&(0,Q.jsxs)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:[`Saved runs: `,S.map((e,t)=>(0,Q.jsxs)(`span`,{children:[t>0?`, `:``,(0,Q.jsxs)(`a`,{href:`#research-run-${e.id}`,className:`text-link underline`,onClick:()=>x(e.id),children:[e.scope?.label??`Whole site`,e.location?`, ${e.location.label}`:`, No location`]})]},e.id))]})]}),(0,Q.jsxs)(rs,{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:E_.historyTitle})}),j.isFetching&&(0,Q.jsx)(Y,{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)(J,{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:E_.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:z_(e.createdAt)})}),(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`span`,{className:`block`,title:e.provider,children:fr(e.provider,k.data?.providerCatalog)}),(e.requestedModel??e.resolvedModel)!==Xe(e.provider)&&(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,title:e.requestedModel??e.resolvedModel,children:mr(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)(Y,{tone:V_(e.status),children:e.status})})]},e.id))})]})}),j.isFetchNextPageError&&(0,Q.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:E_.historyMoreError}),j.hasNextPage&&(0,Q.jsx)(J,{className:`mt-3`,variant:`outline`,disabled:j.isFetching,onClick:()=>{j.fetchNextPage()},children:j.isFetchingNextPage?E_.historyLoading:E_.historyMore})]})]}),!M&&z.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)(J,{variant:`outline`,onClick:()=>{z.refetch()},children:`Retry results`})]}):!M&&(ee||b)?(0,Q.jsx)(F_,{detail:ee,engineLabel:ee?fr(ee.provider,k.data?.providerCatalog):void 0,isLoading:z.isFetching,onReviewForTracking:h?void 0:t}):null]})}var O_=`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`,k_=`__none__`;function A_(e){let{projectName:t,locations:n,provider:r,resolvedModel:i,planRevision:a}=e,o=e.providerOptions.map(e=>({...e,knownModels:e.catalog.knownModels})),s=Xe(r),c=[r?fr(r,o):`Choose an engine`,i&&i!==s?mr(i):i?null:`Choose a model`].filter(Boolean).join(` · `),l=R(),[u,d]=(0,Z.useState)(`once`),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(``),[_,v]=(0,Z.useState)(e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`),[y,b]=(0,Z.useState)(null),[x,S]=(0,Z.useState)([]),[C,w]=(0,Z.useState)(``),[T,E]=(0,Z.useState)({}),[D,O]=(0,Z.useState)(null),[k,j]=(0,Z.useState)([]),[M,N]=(0,Z.useState)(null),[P,F]=(0,Z.useState)(!1),[I,L]=(0,Z.useState)(!1),[z,B]=(0,Z.useState)(``),[ee,te]=(0,Z.useState)(``),ne=(0,Z.useRef)(null),V=(0,Z.useRef)(!1),H=(0,Z.useRef)(null),U=e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`;(0,Z.useEffect)(()=>{v(U),O(null)},[U]);let ie=e.scopeOptions.filter(e=>e.kind===`market`||e.kind===`property`),ae=u===`markets`?`market`:`property`,oe=ie.filter(e=>e.kind===ae),se=t=>({kind:t.kind,key:t.id,label:t.label,planRevision:a??e.initialScope?.planRevision??0}),ce=e=>e===k_?null:n.find(t=>t.label===e),le=y??e.defaultLocation??k_,ue=ie.find(e=>`${e.kind}:${e.id}`===_),de=ue?se(ue):null,fe=u===`once`?[{scope:de,location:ce(le)}]:u===`locations`?x.map(e=>({scope:null,location:ce(e)})):x.map(e=>oe.find(t=>`${t.kind}:${t.id}`===e)).map(e=>e?{scope:se(e),location:ce(T[`${e.kind}:${e.id}`]??k_)}:null),pe=[...new Map([...k,...e.templates].map(e=>[e.id,e])).values()],me=D?pe.find(e=>e.id===D.id):null,he=D!==null&&me?.version!==D.version,ge=u===`once`?f:m,_e=ge.split(/\r?\n/).filter(e=>e.trim()),ve=pt(_e),ye=[...new Set([...m.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))],be=/[{}]/.test(m.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,``)),xe=[];_e.length||xe.push(u===`once`?`Enter at least one query.`:`Enter at least one query pattern.`),_e.some(e=>e.length>4e3)&&xe.push(`Keep each query under 4,001 characters.`),u!==`once`&&be&&xe.push(`Use the name buttons to insert a supported variable. Remove unknown or incomplete braces.`),fe.length||xe.push(u===`locations`?`Select at least one location.`:`Select at least one destination.`),fe.some(e=>!e||e.location===void 0)&&xe.push(`A selected destination or location is no longer available. Update your selection.`);let Se=u===`once`&&_!==`project`||u===`markets`||u===`properties`;Se&&(e.scopePending||e.scopeError||!a||fe.some(e=>!e?.scope))&&xe.push(`Load the current published markets and properties before running scoped research.`);let Ce=(u===`once`?ve.length:_e.length)*fe.length;if(fe.length>20&&xe.push(`Select at most 20 destinations.`),Ce>50&&xe.push(`${Ce} queries selected. Reduce the selection to 50 or fewer.`),he&&xe.push(`This saved pattern changed. Select its current version from Saved patterns.`),u!==`once`&&!be){for(let e of fe)if(e&&e.location!==void 0)try{Ae(D??{pattern:m,variables:ye},e.scope,e.location)}catch{xe.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:ge,contexts:fe,provider:r,resolvedModel:i,template:D,...Se?{planRevision:a}:{}}),Te=M!==null&&M.signature!==we,Ee=u===`once`?ve.map((e,t)=>({id:String(t),query:e,scope:de,location:fe[0]?.location??null})):M?.rows??[],De=P_(Ee),Oe=[];u!==`once`&&M&&(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=>pt(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)&&!xe.length&&!Oe.length&&(u===`once`||M!==null),G=()=>({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(F(!0),xe.length)return;let e=fe.flatMap((e,t)=>_e.map((n,r)=>({id:`${t}:${r}`,scope:e.scope,location:e.location,...D?{template:{templateId:D.id,templateVersion:D.version,bindingLocation:e.location}}:{},query:Ae({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(``),F(!1)},Ne=e=>{if(te(``),u===`once`)try{p(Ae(e,de,ce(le)).output)}catch{te(`Select a matching market, property, or location before using this pattern.`);return}else h(e.pattern);O(e)},Pe=e=>{let t=H.current,n=t?.selectionStart??m.length,r=t?.selectionEnd??n;h(`${m.slice(0,n)}{${e}}${m.slice(r)}`),O(null),requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(n+e.length+2,n+e.length+2)})},Fe=re({...ts(),onSuccess:async e=>{let n={id:e.id,version:e.updatedAt,label:e.name,pattern:e.pattern,variables:e.variables};j(t=>[...t.filter(t=>t.id!==e.id),n]),O(n),L(!1),B(``),te(``),ne.current=null,await l.invalidateQueries({queryKey:Ia({client:q,path:{name:t}})}),Ni({title:`Pattern saved`,detail:`Available in Saved patterns. Tracking was not changed.`,tone:`positive`})},onError:()=>te(`Could not save the pattern. Your text is preserved. Retry to save the same pattern.`),onSettled:()=>{V.current=!1}}),Ie=()=>{if(!e.canWrite||e.isEmbed||V.current)return;let n=u===`once`?f:m,r=u===`once`?[]:ye;if(!z.trim()||!n.trim()||n.length>4e3||u!==`once`&&be){te(`Enter a name and a valid pattern of 1 to 4,000 characters.`);return}let i={name:z.trim(),pattern:n,variables:r},a=JSON.stringify(i);ne.current?.fingerprint!==a&&(ne.current={fingerprint:a,id:crypto.randomUUID()}),V.current=!0,Fe.mutate({client:q,path:{name:t,templateId:ne.current.id},body:i})},Le=[...new Set([...P||ge.trim()?xe:[],...Oe])],Re=pe.filter(e=>{let t=u===`once`?W(de,ce(le)):W(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)(rs,{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:O_,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:!ie.some(e=>e.kind===`market`),children:`Repeat across markets`}),(0,Q.jsx)(`option`,{value:`properties`,disabled:!ie.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:[(ie.length>0||_!==`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:O_,value:_,onChange:e=>{v(e.target.value),O(null)},children:[(0,Q.jsx)(`option`,{value:`project`,children:`Whole site`}),_!==`project`&&!ue&&(0,Q.jsx)(`option`,{value:_,disabled:!0,children:`Selected destination unavailable`}),ie.map(e=>(0,Q.jsxs)(`option`,{value:`${e.kind}:${e.id}`,children:[e.label,` (`,e.kind,`)`]},`${e.kind}:${e.id}`))]})]}),(0,Q.jsx)(j_,{label:`Answer engine location`,value:le,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:O_,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})):oe.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)(j_,{label:`Answer engine location for ${e.label}`,value:T[e.key]??k_,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)(J,{variant:`outline`,onClick:e.onRetryScope,children:`Retry destinations`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`block`,htmlFor:`research-query-editor`,children:(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:u===`once`?`Queries`:`Query pattern`})}),(0,Q.jsx)(`p`,{id:`research-query-guidance`,className:`mt-1 text-copy-14 text-secondary`,children:u===`once`?`Enter one query per line. The answer engine receives exactly this text.`:`Use {${u===`markets`?`market`:u===`properties`?`property`:`location`}} where each name belongs. Preview the resolved queries before running.`}),(0,Q.jsx)(`textarea`,{id:`research-query-editor`,ref:H,className:`${O_} min-h-32`,"aria-describedby":`research-query-guidance research-query-count`,value:ge,placeholder:u===`once`?E_.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)(J,{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:[Ce,` / `,50,` queries`,u===`once`?``:` across ${fe.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.`}),Re.length?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Re.map(e=>(0,Q.jsx)(J,{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)(J,{size:`sm`,variant:`outline`,onClick:()=>L(!I),children:I?`Cancel save`:`Save as a pattern`}),I&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,Q.jsxs)(`label`,{className:`min-w-48 flex-1 text-label-14 text-heading`,children:[`Pattern name`,(0,Q.jsx)(`input`,{className:O_,value:z,maxLength:120,onChange:e=>B(e.target.value)})]}),(0,Q.jsx)(J,{size:`sm`,disabled:Fe.isPending||!z.trim()||!ge.trim(),onClick:Ie,children:Fe.isPending?`Saving…`:`Save pattern`})]})]}),ee&&(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:ee})]})]}),(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:O_,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:fr(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:O_,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?` · ${mr(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:O_,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)(N_,{errors:Le}),u!==`once`&&(0,Q.jsxs)(`div`,{className:`space-y-4 border-t border-default pt-4`,children:[(0,Q.jsxs)(J,{variant:`outline`,size:`sm`,disabled:e.isPending||!e.projectReady,onClick:je,children:[(0,Q.jsx)(g,{size:14}),M?E_.refreshPreview:`Preview queries`]}),M&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Queries to run`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[Ee.length,` query executions in `,De.length,` saved runs · `,c,`. Edit any query or location below.`]}),(0,Q.jsx)(M_,{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)(J,{size:`sm`,disabled:!ke,onClick:()=>{if(ke){let n=G();e.onSubmit(n,JSON.stringify({projectName:t,...n}))}},children:[(0,Q.jsx)(A,{size:14}),e.isPending?`Starting…`:E_.runAction]}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[u===`once`?`${ve.length} queries`:`${Ee.length} reviewed queries`,` · `,c]})]})]})]})}function j_({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:O_,value:t,onChange:e=>r(e.target.value),children:[(0,Q.jsx)(`option`,{value:k_,children:`No location context`}),n.map(e=>(0,Q.jsx)(`option`,{value:e.label,children:e.label},e.label))]})]})}function M_({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:`${O_} 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)(j_,{label:`Location for query ${r+1}`,value:e.location?.label??k_,locations:t,onChange:r=>n(e.id,{location:t.find(e=>e.label===r)??null})})]},e.id))})}function N_({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 P_(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 F_({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)(rs,{id:e?`research-run-${e.id}`:void 0,className:`surface-card min-w-0`,role:`region`,"aria-label":E_.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 ${B_(e.id)}`:E_.resultsEmpty})}),e&&(0,Q.jsx)(Y,{tone:V_(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??fr(e.provider)})]}),(e.requestedModel??e.resolvedModel)!==Xe(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:mr(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:E_.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:E_.methodologySummary}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-prose text-copy-14`,children:E_.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)(Y,{tone:e.queryClass===`branded`?`positive`:e.queryClass===`non-brand`?`neutral`:`caution`,children:e.queryClass===`branded`?E_.brandedQuery:e.queryClass===`non-brand`?E_.discoveryQuery:E_.unclassifiedQuery})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Y,{tone:H_(e.status),children:e.status})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Y,{tone:e.answerMentioned===!0?`positive`:e.answerMentioned===!1?`neutral`:e.status===Te.failed?`negative`:`caution`,children:e.answerMentioned===null?e.status===Te.failed?`Unavailable`:`Pending`:e.answerMentioned?`Matched`:`No match`})}),(0,Q.jsx)(`td`,{children:e.citationMeasured===!1&&e.status===Te.completed?(0,Q.jsx)(Y,{tone:`neutral`,children:`Not measured`}):(0,Q.jsx)(Y,{tone:e.citationState===`cited`?`positive`:e.citationState===`not-cited`?`neutral`:e.status===Te.failed?`negative`:`caution`,children:e.citationState===null?e.status===Te.failed?`Unavailable`:`Pending`:e.citationState===`cited`?`Cited`:`Not cited`})})]},e.id))})]})}),(0,Q.jsx)(I_,{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 I_({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})]}),!G()&&r&&(0,Q.jsxs)(`div`,{className:`material-base px-3 py-3`,children:[(0,Q.jsx)(Rr,{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)(Ks,{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)(Ks,{headingLevel:4,copyable:!0,children:e.answerText})})]}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:e.status===Te.failed?`This query did not return an answer.`:e.status===Te[`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)(rc,{url:e.uri,title:e.title})},`${e.uri}-${t}`))})]}),e.evidence&&(0,Q.jsx)(R_,{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 L_={"explicit-citation":`Cited in the answer`,"answer-support":`Used for the answer`,"search-result":`Search result`,"page-read":`Page read`};function R_({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:Bt(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:Sn(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:L_[e.relationship]}),(0,Q.jsx)(rc,{url:e.url,title:e.title??e.url})]},`${e.url}-${t}`))})]})}function z_(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 B_(e){return e.length>8?e.slice(0,8):e}function V_(e){return e===er.completed?`positive`:e===er.partial||e===er[`waiting-upstream`]?`caution`:e===er.failed?`negative`:`neutral`}function H_(e){return e===Te.completed?`positive`:e===Te.failed?`negative`:e===Te[`waiting-upstream`]?`caution`:`neutral`}async function U_(e){await Pi(e,`researchRuns`)}var W_=new Set([`queued`,`seeding`,`probing`]);function G_({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}=ji(),[d,f]=(0,Z.useState)(`tracked`),[p,m]=(0,Z.useState)(`find`),[h,g]=(0,Z.useState)(null),_=u?.role===`viewer`?Kt():null,v=Uc(u?.role,_),y=Wc(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)(Xc,{id:x,label:`Query workspace`,value:y,onChange:S,className:`flex border-b border-default`,tabClassName:K_,activeTabClassName:q_,inactiveTabClassName:J_,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)(jv,{projectName:e,selection:a,onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,pendingTrackingSource:h,onPendingTrackingSourceHandled:()=>g(null),publishGuard:l}):(0,Q.jsx)(Y_,{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 K_=`-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`,q_=`border-mono-400 text-heading`,J_=`border-transparent text-muted hover:border-strong hover:text-strong`;function Y_({projectName:e,selection:t,mode:n,onModeChange:r,onReviewSavedSource:i,viewerResearchConfig:a}){let{canWrite:o}=ji(),s=(0,Z.useId)(),c=!o||n===`test`,l=U({...xa({client:q,path:{name:e}}),enabled:c,staleTime:6e4}),u=U({...Xo({client:q,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)(Xc,{id:s,label:`Research workspace`,value:n,onChange:r,className:`flex border-b border-default`,tabClassName:K_,activeTabClassName:q_,inactiveTabClassName:J_,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)(Mv,{projectName:e,onReviewDiscoveryProbe:e=>i({source:`discovery`,discoveryProbeId:e})}):(0,Q.jsx)(D_,{...p,onReviewForTracking:({researchRunQueryId:e,scope:t})=>i({source:`research`,researchRunQueryId:e},t??null)})})]}):(0,Q.jsx)(D_,{...p,viewerResearchConfig:a})}function X_({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,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(()=>Z_(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=Gc(e,t),O=(0,Z.useMemo)(()=>sv(e.tracked,t,e.mode),[t,e.mode,e.tracked]),k=O.some(e=>e.provenance!==null),A=jl({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}:${lv(t)}`;if(E.current===n)return;let i=e.tracked.find(e=>e.queryId===r);i&&(E.current=n,v({kind:`edit`,row:i,audience:e.mode===`advanced`?iv(t):void 0,scopeLabel:av(t,e)}),b(Q_(i,t)),S(null))},[t,r,D,e]),(0,Z.useEffect)(()=>{if(D||!a)return;let e=Z_(a.trackingSelection??t);v({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&&(v(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`){v({kind:`add`}),b({...Z_(t),source:e}),S(null),i?.(void 0)}function M(n){E.current=`${n.queryId}:${lv(t)}`,v({kind:`edit`,row:n,audience:e.mode===`advanced`?iv(t):void 0,scopeLabel:av(t,e)}),b(Q_(n,t)),S(null),i?.(n.queryId)}function N(n){E.current=`${n.queryId}:${lv(t)}`,v({kind:`remove`,row:n,audience:e.mode===`advanced`?iv(t):void 0,scopeLabel:av(t,e)}),S(null),i?.(n.queryId)}function P(){T.current=!0,v(null),b(Z_(t)),S(null),i?.(void 0)}let F=g?$_(g,y,e):null,I=g!==null&&g.kind===`add`&&e.mode===`advanced`&&!nv(y),L=F!==null&&(!I||y.contexts.length>0)&&!u&&!d;return D?(0,Q.jsx)(`div`,{className:`query-tracking-workspace space-y-4`,children:(0,Q.jsxs)(`section`,{"aria-label":`Tracked queries`,className:`py-4 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`p`,{children:[`This saved `,t.measurementScope,` filter is unavailable in the current measurement.`]}),(0,Q.jsx)(J,{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)(cv,{selection:t,onSelectionChange:n}):null,(0,Q.jsx)(Ml,{value:A.query,onChange:A.setQuery,label:`Filter tracked queries`,placeholder:`Search tracked queries`,className:`min-w-64 flex-[2]`}),!G()&&(0,Q.jsx)(`div`,{ref:w,children:(0,Q.jsxs)(Rr,{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)(fv,{row:n,workspace:e,selection:t})}):null,e.mode===`advanced`?(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(mv,{row:n})}):null,k?(0,Q.jsx)(`td`,{className:`whitespace-nowrap text-secondary`,children:uv(n)}):null,(0,Q.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,Q.jsx)(hv,{row:n,outsidePlan:e.mode===`advanced`&&n.assignments.length===0})}),(0,Q.jsx)(`td`,{className:`measurement-table-actions whitespace-nowrap text-right`,children:!G()&&(0,Q.jsxs)(`div`,{className:`tracking-row-actions flex min-w-max justify-end gap-2`,children:[(0,Q.jsxs)(Rr,{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)(Rr,{type:`button`,variant:`ghost`,size:`sm`,disabled:d,"aria-label":`Remove ${n.queryText}`,onClick:()=>N(n),children:[(0,Q.jsx)(_,{"aria-hidden":`true`,size:13}),` Remove`]})]})})]},n.queryId))})]})}),(0,Q.jsx)(Nl,{page:A.page,pageSize:A.pageSize,visibleRows:A.rows.length,totalRows:A.totalRows,itemLabel:`queries`,onPageChange:A.setPage})]}),g&&!G()&&(0,Q.jsx)(`fieldset`,{disabled:d,"aria-busy":d,className:`m-0 min-w-0 border-0 p-0`,children:(0,Q.jsx)(gv,{workspace:e,templates:c,action:g,draft:y,onDraftChange:e=>{b(e),S(null)},onClose:P,canReview:L,isPreviewing:u,editorHeadingRef:C,onReview:()=>{F&&(S(F),p(F))}})}),l&&x&&g&&(0,Q.jsx)(Ev,{preview:l,workspace:e,isCommitting:d,sweepActive:h?.sweepActive??!1,onConfirm:Mi(async()=>{await m({...x,expectedWorkspaceVersion:l.workspaceVersion,previewToken:l.previewToken,reviewedAt:l.reviewedAt})&&P()})})]})}function Z_(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 Q_(e,t){return{...Z_(t),text:e.queryText,queryClass:`keep`}}function $_(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=ev(t);if(!i||rv(t)||r&&!t.wholeSite&&t.targetKeys.length+t.groupKeys.length+t.marketKeys.length===0)return null;let a=r?tv(t,n):void 0;return{additions:[{input:i,...a?{audience:a}:{},...r&&!nv(t)&&t.contexts.length>0?{contexts:t.contexts}:{},...r&&t.queryClass!==`auto`&&t.queryClass!==`keep`?{queryClass:t.queryClass}:{}}],removals:[]}}function ev(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 tv(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 nv(e){return e.marketKeys.length>0&&e.targetKeys.length===0&&e.groupKeys.length===0}function rv(e){return e.source===`template`&&e.template.includes(`{market}`)&&(e.wholeSite||e.marketKeys.length===0)}function iv(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 av(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 ov(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 sv(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=>ov(e,t)))}function cv({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 lv(e){return e.measurementScopeKey&&e.measurementScope!==`project`?`${e.measurementScope}:${e.measurementScopeKey}`:`project`}function uv(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 dv(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=>ov(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 fv({row:e,workspace:t,selection:n}){let r=pv(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:dv(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 pv(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=>ov(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 mv({row:e}){let t=[...new Set(e.assignments.map(e=>e.queryClass??`unknown`))],n=t.join(`, `);return(0,Q.jsx)(Y,{tone:t.includes(`unknown`)?`caution`:`neutral`,children:n||`Unknown`})}function hv({row:e,outsidePlan:t=!1}){return t?(0,Q.jsx)(Y,{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)(Y,{tone:`positive`,children:`Measured`}),e.lastMeasuredAt?(0,Q.jsx)(`time`,{className:`text-copy-13 text-secondary`,dateTime:e.lastMeasuredAt,title:vi(e.lastMeasuredAt),children:Zr(e.lastMeasuredAt)}):null]}):(0,Q.jsx)(Y,{tone:`caution`,children:`Awaiting check`})}function gv({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)(rs,{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)(Tv,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):n.kind===`edit`?(0,Q.jsxs)(rs,{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)(J,{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)(Tv,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):(0,Q.jsxs)(rs,{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)(J,{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)(_v,{templates:t,advanced:e.mode===`advanced`,draft:r,onDraftChange:i}):null,r.source===`research`?(0,Q.jsx)(vv,{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)(vv,{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)(wv,{workspace:e,draft:r,onDraftChange:i}):null]}),e.mode===`advanced`&&!nv(r)?(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Cv,{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)(Tv,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]})}function _v({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":rv(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]}),rv(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 vv({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 yv(e){return{providers:[...e.providers],models:{...e.models},location:e.location?.label??null}}function bv(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 xv(e){return[...new Map(e.map(e=>[bv(e),e])).values()]}function Sv(e){let t=e.providers.map(t=>{let n=e.models[t];return n&&n!==Xe(t)?`${fr(t)} (${Xe(t)?mr(n):n})`:fr(t)}).join(`, `);return`${e.location??`No location`} · ${t}`}function Cv({workspace:e,draft:t,onDraftChange:n}){let r=(0,Z.useMemo)(()=>xv([...e.defaultContexts.map(yv),...t.contexts]),[t.contexts,e.defaultContexts]),i=t.contexts.length===1?bv(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=>bv(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:bv(e),children:Sv(e)},bv(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 wv({workspace:e,draft:t,onDraftChange:n}){let{canWrite:r}=ji(),[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)(J,{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)(Ml,{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 Tv({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)(Rr,{type:`button`,size:`sm`,disabled:!e,onClick:r,children:t?`Reviewing…`:`Review changes`}),(0,Q.jsx)(J,{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 Ev({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)(rs,{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:Dv(e)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:s})]}),(0,Q.jsx)(Y,{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)(Ov,{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)(Ov,{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)(Rr,{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 Dv(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 Ov({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`:Av(t,r,n)}),e===`Added`||e===`Reused`?(0,Q.jsx)(kv,{row:r.find(e=>e.queryId===t.queryId),workspace:n}):null]},`${e}:${t.queryId}`))})]})}function kv({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=>Sv(yv(e))).join(`; `);return(0,Q.jsx)(`li`,{children:[r,i,a].filter(Boolean).join(` · `)},`${e.targetKey}:${n}`)})})]})}function Av(e,t,n){let r=t.find(t=>t.queryId===e.queryId);if(!r)return`${e.assignmentCount} ${e.assignmentCount===1?`assignment`:`assignments`}`;let i=xv(r.assignments.flatMap(e=>e.contexts).map(yv)),a=i.length===1?Sv(i[0]):i.length>1?`${i.length} contexts`:null;return[dv(r,n),a].filter(e=>e!==null).join(` · `)}function jv({projectName:e,selection:t={measurementScope:`project`,queryClass:`all`},onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s}){let c=R(),[l,u]=(0,Z.useState)(null),d=U({...xa({client:q,path:{name:e}})}),f=U({...Xo({client:q,path:{name:e}}),staleTime:6e4}),p=re({...Ui(),onSuccess:e=>u(e),onError:async t=>{u(null),await c.invalidateQueries({queryKey:Da({client:q,path:{name:e}})}),Ni({title:`Could not review tracking changes`,detail:t instanceof Error?t.message:`Update the draft and review it again.`,tone:`negative`})}}),m=re({...xo(),onSuccess:async t=>{u(null),i?.(void 0),await zi(c,e),Ni({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 zi(c,e),Ni({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)(rs,{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)(rs,{className:`surface-card`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14 text-negative`,children:`Could not load tracked queries.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void d.refetch(),children:`Try again`})]}):(0,Q.jsx)(X_,{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:q,path:{name:e},body:{...t,expectedWorkspaceVersion:d.data.workspaceVersion}})},onCommit:async t=>{try{return await m.mutateAsync({client:q,path:{name:e},body:t}),!0}catch{return!1}}})}function Mv({projectName:e,onReviewDiscoveryProbe:t}){let n=R(),[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(`100`),l=U({...ma({client:q,path:{name:e},query:{limit:`10`}}),refetchInterval:e=>e.state.data?.some(e=>W_.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=U({...sa({client:q,path:{name:e,id:r??``}}),enabled:!!r,refetchInterval:d&&W_.has(d.status)?3e3:!1}),p=f.data??null,m=re({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),Fn(e,t)},onSuccess:async t=>{i(t.sessionId),o(``),await zv(n,e,t.sessionId),Ni({title:`Discovery started`,detail:`Run ${Rv(t.sessionId)} is testing questions your customers might ask.`,tone:`neutral`,dedupeKey:`discovery:start:${t.sessionId}`,dedupeMode:`replace`})},onError:e=>{Ni({title:`Discovery failed to start`,detail:e instanceof Error?e.message:`Could not start discovery.`,tone:`negative`})}}),h=p??d,_=(0,Z.useMemo)(()=>(p?.probes??[]).slice(0,30),[p?.probes]);async function v(){try{let t=await l.refetch();if(t.error)throw t.error;let n=t.data?.length??0;Ni({title:`Discovery sessions refreshed`,detail:`${n} recent session${n===1?``:`s`} loaded.`,tone:`positive`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}catch(t){Ni({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)(Y,{tone:`neutral`,children:`Runs on Gemini`})]}),(0,Q.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:l.isFetching,onClick:()=>void v(),children:[(0,Q.jsx)(g,{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)(rs,{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)})]}),!G()&&(0,Q.jsxs)(Rr,{type:`button`,size:`sm`,disabled:m.isPending,onClick:()=>m.mutate(),children:[(0,Q.jsx)(A,{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)(Y,{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:Rv(e.id)}),(0,Q.jsx)(Y,{tone:Pv(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 `,Rv(h.id)]}),(0,Q.jsx)(Y,{tone:Pv(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)(Nv,{label:`Questions tested`,value:h.probeCount??0}),(0,Q.jsx)(Nv,{label:`Cited queries`,value:h.citedCount??0,tone:`positive`}),(0,Q.jsx)(Nv,{label:`Worth tracking`,value:h.aspirationalCount??0,tone:`caution`}),(0,Q.jsx)(Nv,{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)(Y,{tone:`neutral`,children:`Loading`})]}),_.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:_.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)(Y,{tone:Fv(e.bucket),children:Lv(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:!G()&&t&&(e.bucket===`cited`||e.bucket===`aspirational`)&&(0,Q.jsx)(Rr,{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 Nv({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 Pv(e){return e===`completed`?`positive`:e===`failed`?`negative`:W_.has(e)?`caution`:`neutral`}function Fv(e){return e===`cited`?`positive`:e===`aspirational`?`caution`:e===`wasted-surface`?`negative`:`neutral`}var Iv={cited:`Cited queries`,aspirational:`Worth tracking`,"wasted-surface":`Skip`};function Lv(e){return e?Iv[e]:`Not classified`}function Rv(e){return e.length>8?e.slice(0,8):e}async function zv(e,t,n){await Promise.all([Pi(e,`discovery`),e.invalidateQueries({queryKey:Xa({client:q})})])}var Bv=4e3,Vv={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 Hv(e){return`canonry:embed-query-draft:${e}`}function Uv(e){try{return window.sessionStorage.getItem(Hv(e))??``}catch{return``}}function Wv(e,t){try{t?window.sessionStorage.setItem(Hv(e),t):window.sessionStorage.removeItem(Hv(e))}catch{}}function Gv(e,t){return e.trim().replace(/\s+/g,` `).toLocaleLowerCase()===t.trim().replace(/\s+/g,` `).toLocaleLowerCase()}function Kv({projectName:e,limit:t}){let n=R(),r=xa({client:q,path:{name:e}}),i=U(r),[a,o]=(0,Z.useState)(()=>Uv(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 v(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 ir(()=>vn({client:q,path:{name:e},body:{...t,expectedWorkspaceVersion:a}}));return n.diff.noOp?`unchanged`:(await ir(()=>Qe({client:q,path:{name:e},body:{...t,expectedWorkspaceVersion:n.workspaceVersion,previewToken:n.previewToken,reviewedAt:n.reviewedAt}})),`saved`)}catch(e){if(e instanceof Pt&&e.code===`EMBED_QUERY_LIMIT`)return`limit`;if(i===0&&e instanceof Pt&&e.code===`QUERY_TRACKING_PREVIEW_STALE`)continue;throw e}}throw Error(`The query list kept changing.`)}async function y(r,i){if(m.some(e=>Gv(e.queryText,r)))return u({kind:`error`,text:Vv.duplicate}),!1;c(i),u(null);try{let i=await v({additions:[{input:{source:`manual`,text:r}}],removals:[]});return i===`unchanged`?(u({kind:`error`,text:Vv.duplicate}),!1):i===`limit`?(u({kind:`error`,text:Vv.limit(t)}),!1):(await zi(n,e),u({kind:`added`,query:r}),!0)}catch{return u({kind:`error`,text:Vv.failed}),!1}finally{c(null)}}async function b(t){t.preventDefault();let n=a.trim();n&&s===null&&!g&&await y(n,`add`)&&(o(``),Wv(e,``),d.current?.focus())}async function x(t,r){if(s===null){c({removing:t.queryId}),u(null);try{await v({additions:[],removals:[{queryId:t.queryId}]}),await zi(n,e),p.current=r,u({kind:`removed`,query:t.queryText})}catch{u({kind:`error`,text:Vv.failed})}finally{c(null)}}}async function S(e){s===null&&await y(e,`undo`)&&d.current?.focus()}if(i.isLoading)return(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,role:`status`,children:Vv.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:Vv.loadFailed}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void i.refetch(),children:Vv.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:Vv.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:Vv.count(m.length,t)}),` · `,h?Vv.nextCheck:Vv.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:Vv.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:Vv.placeholder,maxLength:Bv,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),Wv(e,t.target.value),l?.kind===`error`&&u(null)}}),(0,Q.jsx)(J,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:g||s!==null||!a.trim(),children:s===`add`?Vv.adding:Vv.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:[Vv.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`?Vv.adding:Vv.undo})]}):l?.kind===`added`?(0,Q.jsx)(`span`,{className:`sr-only`,children:Vv.added(l.query)}):null,h&&g&&!C?(0,Q.jsx)(`span`,{className:`block`,children:Vv.limit(t)}):null]})]}),m.length===0?(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:Vv.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)(J,{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":`${Vv.remove} ${e.queryText}`,disabled:s!==null,onClick:()=>void x(e,t),children:[(0,Q.jsx)(_,{"aria-hidden":`true`,size:13}),n?Vv.removing:Vv.remove]}):null]},e.queryId)})})]})}var qv=/^www\./i;function Jv(e){if(!e)return null;try{return new URL(e).hostname}catch{return null}}function Yv(e){return e.trim().toLowerCase().replace(qv,``)}function Xv(e,t){if(!t)return!1;try{return Yv(new URL(e).hostname)===Yv(t)}catch{return!1}}function Zv(e,t){if(!e)return``;if(!Xv(e,t))return e;let n=new URL(e),r=`${n.pathname}${n.search}${n.hash}`;return r===``?`/`:r}function Qv(e,t){return Zv(e.url,t)||e.path||`/`}var $v=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)}})),ey=$v();function ty(){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 ny=ty;typeof Object.assign==`function`&&(ny=Object.assign);function ry(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 iy(e){return typeof e==`object`&&!!e}function ay(e){let t;for(t in e)return!1;return!0}function oy(e,t,n){Object.defineProperty(e,t,{enumerable:!1,configurable:!1,writable:!0,value:n})}function sy(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 cy(e){return!(!iy(e)||e.attributes&&!Array.isArray(e.attributes))}function ly(){let e=Math.floor(Math.random()*256)&255;return()=>e++}function uy(){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 dy(){return{[Symbol.iterator](){return this},next(){return{done:!0}}}}var fy=class extends Error{constructor(e){super(),this.name=`GraphError`,this.message=e}},py=class e extends fy{constructor(t){super(t),this.name=`InvalidArgumentsGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},$=class e extends fy{constructor(t){super(t),this.name=`NotFoundGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}},my=class e extends fy{constructor(t){super(t),this.name=`UsageGraphError`,typeof Error.captureStackTrace==`function`&&Error.captureStackTrace(this,e.prototype.constructor)}};function hy(e,t){this.key=e,this.attributes=t,this.clear()}hy.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 gy(e,t){this.key=e,this.attributes=t,this.clear()}gy.prototype.clear=function(){this.inDegree=0,this.outDegree=0,this.directedLoops=0,this.in={},this.out={}};function _y(e,t){this.key=e,this.attributes=t,this.clear()}_y.prototype.clear=function(){this.undirectedDegree=0,this.undirectedLoops=0,this.undirected={}};function vy(e,t,n,r,i){this.key=t,this.attributes=i,this.undirected=e,this.source=n,this.target=r}vy.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)},vy.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)},vy.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]},vy.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 yy=0,by=1,xy=2,Sy=3;function Cy(e,t,n,r,i,a,o){let s,c,l,u;if(r=``+r,n===yy){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===Sy){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===by?c.source:c.target,l=i,u=a}return[s,l,u]}function wy(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Cy(this,t,n,e,r,i);return a.attributes[o]}}function Ty(e,t,n){e.prototype[t]=function(e,r){let[i]=Cy(this,t,n,e,r);return i.attributes}}function Ey(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Cy(this,t,n,e,r,i);return a.attributes.hasOwnProperty(o)}}function Dy(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Cy(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 Oy(e,t,n){e.prototype[t]=function(e,r,i,a){let[o,s,c]=Cy(this,t,n,e,r,i,a);if(typeof c!=`function`)throw new py(`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 ky(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Cy(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 Ay(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Cy(this,t,n,e,r,i);if(!iy(o))throw new py(`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 jy(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Cy(this,t,n,e,r,i);if(!iy(o))throw new py(`Graph.${t}: provided attributes are not a plain object.`);return ny(a.attributes,o),this.emit(`nodeAttributesUpdated`,{key:a.key,type:`merge`,attributes:a.attributes,data:o}),this}}function My(e,t,n){e.prototype[t]=function(e,r,i){let[a,o]=Cy(this,t,n,e,r,i);if(typeof o!=`function`)throw new py(`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 Ny=[{name:e=>`get${e}Attribute`,attacher:wy},{name:e=>`get${e}Attributes`,attacher:Ty},{name:e=>`has${e}Attribute`,attacher:Ey},{name:e=>`set${e}Attribute`,attacher:Dy},{name:e=>`update${e}Attribute`,attacher:Oy},{name:e=>`remove${e}Attribute`,attacher:ky},{name:e=>`replace${e}Attributes`,attacher:Ay},{name:e=>`merge${e}Attributes`,attacher:jy},{name:e=>`update${e}Attributes`,attacher:My}];function Py(e){Ny.forEach(function({name:t,attacher:n}){n(e,t(`Node`),yy),n(e,t(`Source`),by),n(e,t(`Target`),xy),n(e,t(`Opposite`),Sy)})}function Fy(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new my(`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=ry(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 my(`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 Iy(e,t,n){e.prototype[t]=function(e){let r;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>1){if(this.multi)throw new my(`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=ry(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 my(`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 Ly(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new my(`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=ry(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 my(`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 Ry(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new my(`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=ry(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 my(`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 zy(e,t,n){e.prototype[t]=function(e,r,i){let a;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>3){if(this.multi)throw new my(`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=ry(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 my(`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 py(`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 By(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new my(`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=ry(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 my(`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 Vy(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new my(`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=ry(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 my(`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(!iy(r))throw new py(`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 Hy(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new my(`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=ry(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 my(`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(!iy(r))throw new py(`Graph.${t}: provided attributes are not a plain object.`);return ny(i.attributes,r),this.emit(`edgeAttributesUpdated`,{key:i.key,type:`merge`,attributes:i.attributes,data:r}),this}}function Uy(e,t,n){e.prototype[t]=function(e,r){let i;if(this.type!==`mixed`&&n!==`mixed`&&n!==this.type)throw new my(`Graph.${t}: cannot find this type of edges in your ${this.type} graph.`);if(arguments.length>2){if(this.multi)throw new my(`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=ry(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 my(`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 py(`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 Wy=[{name:e=>`get${e}Attribute`,attacher:Fy},{name:e=>`get${e}Attributes`,attacher:Iy},{name:e=>`has${e}Attribute`,attacher:Ly},{name:e=>`set${e}Attribute`,attacher:Ry},{name:e=>`update${e}Attribute`,attacher:zy},{name:e=>`remove${e}Attribute`,attacher:By},{name:e=>`replace${e}Attributes`,attacher:Vy},{name:e=>`merge${e}Attributes`,attacher:Hy},{name:e=>`update${e}Attributes`,attacher:Uy}];function Gy(e){Wy.forEach(function({name:t,attacher:n}){n(e,t(`Edge`),`mixed`),n(e,t(`DirectedEdge`),`directed`),n(e,t(`UndirectedEdge`),`undirected`)})}var Ky=[{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 qy(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 Jy(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 Yy(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 Xy(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 Zy(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 Qy(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 $y(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 eb(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 tb(e,t){if(e.size===0)return dy();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 nb(e,t,n,r,i,a){let o=t?Jy:qy,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 rb(e,t,n,r){let i=[];return nb(!1,e,t,n,r,function(e){i.push(e)}),i}function ib(e,t,n){let r=dy();return e!==`undirected`&&(t!==`out`&&n.in!==void 0&&(r=uy(r,Yy(n.in))),t!==`in`&&n.out!==void 0&&(r=uy(r,Yy(n.out,t?void 0:n.key)))),e!==`directed`&&n.undirected!==void 0&&(r=uy(r,Yy(n.undirected))),r}function ab(e,t,n,r,i,a,o){let s=n?Zy:Xy,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 ob(e,t,n,r,i){let a=[];return ab(!1,e,t,n,r,i,function(e){a.push(e)}),a}function sb(e,t,n,r){let i=dy();return e!==`undirected`&&(n.in!==void 0&&t!==`out`&&r in n.in&&(i=uy(i,Qy(n.in,r))),n.out!==void 0&&t!==`in`&&r in n.out&&(t||n.key!==r)&&(i=uy(i,Qy(n.out,r)))),e!==`directed`&&n.undirected!==void 0&&r in n.undirected&&(i=uy(i,Qy(n.undirected,r))),i}function cb(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 $y(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 rb(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 ob(r,this.multi,i,a,t)}throw new py(`Graph.${n}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function lb(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,eb(!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 nb(!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 ab(!1,r,this.multi,i,o,t,n)}throw new py(`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 py(`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 py(`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 ub(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,eb(!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 nb(!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 ab(!0,r,this.multi,i,o,t,n)}throw new py(`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 db(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 dy();if(!arguments.length)return tb(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 ib(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 sb(r,i,n,t)}throw new py(`Graph.${a}: too many arguments (expecting 0, 1 or 2 and got ${arguments.length}).`)}}function fb(e){Ky.forEach(t=>{cb(e,t),lb(e,t),ub(e,t),db(e,t)})}var pb=[{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 mb(){this.A=null,this.B=null}mb.prototype.wrap=function(e){this.A===null?this.A=e:this.B===null&&(this.B=e)},mb.prototype.has=function(e){return this.A!==null&&e in this.A||this.B!==null&&e in this.B};function hb(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 gb(e,t,n,r,i){if(t!==`mixed`){if(t===`undirected`)return hb(e,null,r,r.undirected,i);if(typeof n==`string`)return hb(e,null,r,r[n],i)}let a=new mb,o;if(t!==`undirected`){if(n!==`out`){if(o=hb(e,null,r,r.in,i),e&&o)return o;a.wrap(r.in)}if(n!==`in`){if(o=hb(e,a,r,r.out,i),e&&o)return o;a.wrap(r.out)}}if(t!==`directed`&&(o=hb(e,a,r,r.undirected,i),e&&o))return o}function _b(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 gb(!1,e,t,n,function(e){r.push(e)}),r}function vb(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 yb(e,t,n){if(e!==`mixed`){if(e===`undirected`)return vb(null,n,n.undirected);if(typeof t==`string`)return vb(null,n,n[t])}let r=dy(),i=new mb;return e!==`undirected`&&(t!==`out`&&(r=uy(r,vb(i,n,n.in))),t!==`in`&&(r=uy(r,vb(i,n,n.out)))),e!==`directed`&&(r=uy(r,vb(i,n,n.undirected))),r}function bb(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 _b(r===`mixed`?this.type:r,i,t)}}function xb(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.`);gb(!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 py(`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 Sb(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 gb(!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 Cb(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 dy();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 yb(r===`mixed`?this.type:r,i,t)}}function wb(e){pb.forEach(t=>{bb(e,t),xb(e,t),Sb(e,t),Cb(e,t)})}function Tb(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 Eb(e,t){let n={key:e};return ay(t.attributes)||(n.attributes=ny({},t.attributes)),n}function Db(e,t,n){let r={key:t,source:n.source.key,target:n.target.key};return ay(n.attributes)||(r.attributes=ny({},n.attributes)),e===`mixed`&&n.undirected&&(r.undirected=!0),r}function Ob(e){if(!iy(e))throw new py(`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 py(`Graph.import: serialized node is missing its key.`);if(`attributes`in e&&(!iy(e.attributes)||e.attributes===null))throw new py(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`)}function kb(e){if(!iy(e))throw new py(`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 py(`Graph.import: serialized edge is missing its source.`);if(!(`target`in e))throw new py(`Graph.import: serialized edge is missing its target.`);if(`attributes`in e&&(!iy(e.attributes)||e.attributes===null))throw new py(`Graph.import: invalid attributes. Attributes should be a plain object, null or omitted.`);if(`undirected`in e&&typeof e.undirected!=`boolean`)throw new py(`Graph.import: invalid undirectedness information. Undirected should be boolean or omitted.`)}var Ab=ly(),jb=new Set([`directed`,`undirected`,`mixed`]),Mb=new Set([`domain`,`_events`,`_eventsCount`,`_maxListeners`]),Nb=[{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`}],Pb={allowSelfLoops:!0,multi:!1,type:`mixed`};function Fb(e,t,n){if(n&&!iy(n))throw new py(`Graph.addNode: invalid attributes. Expecting an object but got "${n}"`);if(t=``+t,n||={},e._nodes.has(t))throw new my(`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 Ib(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 Lb(e,t,n,r,i,a,o,s){if(!r&&e.type===`undirected`)throw new my(`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 my(`Graph.${t}: you cannot add an undirected edge to a directed graph. Use the #.addEdge or #.addDirectedEdge instead.`);if(s&&!iy(s))throw new py(`Graph.${t}: invalid attributes. Expecting an object but got "${s}"`);if(a=``+a,o=``+o,s||={},!e.allowSelfLoops&&a===o)throw new my(`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 my(`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 my(`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 vy(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 Rb(e,t,n,r,i,a,o,s,c){if(!r&&e.type===`undirected`)throw new my(`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 my(`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 py(`Graph.${t}: invalid updater function. Expecting a function but got "${s}"`)}else if(!iy(s))throw new py(`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 my(`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 my(`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 ny(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 my(`Graph.${t}: the "${i}" edge already exists in the graph.`);let h=!1,g=!1;u||(u=Ib(e,a,{}),h=!0,a===o&&(d=u,g=!0)),d||(d=Ib(e,o,{}),g=!0),f=new vy(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 zb(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 Bb=class e extends ey.EventEmitter{constructor(e){if(super(),e=ny({},Pb,e),typeof e.multi!=`boolean`)throw new py(`Graph.constructor: invalid 'multi' option. Expecting a boolean but got "${e.multi}".`);if(!jb.has(e.type))throw new py(`Graph.constructor: invalid 'type' option. Should be one of "mixed", "directed" or "undirected" but got "${e.type}".`);if(typeof e.allowSelfLoops!=`boolean`)throw new py(`Graph.constructor: invalid 'allowSelfLoops' option. Expecting a boolean but got "${e.allowSelfLoops}".`);let t=e.type===`mixed`?hy:e.type===`directed`?gy:_y;oy(this,`NodeDataClass`,t);let n=`geid_`+Ab()+`_`,r=0;oy(this,`_attributes`,{}),oy(this,`_nodes`,new Map),oy(this,`_edges`,new Map),oy(this,`_directedSize`,0),oy(this,`_undirectedSize`,0),oy(this,`_directedSelfLoopCount`,0),oy(this,`_undirectedSelfLoopCount`,0),oy(this,`_edgeKeyGenerator`,()=>{let e;do e=n+r++;while(this._edges.has(e));return e}),oy(this,`_options`,e),Mb.forEach(e=>oy(this,e,this[e])),sy(this,`order`,()=>this._nodes.size),sy(this,`size`,()=>this._edges.size),sy(this,`directedSize`,()=>this._directedSize),sy(this,`undirectedSize`,()=>this._undirectedSize),sy(this,`selfLoopCount`,()=>this._directedSelfLoopCount+this._undirectedSelfLoopCount),sy(this,`directedSelfLoopCount`,()=>this._directedSelfLoopCount),sy(this,`undirectedSelfLoopCount`,()=>this._undirectedSelfLoopCount),sy(this,`multi`,this._options.multi),sy(this,`type`,this._options.type),sy(this,`allowSelfLoops`,this._options.allowSelfLoops),sy(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 py(`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 py(`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 py(`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 my(`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 my(`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 my(`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 Fb(this,e,t).key}mergeNode(e,t){if(t&&!iy(t))throw new py(`Graph.mergeNode: invalid attributes. Expecting an object but got "${t}"`);e=``+e,t||={};let n=this._nodes.get(e);return n?(t&&(ny(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 py(`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 zb(this,n),n=n.next;while(n)}for(let e in t.in){n=t.in[e];do zb(this,n),n=n.next;while(n)}}if(this.type!==`directed`)for(let e in t.undirected){n=t.undirected[e];do zb(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=ry(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 zb(this,t),this}dropDirectedEdge(e,t){if(arguments.length<2)throw new my(`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 my(`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=ry(this,e,t,`directed`);if(!n)throw new $(`Graph.dropDirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return zb(this,n),this}dropUndirectedEdge(e,t){if(arguments.length<2)throw new my(`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 my(`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=ry(this,e,t,`undirected`);if(!n)throw new $(`Graph.dropUndirectedEdge: could not find a "${e}" -> "${t}" edge in the graph.`);return zb(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 py(`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(!iy(e))throw new py(`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(!iy(e))throw new py(`Graph.mergeAttributes: provided attributes are not a plain object.`);return ny(this._attributes,e),this.emit(`attributesUpdated`,{type:`merge`,attributes:this._attributes,data:e}),this}updateAttributes(e){if(typeof e!=`function`)throw new py(`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 py(`Graph.updateEachNodeAttributes: expecting an updater function.`);if(t&&!cy(t))throw new py(`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 py(`Graph.updateEachEdgeAttributes: expecting an updater function.`);if(t&&!cy(t))throw new py(`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 py(`Graph.forEachAdjacencyEntry: expecting a callback.`);Tb(!1,!1,!1,this,e)}forEachAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new py(`Graph.forEachAdjacencyEntryWithOrphans: expecting a callback.`);Tb(!1,!1,!0,this,e)}forEachAssymetricAdjacencyEntry(e){if(typeof e!=`function`)throw new py(`Graph.forEachAssymetricAdjacencyEntry: expecting a callback.`);Tb(!1,!0,!1,this,e)}forEachAssymetricAdjacencyEntryWithOrphans(e){if(typeof e!=`function`)throw new py(`Graph.forEachAssymetricAdjacencyEntryWithOrphans: expecting a callback.`);Tb(!1,!0,!0,this,e)}nodes(){return Array.from(this._nodes.keys())}forEachNode(e){if(typeof e!=`function`)throw new py(`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 py(`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 py(`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 py(`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 py(`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 py(`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 py(`Graph.reduceNodes: expecting a callback.`);if(arguments.length<2)throw new py(`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++]=Eb(r,n)});let n=Array(this._edges.size);return t=0,this._edges.forEach((e,r)=>{n[t++]=Db(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(!iy(t))throw new py(`Graph.import: invalid argument. Expecting a serialized graph or, alternatively, a Graph instance.`);if(t.attributes){if(!iy(t.attributes))throw new py(`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 py(`Graph.import: invalid nodes. Expecting an array.`);for(r=0,i=a.length;r<i;r++){o=a[r],Ob(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 py(`Graph.import: invalid edges. Expecting an array.`);for(r=0,i=a.length;r<i;r++){s=a[r],kb(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(ny({},this._options,t));return n.replaceAttributes(ny({},this.getAttributes())),n}emptyCopy(e){let t=this.nullCopy(e);return this._nodes.forEach((e,n)=>{let r=ny({},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 my(`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 my(`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 my(`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,Lb(t,`copy`,!1,i.undirected,i.key,i.source.key,i.target.key,ny({},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)&&!Mb.has(e)&&typeof this[e]!=`function`&&typeof e!=`symbol`&&(r[e]=this[e]);return r.attributes=this._attributes,r.nodes=e,r.edges=t,oy(r,`constructor`,this.constructor),r}};typeof Symbol<`u`&&(Bb.prototype[Symbol.for(`nodejs.util.inspect.custom`)]=Bb.prototype.inspect),Nb.forEach(e=>{[`add`,`merge`,`update`].forEach(t=>{let n=e.name(t),r=t===`add`?Lb:Rb;e.generateKey?Bb.prototype[n]=function(i,a,o){return r(this,n,!0,(e.type||this.type)===`undirected`,null,i,a,o,t===`update`)}:Bb.prototype[n]=function(i,a,o,s){return r(this,n,!1,(e.type||this.type)===`undirected`,i,a,o,s,t===`update`)}})}),Py(Bb),Gy(Bb),fb(Bb),wb(Bb);var Vb=class extends Bb{constructor(e){let t=ny({type:`directed`},e);if(`multi`in t&&t.multi!==!1)throw new py(`DirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`directed`)throw new py(`DirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},Hb=class extends Bb{constructor(e){let t=ny({type:`undirected`},e);if(`multi`in t&&t.multi!==!1)throw new py(`UndirectedGraph.from: inconsistent indication that the graph should be multi in given options!`);if(t.type!==`undirected`)throw new py(`UndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},Ub=class extends Bb{constructor(e){let t=ny({multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new py(`MultiGraph.from: inconsistent indication that the graph should be simple in given options!`);super(t)}},Wb=class extends Bb{constructor(e){let t=ny({type:`directed`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new py(`MultiDirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`directed`)throw new py(`MultiDirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}},Gb=class extends Bb{constructor(e){let t=ny({type:`undirected`,multi:!0},e);if(`multi`in t&&t.multi!==!0)throw new py(`MultiUndirectedGraph.from: inconsistent indication that the graph should be simple in given options!`);if(t.type!==`undirected`)throw new py(`MultiUndirectedGraph.from: inconsistent "`+t.type+`" type in given options!`);super(t)}};function Kb(e){e.from=function(t,n){let r=new e(ny({},t.options,n));return r.import(t),r}}Kb(Bb),Kb(Vb),Kb(Hb),Kb(Ub),Kb(Wb),Kb(Gb),Bb.Graph=Bb,Bb.DirectedGraph=Vb,Bb.UndirectedGraph=Hb,Bb.MultiGraph=Ub,Bb.MultiDirectedGraph=Wb,Bb.MultiUndirectedGraph=Gb,Bb.InvalidArgumentsGraphError=py,Bb.NotFoundGraphError=$,Bb.UsageGraphError=my;var qb={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`}},Jb={property:`--chart-neutral-text-dim`,fallback:`#71717a`},Yb=2.5,Xb=200,Zb=3,Qb=1.6;function $b(e){let t=Xb/Math.max(Xb,e);return Math.max(Zb,9*t**.25)}function ex(e){return $b(e)*Qb}var tx={eligible:qb.eligible,hidden:qb.hidden,resource:qb.resource,redirect:qb.redirect,failed:qb.failed,unchecked:qb.unchecked,dimmedNode:{property:`--chart-neutral-text-dim`,fallback:`#71717a`},edge:Jb,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`}},nx=/^#(?:[\da-f]{3}|[\da-f]{4}|[\da-f]{6}|[\da-f]{8})$/i,rx=/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(?:\s*,\s*(?:0|1|0?\.\d+))?\s*\)$/;function ix(e){return nx.test(e)||rx.test(e)}var ax=50,ox=.75,sx=[{maxRatio:.2,budget:1/0},{maxRatio:.45,budget:60},{maxRatio:ox,budget:24}];function cx(e){for(let t of sx)if(e<=t.maxRatio)return t.budget;return 1}function lx(e){return Math.max(0,Math.min(1,(e.linkScoreNormalized??0)/100))}function ux(e){return e.healthState?e.healthState:_t(e)}function dx(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 fx(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 px(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 mx(e){switch(e){case`eligible`:return`●`;case`hidden`:return`◆`;case`resource`:return`▪`;case`redirect`:return`↗`;case`failed`:return`×`;case`unchecked`:return`○`}}function hx(e,t){return!!t&&e.nodeKey===t}function gx(e,t=!1,n=1){let r=$b(n),i=Yb+Math.sqrt(lx(e))*(r-Yb);return t?Math.max(ex(n),i):i}function _x(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 vx(e){return .35+Math.min(1.65,Math.log2(Math.max(1,e)+1)*.28)}function yx(e){return Number.isFinite(e.x)&&Number.isFinite(e.y)}function bx(e,t,n,r=null){let i=new Wb({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(!yx(e))continue;let t=ux(e),o=_x(t,n),s=mx(t),c=hx(e,r);i.addNode(e.nodeKey,{x:e.x,y:e.y,size:gx(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:vx(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 xx(e,t,n=ax){let r=t.trim().toLocaleLowerCase(),i=Math.max(0,Math.min(ax,Math.floor(n)));return[...e].sort((e,t)=>dt(e.path||e.url,t.path||t.url)||dt(e.nodeKey,t.nodeKey)).filter(e=>yx(e)?!r||`${e.path}\n${e.url}\n${e.nodeKey}`.toLocaleLowerCase().includes(r):!1).slice(0,i)}function Sx(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>ox;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=cx(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()>ox,[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 Cx={"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 wx(e){return(e&&Cx[e])??Cx[`no-crawl`]}var Tx=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),gn({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}},Ex=220;function Dx(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches?0:Ex}function Ox(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function kx(e,t,n){let r=window.getComputedStyle(e).getPropertyValue(t).trim();if(r&&!r.includes(`var(`)&&ix(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(`)&&ix(a)?a:n}function Ax(e){let t=t=>{let n=tx[t];return kx(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 jx(){if(typeof document>`u`)return!1;try{return!!document.createElement(`canvas`).getContext(`webgl2`)}catch{return!1}}function Mx({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)(J,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:e,children:`Open page inventory`})]})})}function Nx({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)(J,{variant:`secondary`,size:`sm`,className:`mt-4`,onClick:e,children:`Try again`})]})})}function Px({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=Dx();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>ox,t=cx(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(Sx(n,b,()=>f.getCamera().getState().ratio,r,a));let t=f.getCamera().getState().ratio;S.current={overview:t>ox,budget:cx(t)},f.refresh()},[b,n,a,f,r,e]),null}function Fx({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)(``),[F,I]=(0,Z.useState)(!1),[L,R]=(0,Z.useState)(0),[z,B]=(0,Z.useState)(``),[ee,te]=(0,Z.useState)(0),ne=(0,Z.useRef)(null),V=(0,Z.useDeferredValue)(N),H=c===void 0?k:c,re=(0,Z.useMemo)(()=>new Map(e.map(e=>[e.nodeKey,e])),[e]),U=(0,Z.useMemo)(()=>Jv(a?re.get(a)?.url:null),[re,a]),ie=(0,Z.useCallback)(e=>Qv(e,U),[U]),ae=H?re.get(H)??null:null,oe=j?re.get(j.nodeKey)??null:null,se=(0,Z.useMemo)(()=>xx(e,V),[V,e]),ce=e.some(e=>Number.isFinite(e.x)&&Number.isFinite(e.y)),le=(0,Z.useMemo)(()=>b?bx(e,t,b,a):null,[t,e,a,b]),ue=(0,Z.useMemo)(()=>{if(!b||!le)return null;let e=Sx(le.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}}},[le,b]);(0,Z.useEffect)(()=>{let e=m.current;if(!e)return;let t=()=>x(Ax(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`||!ce?E(`checking`):E(jx()?`ready`:`unavailable`)},[ce,n,e.length]),(0,Z.useEffect)(()=>{if(T!==`ready`){w(null);return}let e=!0;return pc(()=>import(`./react-sigma_core.esm.min-D1q0DR_j.js`).then(t=>{e&&w(t)}),__vite__mapDeps([0,1,2]),import.meta.url).catch(()=>{e&&E(`unavailable`)}),()=>{e=!1}},[T]),(0,Z.useEffect)(()=>{R(0)},[V]);let de=(0,Z.useCallback)(e=>{g.current=e,O(!!e)},[]),fe=(0,Z.useCallback)(e=>{M(e)},[]),pe=(0,Z.useCallback)((e,t)=>{let n=re.get(e);n&&(c===void 0&&A(e),l?.(n),t&&g.current?.gotoNode(e),B(`Focused ${ie(n)}`))},[re,l,ie,c]),me=(0,Z.useCallback)(e=>{pe(e,!1)},[pe]);(0,Z.useEffect)(()=>{!D||!c||!re.has(c)?c||(ne.current=null):ne.current!==c&&(g.current?.gotoNode(c),ne.current=c)},[D,re,c]);let he=e=>{pe(e.nodeKey,!0),P(ie(e)),I(!1)},ge=()=>{window.setTimeout(()=>{document.activeElement!==h.current&&I(!1)},0)},_e=(0,Z.useMemo)(()=>s?t.length:t.filter(e=>e.isTemplate!==!0).length,[t,s]),ve=`Interactive site map showing ${Ox(e.length,`page`)} and ${Ox(_e,`internal link`)}`,ye=e=>`${v}-${e.replaceAll(/[^\w-]/g,`-`)}`,be=wx(r);if(n===`unavailable`)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??ve,className:ln(`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:be.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:be.detail}),d&&(0,Q.jsx)(J,{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??ve,className:ln(`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)(J,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});if(!ce)return(0,Q.jsx)(`section`,{ref:m,role:`group`,"aria-label":f??ve,className:ln(`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:be.heading}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:be.detail}),d&&(0,Q.jsx)(J,{type:`button`,variant:`secondary`,size:`sm`,className:`mt-4`,onClick:d,children:`Open page inventory`})]})});let xe=se.at(L),Se=(0,Q.jsx)(Nx,{onRetry:()=>te(e=>e+1)}),Ce=C?.SigmaContainer;return(0,Q.jsxs)(`section`,{ref:m,role:`group`,"aria-label":f??ve,"aria-describedby":y,className:ln(`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":F,"aria-activedescendant":F&&xe?ye(xe.nodeKey):void 0,value:N,placeholder:ae?`Focused: ${ie(ae)}`:`Find a page`,className:`h-10 w-full rounded-md border border-base bg-bg py-2 pl-9 pr-3 text-label-14 text-primary placeholder-mono-400 outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onFocus:()=>I(!0),onBlur:ge,onChange:e=>{P(e.target.value),I(!0)},onKeyDown:e=>{e.key===`ArrowDown`?(e.preventDefault(),I(!0),R(e=>Math.max(0,Math.min(se.length-1,e+1)))):e.key===`ArrowUp`?(e.preventDefault(),R(e=>Math.max(0,e-1))):e.key===`Enter`&&F&&xe?(e.preventDefault(),he(xe)):e.key===`Escape`&&I(!1)}}),F&&(0,Q.jsxs)(`div`,{className:`absolute left-0 right-0 top-[calc(100%+0.25rem)] z-30 overflow-hidden material-menu`,children:[(0,Q.jsx)(`div`,{id:v,role:`listbox`,"aria-label":`Matching pages`,className:`max-h-72 overflow-auto py-1`,children:se.length>0?se.map((e,t)=>{let n=ux(e);return(0,Q.jsxs)(`button`,{id:ye(e.nodeKey),type:`button`,role:`option`,"aria-selected":t===L,tabIndex:-1,className:ln(`flex min-h-11 w-full items-center justify-between gap-3 px-3 py-2 text-left text-button-14 outline-none`,t===L?`bg-surface-active text-primary`:`text-secondary hover:bg-surface-hover hover:text-primary`),onPointerDown:e=>e.preventDefault(),onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>R(t),onClick:()=>he(e),children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate font-mono`,children:ie(e)}),(0,Q.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1.5 text-label-13 text-muted`,children:[(0,Q.jsx)(`span`,{className:`text-label-13-mono-strong`,style:{color:`var(${qb[n].property})`},"aria-hidden":`true`,children:mx(n)}),(0,Q.jsx)(`span`,{title:px(n),children:dx(n)})]})]},e.nodeKey)}):(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-secondary`,children:`No rendered pages match.`})}),se.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:`${Ox(e.length,`page`)} on the map · ${Ox(_e,`link`)} shown`})]}),(0,Q.jsx)(`div`,{className:`relative min-h-0 flex-1 overflow-hidden`,children:T===`unavailable`?(0,Q.jsx)(Mx,{onOpenInventory:d}):T===`checking`||!b||!le||!ue||!C||!Ce?(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)(Tx,{fallback:Se,resetToken:ee,children:[(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`absolute inset-0`,children:(0,Q.jsx)(Ce,{graph:le.graph,className:`relative size-full bg-bg [&_.sigma-container]:size-full`,style:{width:`100%`,height:`100%`,background:b.background},options:ue.options,children:(0,Q.jsx)(Px,{setReducers:ue.setReducers,reactSigma:C,graph:le.graph,theme:b,selectedNodeKey:H,showTemplateLinks:s,onSelectNodeKey:me,onHoverNode:fe,onCameraReady:de})})}),(0,Q.jsxs)(`div`,{className:`absolute right-3 top-3 z-20 flex flex-col overflow-hidden material-menu`,children:[(0,Q.jsx)(J,{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)(J,{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)(J,{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`})})]}),oe&&j&&(0,Q.jsxs)(`div`,{role:`tooltip`,className:`pointer-events-none absolute z-20 max-w-64 material-tooltip px-3 py-2`,style:{left:j.left,top:j.top},children:[(0,Q.jsx)(`p`,{className:`truncate text-copy-13-mono-strong text-heading`,children:ie(oe)}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-13-strong text-heading`,children:dx(ux(oe))}),(0,Q.jsx)(`p`,{className:`mt-0.5 text-copy-13 text-secondary`,children:px(ux(oe))}),oe.depth!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[Ox(oe.depth,`click`),` from home`]}),oe.auditScore!=null&&(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 tabular-nums text-heading`,children:[`Score `,Math.round(oe.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:[Ge.map(e=>(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,title:px(e),children:[(0,Q.jsx)(`span`,{className:`w-3 text-center font-mono text-label-16-strong`,style:{color:`var(${qb[e].property})`},"aria-hidden":`true`,children:mx(e)}),fx(e)]},e)),(0,Q.jsx)(`span`,{className:`ml-auto`,children:`Bigger = more linked`}),le&&(le.omittedNodes>0||le.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:z})]})}var Ix={"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 Lx(e,t){return`Worth ${$e(e,Lt.percent)} of the ${t} score`}function Rx(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function zx(e){return e>=70?`pass`:e>=40?`partial`:`fail`}function Bx(e){return e===`pass`?`positive`:e===`partial`?`caution`:`negative`}function Vx(e){return e===`pass`?`Pass`:e===`partial`?`Partial`:`Fail`}function Hx({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)(J,{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)(Ux,{audit:e}):(0,Q.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`No findings are available for this page.`})]})}function Ux({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)(Y,{tone:Rx(e.auditScore),children:Vx(zx(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)(Y,{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)(Y,{tone:e.severity===`critical`?`negative`:`caution`,children:e.severity===`critical`?`Critical`:`Warning`})]}),(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)(d,{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)(Y,{tone:Bx(t.status),children:Vx(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:Lx(t.sharePct,`page`)}):null]})]})]}),Ix[t.id]&&(0,Q.jsx)(`div`,{className:`flex min-h-14 items-center`,children:(0,Q.jsx)(X,{text:Ix[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 Wx=`Not recorded by this scan`,Gx=100,Kx=12,qx=[];function Jx(e){return Ol(e.url)}function Yx(e){return e>=70?`positive`:e>=40?`caution`:`negative`}function Xx(e){return e>=70?`text-positive-400`:e>=40?`text-caution-400`:`text-negative-400`}function Zx(e){return e===at.pass?`positive`:e===at.partial?`caution`:`negative`}var Qx={[at.pass]:`Pass`,[at.partial]:`Partial`,[at.fail]:`Fail`},$x=`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.`,eS=`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.`,tS={[at.fail]:0,[at.partial]:1,[at.pass]:2};function nS(e){return e.pagesPartial+e.pagesFailing}function rS(e){return[...e].sort((e,t)=>tS[e.status]-tS[t.status]||nS(t)-nS(e)||e.avgScore-t.avgScore)}function iS(e){return e>=70?`Pass`:e>=40?`Partial`:`Fail`}function aS(e){return bi(hi(String(e)))}function oS(e){return pi(hi(String(e)))}function sS({projectName:e,projectId:t,runId:n,integrated:r=!1}){let{isAdmin:i}=ji(),a=tr(Ct[`site-audit`])&&!i,[o,s]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(null),[f,p]=(0,Z.useState)(null),m=n===void 0?f:n,[h,_]=(0,Z.useState)(!1),v=(0,Z.useRef)(null),b=U(jo({client:q,path:{name:e},...m?{query:{runId:m}}:{}})),S=U({...Go({client:q,path:{name:e},query:{limit:30}}),enabled:!r}),C=U({...io({client:q,path:{name:e},query:{surface:`site-health`}}),enabled:r}),w=U(To({client:q,path:{name:e},query:{limit:Gx,sort:`score-asc`,...m?{runId:m}:{}}})),T=U({...ns({client:q,path:{name:e},query:{kind:Ct[`site-audit`],limit:10}}),enabled:!r,refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.some(e=>e.status===`queued`||e.status===`running`)?3e3:1e4}),D=dc(),O=(0,Z.useSyncExternalStore)(Ts,tc,tc),k=Object.values(O.runs).find(e=>e.kind===Ct[`site-audit`]&&e.projectId===t),j=T.data??[],M=j.find(e=>e.status===`queued`||e.status===`running`),N=j.at(-1),P=D.isPending||!!k||!!M,F=D.isPending?`starting`:M?.status??k?.lastAnnouncedStatus,I=(0,Z.useCallback)(async()=>{r&&C.refetch();let e=await Promise.all([b.refetch(),w.refetch(),...r?[]:[S.refetch()]]),t=e.find(e=>e.error);if(t?.error)throw t.error;return e[0]},[r,w.refetch,b.refetch,S.refetch,C.refetch]);(0,Z.useEffect)(()=>{r||m||!N||N.status!==`completed`&&N.status!==`partial`||b.data?.runId!==N.id&&v.current!==N.id&&(v.current=N.id,I().catch(t=>{Ni({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,r,N?.id,N?.status,e,I,b.data?.runId]);let L=async()=>{_(!0);try{let t=await I();Ni({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){Ni({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)}},R=()=>{(!tr(Ct[`site-audit`])||i)&&D.mutate({projectName:e,projectId:t})},z=F===`running`?`Scan running`:F===`queued`?`Scan queued`:`Starting scan`,B=b.data,ee=w.data?.pages??qx,te=(B?.pagesErrored??0)>0,ne=o&&te,V=jl({rows:(0,Z.useMemo)(()=>ne?ee.filter(e=>e.status===`error`):ee,[ee,ne]),getSearchText:Jx}),H=B?B.pagesAudited>ee.length:!1;if((0,Z.useEffect)(()=>{s(!1),u(null)},[m,r]),b.isLoading)return(0,Q.jsxs)(`div`,{className:`flex min-h-40 items-center justify-center gap-2 text-label-14 text-secondary ${r?``:`mt-6`}`,role:`status`,children:[(0,Q.jsx)(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 ${r?``:`mt-6`}`,role:`alert`,children:[(0,Q.jsxs)(`div`,{className:`flex min-w-0 gap-3`,children:[(0,Q.jsx)(E,{className:`mt-0.5 size-4 shrink-0 text-negative`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{children:[r?(0,Q.jsx)(`h3`,{className:`text-heading-14 text-negative`,children:`Score could not load`}):(0,Q.jsx)(`h2`,{className:`text-heading-14 text-negative`,children:`Score could not load`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`The saved scan could not be read. Try loading it again.`})]})]}),(0,Q.jsxs)(J,{type:`button`,variant:`secondary`,size:`sm`,className:`shrink-0`,onClick:()=>void L(),disabled:h,children:[(0,Q.jsx)(g,{className:`size-4 ${h?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),h?`Trying again…`:`Try again`]})]});if(!B||!B.hasData)return r?(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:a?Ls:`Run a new Agent Readiness audit scan to calculate page-level findings.`})]}):(0,Q.jsxs)(rs,{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.`}),!G()&&!a&&(0,Q.jsx)(`div`,{className:`mt-5 flex items-center justify-center gap-3`,children:(0,Q.jsxs)(Rr,{type:`button`,onClick:R,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)(A,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?z:`Run first scan`]})}),P?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,role:`status`,"aria-live":`polite`,children:`The dashboard will refresh automatically when the scan finishes.`}):null]});let re=B.deltaScore==null?null:`${B.deltaScore>=0?`+`:``}${B.deltaScore} vs previous`,se=B.trend===`up`?`positive`:B.trend===`down`?`negative`:`neutral`,le=S.data?.points??[],ue=le.map(e=>({runId:e.runId,date:e.auditedAt,score:e.aggregateScore})),me=n===void 0&&f!==null,he=ee.filter(e=>e.status===`success`),ge=B.factors.filter(e=>nS(e)>0).length,_e=B.runStatus===`partial`,ve=B.crossCuttingIssues.some(e=>e.topRecommendations.length>0);function ye(e){let t=[];for(let n of he){let r=n.factors.find(t=>t.id===e);r&&r.score<70&&t.push({url:n.url,score:r.score})}return t.sort((e,t)=>e.score-t.score)}return(0,Q.jsxs)(`div`,{className:r?``:`mt-6`,children:[r?(0,Q.jsxs)(`section`,{className:`flex flex-col gap-3 border-b border-default pb-5 sm:flex-row sm:items-end sm:justify-between`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:_e?`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":_e?`Score so far ${B.aggregateScore} out of 100, from a scan that did not cover the whole site`:`Agent Readiness score ${B.aggregateScore} out of 100`,className:`inline-flex items-baseline gap-1 font-mono tabular-nums ${Xx(B.aggregateScore)}`,children:[(0,Q.jsx)(`span`,{className:`text-heading-32`,children:B.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-14 text-muted`,children:`/100`})]}),(0,Q.jsx)(Y,{tone:Yx(B.aggregateScore),children:iS(B.aggregateScore)}),_e?(0,Q.jsx)(Y,{tone:`caution`,children:`Part of the site`}):null,re?(0,Q.jsx)(Y,{tone:se,children:re}):null]})]}),(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:[B.pagesAudited,` page`,B.pagesAudited===1?``:`s`,` scored`]}),(0,Q.jsx)(`span`,{"aria-hidden":`true`,className:`text-faint`,children:`·`}),(0,Q.jsxs)(`span`,{children:[ge,` check`,ge===1?``:`s`,` with pages below pass`]}),B.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:[B.pagesErrored,` crawl error`,B.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:me?`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 ${Xx(B.aggregateScore)}`,children:B.aggregateScore}),(0,Q.jsx)(`span`,{className:`text-label-18 text-muted`,children:`/ 100`}),(0,Q.jsx)(Y,{tone:Yx(B.aggregateScore),children:iS(B.aggregateScore)}),re?(0,Q.jsx)(Y,{tone:se,children:re}):null,P?(0,Q.jsx)(Y,{tone:`neutral`,children:z}):null]}),(0,Q.jsxs)(`p`,{className:`supporting-copy mt-2 tabular-nums`,children:[B.pagesDiscovered,` URL`,B.pagesDiscovered===1?``:`s`,` in sitemap · `,B.pagesAudited,` audited · `,B.pagesSkipped,` skipped · `,B.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:B.sitemapUrl??`#`,target:`_blank`,rel:`noreferrer`,className:`max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong`,children:B.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>`."})]}),B.auditedAt?(0,Q.jsxs)(`p`,{className:`mt-0.5 text-copy-13 text-faint`,children:[`Scanned `,new Date(B.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&&le.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`}),[...le].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)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void L(),disabled:h,children:[(0,Q.jsx)(g,{className:`mr-1.5 h-4 w-4 ${h?`motion-safe:animate-spin`:``}`,"aria-hidden":`true`}),h?`Refreshing…`:`Refresh`]}),!G()&&!a&&(0,Q.jsxs)(Rr,{type:`button`,size:`sm`,onClick:R,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)(A,{className:`mr-1.5 h-4 w-4`,"aria-hidden":`true`}),P?z:`Re-run scan`]})]})]}),r?(0,Q.jsx)(cS,{trend:C.data}):null,!r&&ue.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(...ue.map(e=>e.score)),` to `,Math.max(...ue.map(e=>e.score)),` across `,ue.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)(ce,{width:`100%`,height:`100%`,children:(0,Q.jsxs)(pe,{data:ue,margin:{top:8,right:8,bottom:0,left:0},children:[(0,Q.jsx)(ie,{stroke:wi,vertical:!1}),(0,Q.jsx)(oe,{dataKey:`date`,tick:xi,tickLine:!1,axisLine:{stroke:Ei},tickFormatter:aS,minTickGap:24}),(0,Q.jsx)(de,{domain:[0,100],ticks:[0,25,50,75,100],tick:xi,tickLine:!1,axisLine:!1,width:32}),(0,Q.jsx)(ae,{...Ti,cursor:{stroke:Ei,strokeWidth:1},labelFormatter:oS,formatter:e=>[`${e}/100`,`Agent Readiness score`]}),(0,Q.jsx)(fe,{type:`monotone`,dataKey:`score`,name:`score`,stroke:Si.positive,strokeWidth:2.5,dot:{r:2.5,fill:Si.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,(0,Q.jsxs)(`section`,{className:r?`pt-5`:`page-section-divider`,children:[r?(0,Q.jsxs)(`div`,{children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Findings`}),(0,Q.jsx)(X,{text:$x})]}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:ve?`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:eS})]})]}),(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`evidence-table ${r?`min-w-[42rem]`:``}`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:r?`Check`:`Factor`}),r?null:(0,Q.jsx)(`th`,{className:`text-right`,children:`Share`}),(0,Q.jsx)(`th`,{className:`text-right`,children:r?`Score`:`Avg`}),(0,Q.jsx)(`th`,{children:r?`Worst page`:`Status`}),(0,Q.jsx)(`th`,{children:r?`Pages affected`:`Pass / Partial / Fail`})]})}),(0,Q.jsx)(`tbody`,{children:(r?rS(B.factors):B.factors).map(e=>{let t=l===e.id,n=B.crossCuttingIssues.find(t=>t.factorId===e.id),i=t?ye(e.id):[],a=nS(e),o=e.pagesPassing+a,s=!!n?.topRecommendations.length,f=s&&a>0;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:t?`bg-surface-subtle`:void 0,children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsxs)(`button`,{type:`button`,className:`flex min-h-11 w-full items-center gap-2 text-left text-button-14 text-strong outline-none hover:text-primary focus-visible:text-primary focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-mono-400`,"aria-expanded":t,onClick:()=>u(t?null:e.id),children:[t?(0,Q.jsx)(y,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}):(0,Q.jsx)(d,{className:`size-4 shrink-0 text-muted`,"aria-hidden":`true`}),e.name]}),Ix[e.id]&&(0,Q.jsx)(X,{text:Ix[e.id],placement:`bottom`})]})}),r?null:(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-muted`,children:typeof e.sharePct==`number`?$e(e.sharePct,Lt.percent):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{"aria-hidden":`true`,children:$e(null)}),(0,Q.jsx)(`span`,{className:`sr-only`,children:Wx})]})}),(0,Q.jsxs)(`td`,{className:`text-right font-mono tabular-nums text-strong`,children:[e.avgScore,r?(0,Q.jsx)(`span`,{className:`text-muted`,children:`/100`}):null]}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Y,{tone:Zx(e.status),children:Qx[e.status]})}),r?(0,Q.jsxs)(`td`,{className:`tabular-nums ${a>0?`text-strong`:`text-muted`}`,children:[a,` of `,o]}):(0,Q.jsxs)(`td`,{className:`tabular-nums text-secondary`,children:[(0,Q.jsx)(`span`,{className:`text-positive-400`,children:e.pagesPassing}),` / `,(0,Q.jsx)(`span`,{className:`text-caution-400`,children:e.pagesPartial}),` / `,(0,Q.jsx)(`span`,{className:`text-negative-400`,children:e.pagesFailing})]})]}),t?(0,Q.jsx)(`tr`,{className:`bg-surface-subtle`,children:(0,Q.jsx)(`td`,{colSpan:r?4:5,className:`px-4 pb-5 pt-0`,children:(0,Q.jsxs)(`div`,{className:`grid gap-5 border-t border-subtle pt-4 ${f?`lg:grid-cols-2`:``}`,children:[s&&n?(0,Q.jsxs)(`section`,{"aria-labelledby":`technical-finding-${e.id}-fixes`,children:[(0,Q.jsx)(`h4`,{id:`technical-finding-${e.id}-fixes`,className:`text-heading-14 text-heading`,children:`Recommended fixes`}),(0,Q.jsx)(`ol`,{className:`mt-2 list-decimal space-y-1.5 pl-5 marker:text-muted`,children:n.topRecommendations.map((e,t)=>(0,Q.jsx)(`li`,{className:`pl-1 text-label-14 text-secondary`,children:e},t))}),r&&typeof e.sharePct==`number`?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:Lx(e.sharePct,`site`)}):null]}):a===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Every audited page passes this check.`}):null,a>0?(0,Q.jsxs)(`section`,{"aria-labelledby":`technical-finding-${e.id}-pages`,children:[(0,Q.jsxs)(`h4`,{id:`technical-finding-${e.id}-pages`,className:`text-heading-14 text-heading`,children:[`Affected pages (`,a,`)`]}),r&&w.isLoading?(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center gap-2 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading affected pages…`]}):r&&w.error?(0,Q.jsxs)(`div`,{className:`mt-3`,role:`alert`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-negative`,children:`Affected pages could not load`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Try loading the affected pages again.`}),(0,Q.jsxs)(J,{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)(g,{className:`size-4`,"aria-hidden":`true`}),w.isFetching?`Retrying affected pages…`:`Retry affected pages`]})]}):i.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5`,children:i.slice(0,Kx).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 ${Xx(e.score)}`,children:e.score}),(0,Q.jsx)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,className:`min-w-0 truncate text-link outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400`,title:e.url,children:e.url})]},e.url))}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Page details are not available in the loaded page sample.`}),i.length>Kx?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`+ `,i.length-Kx,` more below pass`]}):null,H&&(!r||!w.isLoading&&!w.error)?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Showing the worst `,ee.length,` audited pages.`]}):null]}):null]})})}):null]},e.id)})})]})})]}),!r&&B.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:B.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)(Y,{tone:Yx(e.avgScore),children:iS(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 (`,$e(e.affectedPct,Lt.percent),`)`]})]}),e.topRecommendations.length>0?(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1`,children:e.topRecommendations.map((e,t)=>(0,Q.jsxs)(`li`,{className:`flex gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(`span`,{className:`select-none text-faint`,children:`→`}),(0,Q.jsx)(`span`,{children:e})]},t))}):null]},e.factorId))})]}):null,r?null:(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Pages`}),(0,Q.jsx)(`h2`,{children:`Per-page breakdown`})]}),te?(0,Q.jsxs)(`div`,{className:`segmented`,role:`group`,"aria-label":`Filter pages`,children:[(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{s(!1),V.setPage(1)},"aria-pressed":!ne,className:`segmented-option min-h-11 tabular-nums ${ne?``:`segmented-option-active`}`,children:[`All `,B.pagesAudited]}),(0,Q.jsxs)(`button`,{type:`button`,onClick:()=>{s(!0),V.setPage(1)},"aria-pressed":ne,className:`segmented-option min-h-11 tabular-nums ${ne?`segmented-option-active text-negative`:``}`,children:[`Errors `,B.pagesErrored]})]}):null]}),ee.length>0?(0,Q.jsx)(Ml,{value:V.query,onChange:V.setQuery,label:`Filter audited page URLs`,placeholder:`Filter page URL or query parameters`,className:`mt-3 max-w-md`}):null,V.totalRows===0?(0,Q.jsx)(`p`,{className:`supporting-copy mt-3`,children:V.hasQuery?`No pages match this filter.`:`No pages recorded.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`evidence-table-wrap mt-3`,children:(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{className:`text-right`,children:`Score`}),(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{className:`w-full`,children:`URL`})]})}),(0,Q.jsx)(`tbody`,{children:V.rows.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.status===`error`?(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1 text-negative-400`,children:[(0,Q.jsx)(E,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`err`]}):(0,Q.jsx)(`span`,{className:Xx(e.overallScore),children:e.overallScore})}),(0,Q.jsx)(`td`,{children:e.status===`error`?(0,Q.jsx)(Y,{tone:`negative`,children:`Error`}):(0,Q.jsx)(Y,{tone:Yx(e.overallScore),children:iS(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)(Al,{value:e.url,headLength:54,tailLength:20,title:e.status===`error`?e.error??e.url:e.url})})})]},e.url))})]})}),(0,Q.jsx)(Nl,{page:V.page,pageSize:V.pageSize,visibleRows:V.rows.length,totalRows:V.totalRows,onPageChange:V.setPage,itemLabel:V.hasQuery?`matches`:`rows`}),H?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-13 text-faint`,children:[`Showing the worst `,ee.length,` of `,B.pagesAudited,` audited pages.`]}):null]})]})]})}function cS({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===rn.score&&e.value!==null?`/100`:void 0,change:_u(e.change,e.unit),series:yu(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`&&uu(e))?null:(0,Q.jsx)(`section`,{"aria-label":`Agent Readiness over time`,className:`border-b border-default py-5`,children:(0,Q.jsx)(Tu,{name:`Agent Readiness figures`,groups:[{key:`site-health`,label:`Every scan`,basis:vu(r.figures),figures:i}],selected:[t],onSelect:n,cadence:`scan`,instants:!0,span:bu(o,s)})})}var lS=[{id:`map`,label:`Map`},{id:`inventory`,label:`Pages`},{id:`technical`,label:`Score`}],uS={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.`},dS=[{id:`all`,label:`All pages`,healthState:void 0},{id:`hidden`,label:`Hidden pages`,healthState:xe.hidden}];function fS(e,t,n){let r=Zv(e,n)||t,i=r.indexOf(`?`);if(i<0)return{path:r,query:null};let a=r.slice(i),o=a;try{o=decodeURIComponent(a.replaceAll(`+`,` `))}catch{o=a}return{path:r.slice(0,i),query:o}}function pS(e){return e?e.urlVersions+(e.urlVersionsNotFetched??0):null}function mS(e){let t=`${NS(e)} URL version${e===1?``:`s`} skipped`;return{label:t,text:`${t}. 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 hS={[or.metaRobotsNoindex]:`Hidden by meta robots tag`,[or.xRobotsNoindex]:`Hidden by X-Robots-Tag header`,[or.robotsDisallow]:`Blocked by robots.txt`,[or.redirectTerminal]:`Redirects to another page`,[or.canonicalToOther]:`Points to another page as canonical`,[or.notHtmlOrUnavailable]:`Not an HTML page, so it was not scored`},gS=new Map(Object.entries(hS));function _S(e){return gS.get(e)??e}var vS=20,yS=200,bS=100,xS=100,SS=50,CS=Me,wS=nt,TS=new Intl.NumberFormat,ES=new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}),DS={eligible:`positive`,hidden:`caution`,resource:`neutral`,redirect:`neutral`,failed:`negative`,unchecked:`neutral`};function OS(e){if(!e)return`Date unavailable`;let t=new Date(e);return Number.isNaN(t.getTime())?`Date unavailable`:ES.format(t)}function kS(e){return e.replaceAll(`_`,` `).replaceAll(`-`,` `).replace(/\b\w/g,e=>e.toUpperCase())}function AS(e){let t=ux(e);return{label:dx(t),tone:DS[t]}}function jS(e){return e==null?`Not scored`:$e(e,Lt.percent)}function MS(e){return e.auditScore==null?`Not checked`:`${Math.round(e.auditScore)}/100`}function NS(e){return e==null?`Not available`:TS.format(e)}var PS={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.`},FS=new Set([`clicksFromHome`,`linkImportance`,`internalLinks`,`pagesFound`,`pagesChecked`]);function IS(e,t){let n=PS[e];return FS.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 LS(e,t){return`${TS.format(e)} ${t}${e===1?``:`s`}`}function RS(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 zS(e){return e===`completed`?`positive`:e===`partial`||e===`queued`||e===`running`?`caution`:e===`failed`||e===`cancelled`?`negative`:`neutral`}function BS(e){return e?.hasData?e.runStatus===Ot.partial?`Score so far ${e.aggregateScore}/100`:e.runStatus===Ot.completed?`Score ${e.aggregateScore}/100`:null:null}var VS=`Latest scan`,HS=`Shows the most complete scan from the latest day with results. Choose a dated entry to view another scan.`;function US(e){let t=OS(e.finishedAt??e.startedAt??e.createdAt),n=e.hasCrawlData?``:` · Score only`;return`${t} · ${kS(e.status)}${n}`}var WS=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.`})),GS=ic,KS=[{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)`}],qS={"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 JS(e){return e?qS[e]??null:null}function YS(e){return e?WS.get(e)??`This scan stopped early: ${e}.`:`This scan stopped before it checked every page it found.`}var XS={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.`},ZS=new Map(Object.entries(XS));function QS(e){return e===null?``:ZS.get(e)??XS[`unavailable-legacy-scan`]}var $S=`Scroll to zoom. Click a page to inspect it.`,eC=`Observed links to and from this page in the selected scan.`,tC=`Page positions on this map were set before menu and footer links were separated. Run a new scan to update them.`;function nC(e){if(e.filterUnavailable)return`All ${LS(e.totalEdgeCount,`link`)} shown.`;let t=`${TS.format(e.contentEdgeCount)} link${e.contentEdgeCount===1?``:`s`} in your page text`,n=TS.format(e.templateEdgeCount);return e.showTemplateLinks?`${t}, ${n} menu and footer.`:`${t}. ${n} menu and footer link${e.templateEdgeCount===1?``:`s`} hidden.`}var rC=`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 iC(e,t){let n=[rC,QS(e)];return t.staleLayout&&n.push(tC),n.filter(Boolean).join(` `)}function aC(e,t,n){if(e===`disabled`)return{label:`Broken links: not checked`,tone:`neutral`};let r=n??0,i=r>0?`, ${TS.format(r)} unchecked`:``;return e===`complete`?t?{label:`Broken links: ${TS.format(t)} found${i}`,tone:`negative`}:r>0?{label:`Broken links: none found, ${TS.format(r)} unchecked`,tone:`caution`}:{label:`Broken links: none found`,tone:`positive`}:e===`partial`?{label:`Broken links: ${TS.format(t??0)} found so far${i}`,tone:`caution`}:{label:`Broken links: not checked`,tone:`neutral`}}function oC(e){return e.showTemplateLinks||!e.known?{value:NS(e.total),hiddenNote:null,filtered:!1}:{filtered:!0,value:e.truncated?`${NS(e.visible)}+`:NS(e.visible),hiddenNote:e.hidden===0?null:e.truncated?`At least ${NS(e.hidden)} menu and footer hidden`:`${NS(e.hidden)} menu and footer hidden`}}function sC({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 cC({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)(sC,{label:`Clicks from home`,value:String(e.depth??`Not reached`),help:IS(`clicksFromHome`,!1)}),(0,Q.jsx)(sC,{label:`Links in`,value:t.value,hiddenNote:t.hiddenNote,help:IS(`linksIn`,t.filtered)}),(0,Q.jsx)(sC,{label:`Links out`,value:n.value,hiddenNote:n.hiddenNote,help:IS(`linksOut`,n.filtered)}),(0,Q.jsx)(sC,{label:`Link importance`,value:jS(e.linkScoreNormalized),help:IS(`linkImportance`,!1)})]})})}function lC(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 ${NS(t)} menu and footer links hidden.`:`${LS(t,`menu and footer link`)} hidden.`}`}function uC({label:e,metric:t}){return(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[e,(0,Q.jsx)(X,{text:IS(t,!1)})]})}function dC({direction:e,edges:t,truncated:n,rootHost:r,hiddenTemplateCount:i}){let a=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:[a,` (`,NS(t.length),`)`]}),n&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`First `,xS]})]}),t.length===0?(0,Q.jsx)(`p`,{className:`material-base px-3 py-4 text-copy-14 text-secondary`,children:lC(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)(uC,{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:Zv(n,r)}),(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:NS(t.occurrences)})]},t.edgeKey)})})]})})]})}function fC(e){return e&&`indexabilityReasons`in e?e.indexabilityReasons:[]}function pC({page:e,isLoading:t,error:n,inbound:r,outbound:i,inboundTruncated:a,outboundTruncated:o,audit:l,auditLoading:u,auditError:d,onRetryAudit:f,rootHost:p,reasonSource:m,reasonsState:h,onRetryReasons:g,showTemplateLinks:_}){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 v=AS(e),y=fC(m??e),b=m?.urlVersionOf??null,x=_?r:r.filter(e=>!e.isTemplate),S=_?i:i.filter(e=>!e.isTemplate),C=!t&&!n,w=r.length-x.length,T=i.length-S.length,E=oC({total:e.inboundUniqueEdges,visible:x.length,hidden:w,truncated:a,showTemplateLinks:_,known:C}),D=oC({total:e.outboundUniqueEdges,visible:S.length,hidden:T,truncated:o,showTemplateLinks:_,known:C});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:e.path}),(0,Q.jsx)(Y,{tone:v.tone,children:v.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)(J,{type:`button`,variant:`secondary`,size:`sm`,onClick:g,children:`Try again`})]}):y.length>0||b?(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:[b&&(0,Q.jsx)(`li`,{children:`URL version of ${Zv(b,p)}, not scored`}),y.map(e=>(0,Q.jsx)(`li`,{children:_S(e)},e))]}):null]}),(0,Q.jsx)(J,{asChild:!0,variant:`secondary`,size:`sm`,children:(0,Q.jsxs)(`a`,{href:e.url,target:`_blank`,rel:`noreferrer`,children:[`Open page `,(0,Q.jsx)(s,{className:`size-3.5`,"aria-hidden":`true`})]})})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(Hx,{audit:l,isLoading:u,error:d,onRetry:f})}),(0,Q.jsxs)(`section`,{className:`mt-5 border-t border-default pt-5`,"aria-labelledby":`site-health-page-links-heading`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`h3`,{id:`site-health-page-links-heading`,className:`text-heading-16 text-heading`,children:`Internal links`}),(0,Q.jsx)(X,{text:eC})]}),(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(cC,{page:e,inbound:E,outbound:D})}),(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)(dC,{direction:`inbound`,edges:x,truncated:a,rootHost:p,hiddenTemplateCount:w}),(0,Q.jsx)(dC,{direction:`outbound`,edges:S,truncated:o,rootHost:p,hiddenTemplateCount:T})]})})]})]})}function mC({pages:e,total:t,skippedUrlVersions:n,rootHost:r,selectedNodeKey:i,onSelect:a,hasNextPage:o,isFetchingNextPage:s,onLoadMore:l,filter:u,onFilterChange:d,filterUnavailable:f}){let[p,m]=(0,Z.useState)(``),h=p.trim().toLowerCase(),g=(0,Z.useMemo)(()=>h?e.filter(e=>`${e.path} ${e.url}`.toLowerCase().includes(h)):e,[h,e]),_=h.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 ${NS(e.length)} of ${NS(t)} pages.`:`Showing ${NS(e.length)} of ${NS(t)} hidden pages.`}),n!=null&&n>0&&(0,Q.jsx)(X,{...mS(n)})]})]}),(0,Q.jsxs)(`div`,{className:`flex w-full flex-wrap items-center gap-2 sm:w-auto`,role:`group`,"aria-label":`Page filters`,children:[(0,Q.jsx)(`select`,{"aria-label":`Filter pages by status`,value:u,onChange:e=>{let t=dS.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:dS.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))}),(0,Q.jsxs)(`label`,{className:`relative block min-w-0 flex-1 sm:w-72 sm:flex-none`,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:p,onChange:e=>m(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:px(`eligible`),children:`Status`}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(uC,{label:`Clicks from home`,metric:`clicksFromHome`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(uC,{label:`Links in`,metric:`linksIn`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(uC,{label:`Links out`,metric:`linksOut`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(uC,{label:`Link importance`,metric:`linkImportance`})}),(0,Q.jsx)(`th`,{scope:`col`,children:(0,Q.jsx)(uC,{label:`Score`,metric:`technicalScore`})})]})}),(0,Q.jsx)(`tbody`,{children:g.map(e=>{let t=AS(e),n=fS(e.url,e.path,r);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:n.path}),n.query&&(0,Q.jsx)(`span`,{className:`line-clamp-2 [overflow-wrap:anywhere] text-label-12-mono text-secondary`,children:n.query})]})}),(0,Q.jsx)(`td`,{title:px(ux(e)),children:(0,Q.jsx)(Y,{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:NS(e.inboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:NS(e.outboundUniqueEdges)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:jS(e.linkScoreNormalized)}),(0,Q.jsx)(`td`,{className:`tabular-nums`,children:MS(e)})]},e.nodeKey)})})]})}),g.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:h.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.`:_?`No matches in the ${NS(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)(J,{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 hC({projectName:e,runId:t,section:n,onSelect:r}){let[i,a]=(0,Z.useState)(!1),o=n.pageCount-+!!n.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:[o?(0,Q.jsx)(`button`,{type:`button`,"aria-label":`${i?`Collapse`:`Expand`} ${n.path}`,"aria-expanded":i,onClick:()=>a(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:i?(0,Q.jsx)(y,{className:`size-3.5`,"aria-hidden":`true`}):(0,Q.jsx)(d,{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:()=>r(n.path),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:n.path}),(0,Q.jsx)(`span`,{className:`shrink-0 px-2 text-label-12-mono text-muted`,children:NS(n.pageCount)})]}),i&&(0,Q.jsx)(`div`,{className:`ml-6 border-l border-default pl-1`,children:(0,Q.jsx)(_C,{projectName:e,runId:t,parentPath:n.path,onSelect:r})})]})}function gC({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:NS(1)})]})})}function _C({projectName:e,runId:t,parentPath:n,onSelect:r,rootPage:i,onSelectRootPage:a}){let o={client:q,path:{name:e},query:{runId:t,parentPath:n,limit:bS}},s=B({...Ya(o),initialPageParam:o,getNextPageParam:e=>e.nextCursor?{path:o.path,query:{...o.query,cursor:e.nextCursor}}:void 0}),l=s.data?.pages.flatMap(e=>e.children)??[];return s.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…`]}):s.error?(0,Q.jsx)(`p`,{className:`px-3 py-4 text-copy-14 text-negative`,role:`alert`,children:`Site sections could not be loaded.`}):l.length===0&&!i?(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:[i&&a&&(0,Q.jsx)(gC,{page:i,onSelect:a}),l.map(n=>(0,Q.jsx)(hC,{projectName:e,runId:t,section:n,onSelect:r},n.path))]}),s.hasNextPage&&(0,Q.jsx)(`div`,{className:`px-3 py-2`,children:(0,Q.jsx)(J,{variant:`ghost`,size:`sm`,disabled:s.isFetchingNextPage,onClick:()=>void s.fetchNextPage(),children:s.isFetchingNextPage?`Loading more sections`:`Load more sections`})})]})}function vC(){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 yC(e){return e===`discovering`?`Discovering pages`:e===`checking`?`Checking pages`:e===`arranging-map`?`Arranging map`:e===`queued`?`Waiting to start`:`Preparing scan`}var bC=3;function xC(e){return e===`checking`?1:e===`arranging-map`?2:0}function SC({phase:e,pagesChecked:t}){let n=xC(e),r=[`Find pages`,n===1&&t!==null?`Check pages · ${NS(t)}`:`Check pages`,`Build map`];return(0,Q.jsxs)(`div`,{className:`mt-4`,role:`progressbar`,"aria-label":`Scan progress`,"aria-valuemin":0,"aria-valuemax":bC,"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)(k,{className:`h-3.5 w-3.5 shrink-0`,"aria-hidden":`true`}):null,(0,Q.jsx)(`span`,{className:`truncate`,children:e})]},e))})]})}function CC(e){return e!==`completed`&&e!==`partial`&&e!==`failed`&&e!==`cancelled`}function wC(e){return e===`queued`||e===`discovering`||e===`checking`||e===`arranging-map`}function TC(e){return e===`completed`||e===`partial`||e===`failed`||e===`cancelled`}function EC(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 DC({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 OC({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.`:`${yC(a)}. The map appears after the scan finishes.`}),(0,Q.jsx)(SC,{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?NS(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?NS(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?NS(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?NS(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)(J,{type:`button`,variant:`secondary`,size:`sm`,onClick:r,children:`Retry progress`})]})]})}function kC({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)(J,{type:`button`,className:`mt-4`,onClick:n,children:`Run scan again`})]})}function AC({projectName:e,projectId:t,initialRunId:n,onReleaseInitialRun:r}){let i=(0,Z.useId)(),[a,o]=(0,Z.useState)(`map`),s=(0,Z.useRef)([]),l=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=e=>{l.current?.open&&e.target instanceof Node&&!l.current.contains(e.target)&&(l.current.open=!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[]);let[u,d]=(0,Z.useState)(()=>n??null),[f,p]=(0,Z.useState)(null),m=(0,Z.useRef)(n),[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(!1),[b,x]=(0,Z.useState)(!1),[S,C]=(0,Z.useState)(!0),[w,D]=(0,Z.useState)(null),[O,k]=(0,Z.useState)(null),[j,M]=(0,Z.useState)(`all`),[N,P]=(0,Z.useState)(!1),F=G(),{isAdmin:I}=ji(),L=tt(),R=(L||tr(Ct[`site-audit`]))&&!I,z=dc(),ee=!F&&!R,te=U({...So({client:q,path:{name:e}}),enabled:ee,staleTime:Ii});(0,Z.useEffect)(()=>{let e=m.current;e!==n&&(m.current=n,d(t=>n??(t===e?null:t)),g(null))},[n]);let ne=U({...fo({client:q,path:{name:e},query:{limit:vS}}),refetchOnWindowFocus:`always`,refetchInterval:e=>e.state.data?.scans.some(e=>e.status===`queued`||e.status===`running`)?3e3:15e3}),V=ne.data?.scans??[],H=V.find(e=>e.status===`queued`||e.status===`running`),re=V.find(e=>e.status===`completed`||e.status===`partial`),ie=z.data?.runId??null,ae=ie&&ie!==f&&V.some(e=>e.runId===ie&&(e.status===`completed`||e.status===`partial`))?ie:null,oe=u??ae??ne.data?.preferredRunId??re?.runId??H?.runId??null,se=H?.runId===oe?H:null,ce=oe?V.find(e=>e.runId===oe):void 0,le=!!(n&&oe===n),ue=se?.runId??(le?oe:null),de=U({...mo({client:q,path:{name:e,runId:ue??``}}),enabled:!!ue,refetchInterval:e=>CC(e.state.data?.phase)?3e3:!1,refetchIntervalInBackground:!0});(0,Z.useEffect)(()=>{le&&de.isError&&EC(de.error)===`NOT_FOUND`&&(d(null),g(null),r?.())},[de.error,de.isError,le,r]);let fe=wC(de.data?.phase),pe=TC(de.data?.phase)?null:se,me=!!(ue&&de.isPending),he=!!(le&&!ce&&de.isError),ge=!!(pe||fe||me||he),_e=de.data?.phase===`failed`||de.data?.phase===`cancelled`?de.data.phase:le&&(ce?.status===`failed`||ce?.status===`cancelled`)?ce.status:null,ve=U({...Oo({client:q,path:{name:e},...oe?{query:{runId:oe}}:{}}),enabled:!ge}),ye=ve.data,be=oe??ye?.runId??null,xe=!!(be&&ye?.hasCrawlData&&ye.detailsAvailable),Se=be?{runId:be}:{},Ce=U({...ro({client:q,path:{name:e},query:{...Se,maxNodes:CS,maxEdges:wS}}),enabled:xe&&!ge}),we=dS.find(e=>e.id===j)?.healthState,Te={client:q,path:{name:e},query:{...Se,...we?{healthState:we}:{},urlVersions:`exclude`,limit:yS,sort:`path`}},Ee=B({...to(Te),enabled:xe,initialPageParam:Te,getNextPageParam:e=>e.nextCursor?{path:Te.path,query:{...Te.query,cursor:e.nextCursor}}:void 0}),De=xe&&(ye?.deadLinks.state===`complete`||ye?.deadLinks.state===`partial`),W=U({...Uo({client:q,path:{name:e},query:{...Se,limit:SS}}),enabled:De}),Oe=Ce.data?.nodes??[],ke=Ce.data?.edges??[],Ae=(0,Z.useMemo)(()=>ke.filter(e=>e.isTemplate).length,[ke]),je=ke.length-Ae,Me=Ce.data?.templateDetection??null,Ne=Me===null||!bt(Me),Pe=(0,Z.useMemo)(()=>N||Ne?ke:ke.filter(e=>!e.isTemplate),[ke,N,Ne]),Fe=Ce.data?.layout.state===`ready`&&!Ce.data.layout.templateLinksExcluded,Ie=(0,Z.useMemo)(()=>Ee.data?.pages.flatMap(e=>e.pages)??[],[Ee.data]),Le=Ee.data?.pages[0]?.total??Ie.length,Re=(0,Z.useMemo)(()=>Ie.find(e=>e.nodeKey===h)??null,[Ie,h]),ze=!!(xe&&h&&!Re),Be=U({...Co({client:q,path:{name:e},query:{...Se,...we?{healthState:we}:{},nodeKey:h??void 0,limit:1}}),enabled:ze}),Ve=Re??Be.data?.pages[0]??null,He=!!(h&&we&&ze&&Be.isSuccess&&Be.data.healthStateFilter===`applied`&&Be.data.pages.length===0);(0,Z.useEffect)(()=>{He&&g(null)},[He]);let Ue=(0,Z.useMemo)(()=>He?null:Oe.find(e=>e.nodeKey===h)??Ve,[Oe,Ve,h,He]),We=Ue?.nodeKey??null;bc(e,{view:`site-health`,page:{...be?{runId:be}:{},...We?{nodeKey:We}:{}}});let Ge=Ue?Ve?`ready`:Be.isError?`error`:ze&&Be.isLoading?`loading`:`ready`:`idle`,Ke=U({...co({client:q,path:{name:e},query:{...Se,nodeKey:We??void 0,limit:xS}}),enabled:xe&&!!We}),qe=U({...zo({client:q,path:{name:e},query:{...Se,nodeKey:We??void 0}}),enabled:xe&&!!We}),Je=(0,Z.useMemo)(()=>{let e=V.filter(e=>e.status===`completed`||e.status===`partial`),t=u?V.find(e=>e.runId===u):void 0;return t&&!e.some(e=>e.runId===t.runId)?[t,...e]:e},[V,u]),Ye=Je.length>0,Xe=V[0]?.status??null,Ze=be?ce:void 0,Qe=pe?pe.status:fe?de.data?.status??null:_e??ye?.runStatus??Ze?.status??null,$e=Qe===`running`?`Scan running`:Qe===`queued`?`Scan queued`:Qe===`partial`?`Partial scan`:Qe===`completed`?`Complete`:Qe===`failed`?`Scan failed`:Qe===`cancelled`?`Scan cancelled`:`No scan`,et=!!be&&(Qe===Ot.completed||Qe===Ot.partial),nt=U({...jo({client:q,path:{name:e},...be?{query:{runId:be}}:{}}),enabled:et}),rt=et?BS(nt.data):null,K=W.data,it=K&&`found`in K?K:ye?.deadLinks&&`found`in ye.deadLinks?ye.deadLinks:void 0,at=aC(K?.state??ye?.deadLinks?.state??`unavailable`,it?.found,it?.unverified),ot=RS(ye?.requestedRootUrl??null,ye?.rootUrl??null),st=Jv(ye?.rootUrl??null),ct=Ce.data?.rootNodeKey??null,lt=U({...Co({client:q,path:{name:e},query:{...Se,nodeKey:ct??void 0,limit:1}}),enabled:!!(xe&&ct)}),ut=(0,Z.useMemo)(()=>Oe.find(e=>e.nodeKey===ct)??lt.data?.pages[0]??null,[Oe,ct,lt.data]),dt=H&&H.runId!==oe?H:null,ft=z.isPending||!!pe||!!dt||fe||me,pt=a===`technical`?`map`:a,mt=e=>{d(e||null),p(ie),g(null)},ht=()=>{(!L&&!tr(Ct[`site-audit`])||I)&&(l.current&&(l.current.open=!1),d(null),g(null),n&&r?.(),z.mutate({projectName:e,projectId:t,projectLabel:te.data?.displayName||e,body:{checkDeadLinks:_,...b?{includeGeo:!0}:{},...S?{}:{includeAgentSkills:!1},...w===null?{}:{maxPages:w},...O===null?{}:{maxDepth:O}}}))},gt=e=>{let t=Oe.find(t=>t.path===e||t.path.startsWith(`${e}/`));t&&g(t.nodeKey)},_t=e=>o(e),vt=(e,t)=>{let n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%lS.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+lS.length)%lS.length:e.key===`Home`?n=0:e.key===`End`&&(n=lS.length-1),n!=null&&(e.preventDefault(),_t(lS[n].id),s.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:uS[a]}),(0,Q.jsx)(Y,{tone:zS(Qe),children:$e}),rt&&(0,Q.jsx)(`span`,{className:`text-label-14-strong tabular-nums text-heading`,children:rt}),Ze&&(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:OS(Ze.finishedAt??Ze.startedAt)})]})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start gap-2`,children:[Ye&&(0,Q.jsxs)(`div`,{className:`grid gap-1 text-label-12 text-muted`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`label`,{htmlFor:i,children:`Scan history`}),(0,Q.jsx)(X,{text:HS,placement:`bottom`})]}),(0,Q.jsxs)(`select`,{id:i,"aria-label":`View an Agent Readiness audit scan`,value:u??ae??``,onChange:e=>mt(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:VS}),Je.map(e=>(0,Q.jsx)(`option`,{value:e.runId,children:US(e)},e.runId))]})]}),!F&&!R&&(0,Q.jsxs)(`div`,{className:ln(`flex items-end gap-2`,Ye&&`pt-5`),children:[(0,Q.jsxs)(`details`,{ref:l,className:`group relative`,onKeyDown:e=>{e.key===`Escape`&&e.currentTarget.open&&(e.preventDefault(),e.currentTarget.open=!1,e.currentTarget.querySelector(`summary`)?.focus())},children:[(0,Q.jsxs)(`summary`,{className:`flex h-9 cursor-pointer list-none items-center gap-2 rounded-md border border-base bg-bg px-3 text-label-14-strong text-heading outline-none hover:bg-bg-elevated focus-visible:ring-2 focus-visible:ring-mono-400 [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(T,{className:`size-4`,"aria-hidden":`true`}),`Scan settings`,(0,Q.jsx)(y,{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:[(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:_,disabled:ft,onChange:e=>v(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:Ix[`geographic-signals`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Geographic signals`,checked:b,disabled:ft,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:Ix[`agent-skill-exposure`],placement:`bottom`})]}),(0,Q.jsx)(`input`,{type:`checkbox`,"aria-label":`Agent integrations`,checked:S,disabled:ft,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:cc,placement:`bottom`})]}),(0,Q.jsxs)(`select`,{"aria-label":`Page budget`,value:w===null?``:String(w),disabled:ft,onChange:e=>D(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:Xs(te.data)}),[...Zs(te.data)?[Zs(te.data)]:[],...GS].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:ft,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:KS.map(e=>(0,Q.jsx)(`option`,{value:e.value===null?``:String(e.value),children:e.label},String(e.value)))})]})]})]}),(0,Q.jsxs)(Rr,{onClick:ht,disabled:ft,children:[ft?(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}):(0,Q.jsx)(A,{className:`size-4`,"aria-hidden":`true`}),H?.status===`running`?`Scan running`:H?.status===`queued`?`Scan queued`:`Run scan`]})]})]})]}),R&&(0,Q.jsx)(ys,{projectName:e,kind:Ct[`site-audit`],loadSchedule:!L}),ye?.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:IS(`pagesFound`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:NS(ye.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:IS(`pagesChecked`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:NS(ye.counts.pagesFetched)})]}),(0,Q.jsxs)(`div`,{className:`px-4 py-3`,children:[(0,Q.jsx)(`div`,{className:`text-label-12 text-muted`,title:px(`eligible`),children:`Indexable`}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:NS(ye.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:IS(`internalLinks`,!1)})]}),(0,Q.jsx)(`div`,{className:`mt-1 text-label-20-strong tabular-nums text-heading`,children:NS(ye.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:lS.map((e,t)=>(0,Q.jsx)(`button`,{type:`button`,role:`tab`,id:`site-health-${e.id}-tab`,"aria-selected":a===e.id,"aria-controls":`site-health-${e.id}-panel`,tabIndex:a===e.id?0:-1,ref:e=>{s.current[t]=e},onClick:()=>_t(e.id),onKeyDown:e=>vt(e,t),className:`min-h-11 border-b-2 px-0.5 text-button-14 outline-none transition-colors focus-visible:ring-2 focus-visible:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-50 ${a===e.id?`border-strong text-heading`:`border-transparent text-secondary hover:border-base hover:text-primary`}`,children:e.label},e.id))}),ye?.hasCrawlData&&a!==`technical`&&(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 pb-2`,children:[(0,Q.jsx)(`span`,{className:`text-label-12 text-muted`,children:`Dead-link check`}),(0,Q.jsx)(Y,{tone:at.tone,children:at.label})]})]}),!u&&H&&!pe&&(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.`}),ot&&(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:ot.requested}),` and continued at`,` `,(0,Q.jsx)(`span`,{className:`font-mono text-primary`,children:ot.effective}),`.`,` `,`The map and inventory use the new address.`]}),ye?.hasCrawlData&&!ye.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:[YS(ye.termination),` `,!F&&!R?JS(ye.termination):null]}),!H&&Xe===`failed`&&!u&&(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)(E,{className:`mt-0.5 size-4 shrink-0`,"aria-hidden":`true`}),(0,Q.jsx)(`span`,{children:ye?.hasCrawlData?`The latest scan failed. The previous completed results remain available.`:`The latest scan failed, and there are no earlier results to show.`})]}),_e?(0,Q.jsx)(DC,{view:pt,children:(0,Q.jsx)(kC,{phase:_e,progress:de.data,onRunAgain:R?void 0:ht})}):ge?(0,Q.jsx)(DC,{view:pt,children:(0,Q.jsx)(OC,{status:de.data?.phase??(pe?.status===`running`?`running`:`queued`),progress:de.data,progressError:de.isError,onRetryProgress:()=>{de.refetch()}})}):a===`technical`?(0,Q.jsx)(`div`,{id:`site-health-technical-panel`,role:`tabpanel`,"aria-labelledby":`site-health-technical-tab`,className:`min-w-0 space-y-6`,children:(0,Q.jsx)(sS,{projectName:e,projectId:t,runId:be,integrated:!0})}):ve.isLoading?(0,Q.jsx)(DC,{view:a,children:(0,Q.jsxs)(`div`,{className:`flex min-h-72 items-center justify-center gap-2 text-label-14 text-secondary`,role:`status`,children:[(0,Q.jsx)(c,{className:`size-4 motion-safe:animate-spin`,"aria-hidden":`true`}),`Loading Agent Readiness…`]})}):ve.error?(0,Q.jsx)(DC,{view:a,children:(0,Q.jsxs)(`section`,{className:`rounded-md border border-negative bg-negative-soft px-5 py-6`,role:`alert`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-14 text-negative`,children:`Agent Readiness could not load`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-negative`,children:`Try loading the crawl again.`}),(0,Q.jsx)(J,{variant:`secondary`,size:`sm`,className:`mt-4`,onClick:()=>void ve.refetch(),children:`Try again`})]})}):ye?.hasCrawlData?ye.detailsAvailable?a===`inventory`?(0,Q.jsxs)(`div`,{id:`site-health-inventory-panel`,role:`tabpanel`,"aria-labelledby":`site-health-inventory-tab`,className:`space-y-5`,children:[Ee.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…`]}):Ee.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)(mC,{pages:Ie,total:Le,skippedUrlVersions:pS(Ee.data?.pages[0]?.inventorySummary),rootHost:st,filterUnavailable:Ee.data?.pages[0]?.healthStateFilter===`unavailable-legacy-scan`,selectedNodeKey:We,onSelect:g,hasNextPage:!!Ee.hasNextPage,isFetchingNextPage:Ee.isFetchingNextPage,onLoadMore:()=>void Ee.fetchNextPage(),filter:j,onFilterChange:M}),(0,Q.jsx)(pC,{page:Ue,isLoading:Ke.isLoading&&!!Ue,error:Ke.error,inbound:Ke.data?.inbound??[],outbound:Ke.data?.outbound??[],inboundTruncated:Ke.data?.inboundTruncated??!1,outboundTruncated:Ke.data?.outboundTruncated??!1,audit:qe.data,auditLoading:qe.isLoading&&!!Ue,auditError:qe.error,onRetryAudit:()=>{qe.refetch()},rootHost:st,reasonSource:Ve,reasonsState:Ge,onRetryReasons:()=>{Be.refetch()},showTemplateLinks:N||Ne})]}):(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:$S})]})}),Ce.data?.sampled&&(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`Map limited to `,NS(Ce.data.nodes.length),` of `,NS(Ce.data.totalNodes),` pages`,` and `,NS(Ce.data.edges.length),` of `,NS(Ce.data.totalEdges),` links`]})]}),Ce.data?.layout.state===`ready`&&ke.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:[nC({filterUnavailable:Ne,showTemplateLinks:N,contentEdgeCount:je,templateEdgeCount:Ae,totalEdgeCount:ke.length}),(0,Q.jsx)(X,{text:iC(Me,{staleLayout:Fe&&!Ne})})]}),(0,Q.jsxs)(`label`,{className:ln(`flex shrink-0 items-center gap-2 text-label-14`,Ne?`cursor-not-allowed text-muted`:`cursor-pointer text-heading`),title:Ne?QS(Me):`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:N&&!Ne,disabled:Ne,onChange:e=>P(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:`Folders in this scan`})]}),(0,Q.jsx)(`div`,{className:`max-h-[468px] overflow-auto`,children:be&&(0,Q.jsx)(_C,{projectName:e,runId:be,parentPath:`/`,onSelect:gt,rootPage:ut,onSelectRootPage:g})})]}),(0,Q.jsx)(`div`,{className:`min-w-0`,children:Ce.isLoading?(0,Q.jsx)(vC,{}):Ce.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)(J,{variant:`secondary`,size:`sm`,className:`mt-4`,onClick:()=>o(`inventory`),children:`Open page inventory`})]})}):(0,Q.jsx)(Fx,{nodes:Ce.data?.nodes??[],edges:ke,showTemplateLinks:N||Ne,layoutState:Ce.data?.layout.state??`unavailable`,layoutUnavailableReason:Ce.data?.layout.state===`unavailable`?Ce.data.layout.reason:null,rootNodeKey:Ce.data?.rootNodeKey??null,selectedNodeKey:We,onSelectNode:e=>g(e.nodeKey),onOpenInventory:()=>o(`inventory`),ariaLabel:`Interactive site map showing ${LS(Ce.data?.nodes.length??0,`page`)} and ${LS(Pe.length,`internal link`)}`})})]})]}),(0,Q.jsx)(pC,{page:Ue,isLoading:Ke.isLoading&&!!Ue,error:Ke.error,inbound:Ke.data?.inbound??[],outbound:Ke.data?.outbound??[],inboundTruncated:Ke.data?.inboundTruncated??!1,outboundTruncated:Ke.data?.outboundTruncated??!1,audit:qe.data,auditLoading:qe.isLoading&&!!Ue,auditError:qe.error,onRetryAudit:()=>{qe.refetch()},rootHost:st,reasonSource:Ve,reasonsState:Ge,onRetryReasons:()=>{Be.refetch()},showTemplateLinks:N||Ne})]}):(0,Q.jsx)(DC,{view:a,children:(0,Q.jsxs)(`section`,{className:`rounded-md border border-caution bg-caution-soft px-5 py-6`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-14 text-caution`,children:`Page details unavailable`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-caution`,children:`Summary metrics are preserved for this scan, but its page graph cannot be opened.`})]})}):(0,Q.jsx)(DC,{view:a,children:(0,Q.jsxs)(`section`,{className:`material-base px-5 py-8 text-center`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-16 text-heading`,children:`Full-site map not available`}),(0,Q.jsx)(`p`,{className:`mx-auto mt-2 max-w-xl text-copy-14 text-secondary`,children:R?Ls:ye?.legacyAuditAvailable?`The existing score is preserved. Run a new scan to build the page and internal-link map.`:F?`An Agent Readiness audit scan has not been run for this project.`:`Run a scan to discover pages, site sections, and internal links.`}),ye?.legacyAuditAvailable&&(0,Q.jsx)(`div`,{className:`mt-4 flex flex-wrap justify-center gap-2`,children:(0,Q.jsx)(J,{variant:`secondary`,size:`sm`,onClick:()=>o(`technical`),children:`View score`})})]})})]})}function jC({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=U({...No({client:q,path:{name:e},query:{limit:30}}),enabled:n===`health`}),l=U({...ns({client:q,path:{name:e},query:{kind:Ct[`answer-visibility`],limit:100}}),enabled:n===`compare`}),u=(l.data??[]).filter(e=>(e.status===Ot.completed||e.status===Ot.partial)&&e.trigger!==rt.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=U({...go({client:q,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)(Xc,{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)(Sc,{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)(rs,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`No coverage history yet`}),(0,Q.jsx)(`p`,{children:mt()?ms:`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:$e(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:ei.label}):$e(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)(rs,{className:`surface-card empty-card mt-4`,children:[(0,Q.jsx)(`h3`,{children:`Two completed checks are required`}),(0,Q.jsx)(`p`,{children:mt()?ms:`Run another AI Visibility check before comparing historical evidence.`})]}):null,h.data&&_.length===0?(0,Q.jsxs)(rs,{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)(Y,{tone:e.changed?`caution`:`neutral`,children:[e.run1State??`none`,` → `,e.run2State??`none`]})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(Y,{tone:e.visibilityChanged?`caution`:`neutral`,children:[e.run1MentionState??`none`,` → `,e.run2MentionState??`none`]})})]},e.queryId??e.query??`unknown`))})]})}):null]}):null]})]})}var MC={state:`not-connected`,selection:null,snapshotCount:0,evidence:`No stored evidence yet.`,lastSnapshotAt:null},NC={contract:null,assessment:null,googleAds:MC,gtm:MC,snapshots:[]};function PC(e){return e.contractSelectionRequired?`contract-selection-required`:e.assessmentState===`loading`?`assessment-loading`:e.assessmentState===`unavailable`?`assessment-unavailable`:zC(e)?`static-mismatch`:e.assessment?.status??(e.contract?`configured`:`not-configured`)}function FC(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 IC(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 LC(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 RC(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`&&BC(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 zC(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome===`fail`)}function BC(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome!==`pass`)}function VC(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 HC(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 UC(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 WC(e){return e.length<=12?e:`…${e.slice(-10)}`}function GC(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 KC(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 qC={"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 JC(e){return e.outcome===`pass`?{label:qC[e.code],tone:`positive`,outcome:`Pass`}:e.outcome===`fail`?{label:qC[e.code],tone:`negative`,outcome:`Fail`}:{label:qC[e.code],tone:`caution`,outcome:`Unknown`}}function YC(e){return e.runtime.productionHosts.length>0?e.runtime.productionHosts.join(`, `):`the declared production site`}function XC(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 ZC(e){return e.provider===`google-ads`?`Google Ads`:`Tag Manager`}function QC({label:e,connection:t,changeSelectionLabel:n,onChangeSelection:r,actionPending:i}){let a=VC(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)(Y,{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 ${vi(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)(Rr,{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 $C=`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.`,ew=`Available once Google Ads and Tag Manager are connected.`;function tw({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:IC(e)},{title:`Tag Manager`,state:e.gtm.state,ready:s,summary:e.gtm.selection,changeLabel:`Change Tag Manager container`,onChange:r,action:l?d:LC(e)}],p=o&&s&&!u?RC(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:$C})]}),p&&t?(0,Q.jsx)(Rr,{type:`button`,disabled:i,onClick:()=>t(p.id),children:i?`Working…`:p.label}):(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:ew})]}),(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`}:VC(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)(Y,{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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):(0,Q.jsx)(Rr,{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)(Rr,{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 nw({workspace:e=NC,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=PC(e),m=FC(p),h=RC(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)(tw,{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)(Y,{tone:m.tone,children:m.label}),e.assessment?.evaluatedAt?(0,Q.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`Assessed `,vi(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:[ZC(e),` `,e.kind,`, captured `,vi(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)(J,{type:`button`,disabled:n||h.id===`waiting-for-integrity`,onClick:()=>t(h.id),children:n?`Working…`:h.label}):(0,Q.jsx)(Rr,{type:`button`,disabled:n,onClick:()=>t(h.id),children:n?`Working…`:h.label}):h.id===`review-findings`?(0,Q.jsx)(J,{asChild:!0,type:`button`,children:(0,Q.jsx)(`a`,{href:`#conversion-integrity-findings`,children:`Review findings`})}):p===`runtime-unverified`?(0,Q.jsx)(J,{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)(Rr,{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:GC(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:KC(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:WC(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:WC(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:WC(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:WC(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)(J,{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)(Y,{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=JC(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)(Y,{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=HC(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)(Y,{tone:t,children:UC(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:[QC({label:`Google Ads`,connection:e.googleAds,...e.googleAds.state===`connected`||e.googleAds.state===`stale`?{changeSelectionLabel:`Change Google Ads account`,onChangeSelection:u}:{},actionPending:n}),QC({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)(J,{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:vi(e.capturedAt)}),(0,Q.jsx)(`td`,{className:`text-label-12-mono text-muted`,children:WC(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=JC(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)(Y,{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 `,YC(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:WC(e.contract.gtm.tagId)}),` fires with `,XC(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:WC(e.contract.googleAds.conversionActionId)}),`. Do not change the account or publish a Tag Manager version just to verify it.`]})]})]}):null]})}var rw=3e4,iw={name:``,eventName:``,conversionActionId:``,conversionId:``,conversionLabel:``,campaignIds:``,tagId:``,triggerIds:``,variableIds:``,productionHosts:``,requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},aw=`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`,ow=`text-label-14-strong text-secondary`;function sw(e,t,n,r){return n?{snapshotCount:e,snapshotState:`unavailable`,snapshotError:Ds(r)}:t?{snapshotCount:e,snapshotState:`loading`}:{snapshotCount:e}}function cw(e){return[...new Set(e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function lw(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 uw(e,t,n){let r=[`Container ${e}`,`account ${t}`];return n&&r.push(`workspace ${n}`),r.join(` · `)}function dw(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:uw(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 fw(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:cw(e.campaignIds),requireBiddableGoal:e.requireBiddableGoal,requirePrimaryAction:e.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:e.tagId.trim(),triggerIds:cw(e.triggerIds),variableIds:cw(e.variableIds)},runtime:{verificationRequired:e.verificationRequired,requireTransactionId:e.requireTransactionId,requireValue:e.requireValue,requireCurrency:e.requireCurrency,productionHosts:cw(e.productionHosts)}}}function pw(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 mw(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 hw(e,t,n){return e?`no longer accessible`:n?`access not verified`:t?`not in the current result`:`checking access`}function gw({id:e,label:t,value:n,onChange:r,children:i,disabled:a=!1}){return(0,Q.jsxs)(`label`,{htmlFor:e,className:ow,children:[t,(0,Q.jsx)(`select`,{id:e,className:aw,value:n,onChange:e=>r(e.target.value),disabled:a,children:i})]})}function _w({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 vw({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(Ds(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)(J,{ref:u,type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:a,onClick:p,children:`Keep connected`}),(0,Q.jsx)(Rr,{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)(Rr,{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 yw({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:ow,children:t});return i?(0,Q.jsxs)(`div`,{children:[m,(0,Q.jsx)(`select`,{id:e,className:aw,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:aw,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:aw,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:aw,value:c,onChange:e=>l(e.target.value)}):(0,Q.jsxs)(`select`,{id:e,required:!0,className:aw,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 bw({projectId:e,projectName:t}){let n=ji(),[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)(iw),[j,M]=(0,Z.useState)(null),N=(0,Z.useRef)(null),P=U({...Bi({client:q,path:{name:t}}),staleTime:rw}),F=U({...uo({client:q,path:{name:t}}),staleTime:rw}),I=U({...Ta({client:q,path:{name:t}}),staleTime:rw}),L=U({...ta({client:q,path:{name:t}}),staleTime:rw}),R=L.data,z=U({...Oa({client:q,path:{name:t},query:{limit:5}}),staleTime:rw}),B=U({...ao({client:q,path:{name:t},query:{limit:5}}),staleTime:rw}),ee=I.data??[],te=(j?ee.find(e=>e.id===j)??null:null)??(ee.length===1?ee[0]??null:null),ne=ee.length>1&&!te,V=U({...ya({client:q,path:{name:t,contractId:te?.id??``}}),enabled:!!te,staleTime:rw}),H=U({...Ua({client:q,path:{name:t}}),enabled:d===`google-ads`&&P.data?.connected===!0,staleTime:0}),ie=U({...Wo({client:q,path:{name:t}}),enabled:d===`gtm`&&F.data?.connected===!0,staleTime:0}),ae=U({...wo({client:q,path:{name:t,accountId:x}}),enabled:d===`gtm`&&!!x,staleTime:0}),oe=U({...no({client:q,path:{name:t,accountId:x,containerId:C}}),enabled:d===`gtm`&&!!x&&!!C,staleTime:0}),se=re(Yo({client:q})),ce=re(ea({client:q})),le=re(ha({client:q})),ue=re(ja({client:q})),de=re(Fa({client:q})),fe=re(Zi({client:q})),pe=re(Vo({client:q})),me=re(Eo({client:q})),he=re(Na({client:q}));(0,Z.useEffect)(()=>{if(d!==`google-ads`||p||!P.isSuccess)return;let e=P.data.connection?.selection;v(e?.customerId??``),b(e?.loginCustomerId??``),m(!0)},[p,P.data,P.isSuccess,d]),(0,Z.useEffect)(()=>{if(d!==`gtm`||h||!F.isSuccess)return;let e=F.data.selection;S(e?.accountId??``),w(e?.containerId??``),E(e?.workspaceId??``),g(!0)},[h,F.data,F.isSuccess,d]),(0,Z.useEffect)(()=>{j&&I.data&&(I.data.some(e=>e.id===j)||M(null))},[I.data,j]);let ge=(0,Z.useMemo)(()=>{let e=z.data?.snapshots??[],t=B.data?.snapshots??[],n=[...e.map(e=>({id:e.id,provider:`google-ads`,kind:e.kind,capturedAt:e.capturedAt})),...t.map(e=>({id:e.id,provider:`gtm`,kind:e.kind,capturedAt:e.capturedAt}))].sort((e,t)=>t.capturedAt.localeCompare(e.capturedAt)).slice(0,5),r=[],i=V.data?.googleAdsSnapshot,a=V.data?.gtmSnapshot;return i&&r.push({id:i.id,provider:`google-ads`,kind:i.kind,capturedAt:i.capturedAt}),a&&r.push({id:a.id,provider:`gtm`,kind:a.kind,capturedAt:a.capturedAt}),{contract:V.data?.assessment.contract??te,assessment:V.data?.assessment??null,contractSelectionRequired:ne,assessmentState:te?V.isError?`unavailable`:V.isLoading?`loading`:void 0:void 0,assessmentError:V.isError?Ds(V.error):null,googleAds:lw(P.data,sw(z.data?.total??0,z.isLoading,z.isError,z.error),P.isError),gtm:dw(F.data,sw(B.data?.total??0,B.isLoading,B.isError,B.error),F.isError),snapshots:n,assessmentEvidenceSnapshots:r}},[te,ne,z.data,z.error,z.isError,z.isLoading,P.data,P.isError,B.data,B.error,B.isError,B.isLoading,F.data,F.isError,V.data,V.error,V.isError,V.isLoading]),_e=(0,Z.useSyncExternalStore)(Ts,tc,tc),ve=Object.values(_e.runs).some(t=>t.projectId===e&&(t.kind===Ct[`google-ads-sync`]||t.kind===Ct[`gtm-sync`])),ye=se.isPending||ce.isPending||le.isPending||ue.isPending||de.isPending||fe.isPending||pe.isPending||me.isPending||he.isPending||ve;async function be(){await Promise.all([P.refetch(),F.refetch(),I.refetch(),z.refetch(),B.refetch(),L.refetch(),te?V.refetch():Promise.resolve()])}async function xe(e){await be();for(let t=0;t<10&&!e();t+=1)await new Promise(e=>setTimeout(e,1500)),await be()}function Se(){let e=document.activeElement;N.current=e instanceof HTMLElement?e:null}function Ce(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:Is()?`auto`:`smooth`,block:`start`}),we(document.getElementById(t)??n)}function Ee(e,t){Se(),Ce(()=>Te(e,t))}function De(){let e=N.current;N.current=null,e&&Ce(()=>{e.isConnected&&e.focus({preventScroll:!0})})}function W(){i(null),c(!1),De()}function Oe(){i(null),f(null),De()}function ke(){i(null),O(!1),De()}function Ae(){i(null),f(null),c(!0),Ee(`google-ads-connect-panel`,`google-ads-connect-title`)}function G(){i(null),v(``),b(``),m(!1),f(`google-ads`),c(!1),Ee(`google-ads-selection-panel`,`google-ads-selection-title`)}function je(){i(null),S(``),w(``),E(``),g(!1),f(`gtm`),c(!1),Ee(`gtm-selection-panel`,`gtm-selection-title`)}function Me(){i(null),O(!0),Ee(`conversion-integrity-contract-form`,`conversion-integrity-contract-form-title`)}function Ne(e,n){ks({id:e.id,projectId:e.projectId,kind:e.kind,projectLabel:t,sourceAction:n}),Ni({title:n===`google-ads-sync`?`Google Ads sync queued`:`Tag Manager sync queued`,detail:`${t} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`google-marketing-sync:${e.id}`,dedupeMode:`replace`})}async function Pe(){Ws(n),i(null);try{let e=await se.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.`),pw(e.authorizationUrl,()=>{be(),o(null),De()})}catch(e){i(Ds(e))}}async function Fe(){Ws(n),i(null);try{let e=await ce.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.`),pw(e.authorizationUrl,()=>{be(),o(null),De()})}catch(e){i(Ds(e))}}async function Ie(){if(Ws(n),!_)i(`Select a Google Ads customer before saving.`);else{i(null);try{await le.mutateAsync({path:{name:t},body:{customerId:_,...y.trim()?{loginCustomerId:y.trim()}:{}}}),f(null),De(),await xe(()=>P.data?.selectedCustomer!=null)}catch(e){i(Ds(e))}}}async function Le(){if(Ws(n),!x||!C)i(`Select a Tag Manager account and container before saving.`);else{i(null);try{await ue.mutateAsync({path:{name:t},body:{accountId:x,containerId:C,...T?{workspaceId:T}:{}}}),f(null),De(),await xe(()=>F.data?.status===`connected`)}catch(e){i(Ds(e))}}}async function Re(){Ws(n),i(null),await pe.mutateAsync({path:{name:t}}),f(null),c(!1),v(``),b(``),m(!1),o(null),await be(),Ni({title:`Google Ads disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`google-ads-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,Ce(()=>we(document.getElementById(`conversion-integrity-title`)))}async function ze(){Ws(n),i(null),await me.mutateAsync({path:{name:t}}),f(null),S(``),w(``),E(``),g(!1),o(null),await be(),Ni({title:`Tag Manager disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`gtm-disconnected:${e}`,dedupeMode:`replace`}),N.current=null,Ce(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Be(){Ws(n),i(null);try{Ne(await de.mutateAsync({path:{name:t}}),`google-ads-sync`)}catch(e){i(Ds(e))}}async function Ve(){Ws(n),i(null);try{Ne(await fe.mutateAsync({path:{name:t}}),`gtm-sync`)}catch(e){i(Ds(e))}}async function He(){Ws(n),i(null);try{let e=await Promise.allSettled([de.mutateAsync({path:{name:t}}),fe.mutateAsync({path:{name:t}})]),[n,r]=e;n.status===`fulfilled`&&Ne(n.value,`google-ads-sync`),r.status===`fulfilled`&&Ne(r.value,`gtm-sync`);let i=e.find(e=>e.status===`rejected`);if(i?.status===`rejected`)throw i.reason}catch(e){i(Ds(e))}}async function Ue(){Ws(n);let e=P.data?.connection?.selection.customerId,r=F.data?.selection;if(!e||!r?.accountId||!r.containerId)i(`Select Google Ads and Tag Manager resources before declaring a conversion.`);else{i(null);try{let n=await he.mutateAsync({path:{name:t},body:fw(k,e,{accountId:r.accountId,containerId:r.containerId})});A(iw),O(!1),De(),(await I.refetch()).data?.some(e=>e.id===n.id)&&M(n.id)}catch(e){i(Ds(e))}}}function We(e){switch(e){case`connect-google-ads`:Ae();return;case`connect-gtm`:Se(),Fe();return;case`select-google-ads`:G();return;case`select-gtm`:je();return;case`sync-google-ads`:Be();return;case`sync-gtm`:Ve();return;case`sync-static-evidence`:He();return;case`declare-contract`:Me();return;case`review-findings`: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`:be();return;case`select-contract`:Ee(`conversion-integrity-contract-select`,`conversion-integrity-contract-select`);return;case`retry-integrity`:V.refetch();return;case`waiting-for-integrity`:return}}let Ge=H.data?.customers??[],Ke=ie.data?.accounts??[],qe=ae.data?.containers??[],Je=oe.data?.workspaces??[],Ye=!!_&&!Ge.some(e=>e.customerId===_),Xe=!!x&&!Ke.some(e=>e.id===x),Ze=!!C&&!qe.some(e=>e.id===C),Qe=!!T&&!Je.some(e=>e.id===T),$e=Ye&&H.isSuccess&&H.data.truncated===!1,et=Xe&&ie.isSuccess&&ie.data.truncated===!1,tt=Ze&&ae.isSuccess&&ae.data.truncated===!1,nt=Qe&&oe.isSuccess&&oe.data.truncated===!1,rt=et||tt||nt,K=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,it=hw($e,H.data,H.isError),at=hw(et,ie.data,ie.isError),ot=hw(tt,ae.data,ae.isError),st=hw(nt,oe.data,oe.isError),ct=H.isError?Ds(H.error):null,lt=ie.isError?Ds(ie.error):ae.isError?Ds(ae.error):oe.isError?Ds(oe.error):null,ut=d===`google-ads`?ct:d===`gtm`?lt:null,dt=mw(`customer`,H.data,Ge.length),ft=mw(`account`,ie.data,Ke.length),pt=mw(`container`,ae.data,qe.length),mt=mw(`draft workspace`,oe.data,Je.length),ht=ie.isError||ae.isError||oe.isError&&!!T,gt=s||d!==null||D;function _t(){H.refetch()}function vt(){ie.isError?ie.refetch():ae.isError?ae.refetch():oe.isError&&oe.refetch()}return P.isLoading||F.isLoading||I.isLoading?(0,Q.jsxs)(`section`,{className:`page-section`,"aria-busy":`true`,"aria-labelledby":`conversion-integrity-title`,children:[(0,Q.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,Q.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,Q.jsx)(`div`,{"aria-hidden":`true`,className:`mt-5 grid gap-4 sm:grid-cols-2`,children:[0,1].map(e=>(0,Q.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text w-28`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-full`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-3/4`})]},e))}),(0,Q.jsx)(`p`,{role:`status`,className:`sr-only`,children:`Loading conversion setup…`})]}):I.isError&&!I.data?(0,Q.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,Q.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,Q.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,Q.jsxs)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:[`Could not load conversion contracts: `,Ds(I.error)]}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void I.refetch(),children:`Retry contracts`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(nw,{workspace:ge,onPrimaryAction:We,actionPending:ye,actionError:gt?null:r,contracts:ee,selectedContractId:te?.id??null,onSelectContract:e=>M(e||null),contractError:I.isError?Ds(I.error):null,onRetryContracts:()=>void I.refetch(),onRetryEvidence:()=>{Promise.all([z.refetch(),B.refetch()])},onChangeGoogleAdsSelection:G,onChangeGtmSelection:je,onAddContract:()=>We(`declare-contract`)}),a?(0,Q.jsx)(`p`,{role:`status`,className:`page-section text-copy-14 text-secondary`,children:a}):null,s?(0,Q.jsxs)(`section`,{id:`google-ads-connect-panel`,className:`page-section-divider`,"aria-labelledby":`google-ads-connect-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Ads`}),(0,Q.jsx)(`h3`,{id:`google-ads-connect-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Connect read-only access`})]})}),r?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,(0,Q.jsxs)(`form`,{className:`max-w-xl`,onSubmit:Mi(async e=>{e.preventDefault(),await Pe()}),children:[(0,Q.jsxs)(`label`,{htmlFor:`google-ads-developer-token`,className:ow,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:aw,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)(Rr,{type:`submit`,disabled:se.isPending,children:se.isPending?`Starting…`:`Continue to Google`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:W,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`})]})}),ut?(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:ut}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:_t,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)(gw,{id:`google-ads-customer`,label:`Customer account`,value:_,onChange:e=>{m(!0),v(e);let t=Ge.find(t=>t.customerId===e);b(t?.parentCustomerId??``)},disabled:H.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:H.isLoading?`Loading accessible customers…`:`Select a customer`}),Ye?(0,Q.jsxs)(`option`,{value:_,disabled:$e,children:[`Saved customer `,_,` (`,it,`)`]}):null,Ge.map(e=>(0,Q.jsx)(`option`,{value:e.customerId,children:e.descriptiveName??`Customer ${e.customerId}`},e.customerId))]}),(0,Q.jsxs)(`label`,{htmlFor:`google-ads-login-customer`,className:ow,children:[`Manager account ID (optional)`,(0,Q.jsx)(`input`,{id:`google-ads-login-customer`,className:aw,value:y,onChange:e=>{m(!0),b(e.target.value)},placeholder:`Use only when a manager context is required`})]})]}),dt?(0,Q.jsx)(`p`,{role:`status`,className:`mt-3 text-copy-14 ${H.data?.truncated?`text-caution`:`text-secondary`}`,children:dt}):null,(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,Q.jsx)(Rr,{type:`button`,disabled:le.isPending||H.isLoading||H.isError||$e||!_,onClick:Mi(Ie),children:le.isPending?`Saving…`:`Save customer selection`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:Oe,children:`Cancel`})]}),P.data?.connected?(0,Q.jsx)(vw,{providerLabel:`Google Ads`,disabled:ye,onDisconnect:Re}):null]}):null,d===`gtm`?(0,Q.jsxs)(`section`,{id:`gtm-selection-panel`,className:`page-section-divider`,"aria-labelledby":`gtm-selection-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Tag Manager`}),(0,Q.jsx)(`h3`,{id:`gtm-selection-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Select container context`})]})}),ut?(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:ut}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:vt,children:ie.isError?`Retry account list`:ae.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,K?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:K}):null,(0,Q.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-3`,children:[(0,Q.jsxs)(gw,{id:`gtm-account`,label:`Account`,value:x,onChange:e=>{g(!0),e!==x&&(w(``),E(``)),S(e)},disabled:ie.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:ie.isLoading?`Loading accounts…`:`Select an account`}),Xe?(0,Q.jsxs)(`option`,{value:x,disabled:et,children:[`Saved account `,x,` (`,at,`)`]}):null,Ke.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(gw,{id:`gtm-container`,label:`Container`,value:C,onChange:e=>{g(!0),e!==C&&E(``),w(e)},disabled:!x||ae.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:ae.isLoading?`Loading containers…`:`Select a container`}),Ze?(0,Q.jsxs)(`option`,{value:C,disabled:tt,children:[`Saved container `,C,` (`,ot,`)`]}):null,qe.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,Q.jsxs)(gw,{id:`gtm-workspace`,label:`Draft workspace (optional)`,value:T,onChange:e=>{g(!0),E(e)},disabled:!C||oe.isLoading,children:[(0,Q.jsx)(`option`,{value:``,children:oe.isLoading?`Loading workspaces…`:`No draft workspace`}),Qe?(0,Q.jsxs)(`option`,{value:T,disabled:nt,children:[`Saved draft workspace `,T,` (`,st,`)`]}):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:[ft?(0,Q.jsx)(`p`,{role:`status`,className:ie.data?.truncated?`text-caution`:`text-secondary`,children:ft}):null,pt?(0,Q.jsx)(`p`,{role:`status`,className:ae.data?.truncated?`text-caution`:`text-secondary`,children:pt}):null,mt?(0,Q.jsx)(`p`,{role:`status`,className:oe.data?.truncated?`text-caution`:`text-secondary`,children:mt}):null]}),(0,Q.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,Q.jsx)(Rr,{type:`button`,disabled:ue.isPending||ie.isLoading||ae.isLoading||oe.isLoading&&!!T||ht||rt||!x||!C,onClick:Mi(Le),children:ue.isPending?`Saving…`:`Save container selection`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:Oe,children:`Cancel`})]}),F.data?.connected?(0,Q.jsx)(vw,{providerLabel:`Tag Manager`,disabled:ye,onDisconnect:ze}):null]}):null,D?(0,Q.jsxs)(`section`,{id:`conversion-integrity-contract-form`,className:`page-section-divider`,"aria-labelledby":`conversion-integrity-contract-form-title`,children:[(0,Q.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Declared conversion`}),(0,Q.jsx)(`h3`,{id:`conversion-integrity-contract-form-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Declare the expected path`})]})}),r?(0,Q.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,(0,Q.jsxs)(`form`,{onSubmit:Mi(async e=>{e.preventDefault(),await Ue()}),children:[(0,Q.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{htmlFor:`contract-name`,className:ow,children:[`Conversion name`,(0,Q.jsx)(`input`,{id:`contract-name`,required:!0,maxLength:120,className:aw,value:k.name,onChange:e=>A(t=>({...t,name:e.target.value})),placeholder:`Booking completed`})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-event-name`,className:ow,children:[`Website event`,(0,Q.jsx)(`input`,{id:`contract-event-name`,required:!0,className:aw,value:k.eventName,onChange:e=>A(t=>({...t,eventName:e.target.value})),placeholder:`booking_complete`})]}),(0,Q.jsx)(yw,{id:`contract-conversion-action`,label:`Google Ads conversion action`,options:R?.googleAds.conversionActions??[],synced:R?.googleAds.syncedAt!=null,loading:L.isLoading,failed:L.isError,onRetry:()=>void L.refetch(),emptyHint:`Run a Google Ads sync to list conversion actions.`,value:k.conversionActionId,onChange:e=>A(t=>({...t,conversionActionId:e}))}),(0,Q.jsx)(yw,{id:`contract-gtm-tag`,label:`Tag Manager tag`,options:R?.gtm.tags??[],synced:R?.gtm.syncedAt!=null,loading:L.isLoading,failed:L.isError,onRetry:()=>void L.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:ow,children:[`Google conversion ID (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-id`,className:aw,value:k.conversionId,onChange:e=>A(t=>({...t,conversionId:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-conversion-label`,className:ow,children:[`Google conversion label (optional)`,(0,Q.jsx)(`input`,{id:`contract-conversion-label`,className:aw,value:k.conversionLabel,onChange:e=>A(t=>({...t,conversionLabel:e.target.value}))})]}),(0,Q.jsxs)(`label`,{htmlFor:`contract-trigger-ids`,className:ow,children:[`Trigger IDs`,(0,Q.jsx)(`input`,{id:`contract-trigger-ids`,className:aw,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:ow,children:[`Variable IDs`,(0,Q.jsx)(`input`,{id:`contract-variable-ids`,className:aw,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:ow,children:[`Campaign IDs`,(0,Q.jsx)(`input`,{id:`contract-campaign-ids`,className:aw,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:ow,children:[`Production hosts`,(0,Q.jsx)(`input`,{id:`contract-production-hosts`,className:aw,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)(_w,{id:`contract-primary-action`,checked:k.requirePrimaryAction,onChange:e=>A(t=>({...t,requirePrimaryAction:e})),children:`Google Ads action is primary`}),(0,Q.jsx)(_w,{id:`contract-biddable-goal`,checked:k.requireBiddableGoal,onChange:e=>A(t=>({...t,requireBiddableGoal:e})),children:`Google Ads goal is biddable`}),(0,Q.jsx)(_w,{id:`contract-runtime-verification`,checked:k.verificationRequired,onChange:e=>A(t=>({...t,verificationRequired:e})),children:`Runtime proof is required`}),(0,Q.jsx)(_w,{id:`contract-transaction-id`,checked:k.requireTransactionId,onChange:e=>A(t=>({...t,requireTransactionId:e})),children:`Transaction ID is required`}),(0,Q.jsx)(_w,{id:`contract-value`,checked:k.requireValue,onChange:e=>A(t=>({...t,requireValue:e})),children:`Conversion value is required`}),(0,Q.jsx)(_w,{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)(Rr,{type:`submit`,disabled:he.isPending,children:he.isPending?`Saving…`:`Save conversion contract`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]})]})]}):null]})}var xw=6e4,Sw=[`7d`,`14d`,`30d`],Cw=`not available`,ww=`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%.`,Tw=`No Google Ads snapshot stored yet`,Ew=`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.`,Dw=`No closed days yet`,Ow=`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.`,kw={"insufficient-history":`Period change is hidden: the stored snapshot does not cover a prior period of equal length yet.`},Aw=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),jw=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Mw=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Nw(e,t){return e===null||!Number.isFinite(e)?Cw:t===null?Mw.format(e/1e6):Vc(e,t)}function Pw(e){return e===null||!Number.isFinite(e)?Cw:$e(e)}function Fw(e,t){return e===null||!Number.isFinite(e)?`${Cw} vs prior ${t}d`:e===0?`no change vs prior ${t}d`:`${e>0?`↑`:`↓`} ${$e(Math.abs(e))} vs prior ${t}d`}function Iw(e){return e===`enabled`?`positive`:e===`paused`?`caution`:`neutral`}function Lw(e){return e===`enabled`?`Enabled`:e===`paused`?`Paused`:e===`removed`?`Removed`:`Unknown`}function Rw(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 zw({projectName:e}){let[t,n]=(0,Z.useState)(`14d`),[r,i]=(0,Z.useState)(()=>new Set([`costMicros`,`conversions`])),a=U({...qa({client:q,path:{name:e},query:{window:t}}),staleTime:xw}),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:ww})]}),o?.source?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[yi(o.startDate),` to `,yi(o.endDate),` · `,o.days,` closed `,o.days===1?`day`:`days`]}):null]}),(0,Q.jsx)(ru,{windows:Sw,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: `,Ds(a.error)]}),(0,Q.jsx)(J,{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?Dw:Tw}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e?Ow:Ew})]})]})}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:Nw(c.costMicros,m),change:d?.change.costMicros??null,direction:`none`,seriesKey:`costMicros`},{key:`conversions`,comparable:!0,label:`Conversions`,value:jw.format(c.conversions),change:d?.change.conversions??null,direction:`up-good`,seriesKey:`conversions`},{key:`cost-per-conversion`,label:`Cost / conv.`,value:g?`no conversions`:Nw(c.costPerConversionMicros,m),change:null,comparable:!1,direction:`down-good`,seriesKey:null},{key:`conversion-rate`,comparable:!0,label:`Conv. rate`,value:Pw(c.conversionRate),change:d?.change.conversionRate??null,direction:`up-good`,seriesKey:null}],v=[{key:`clicks`,label:`Clicks`,value:Aw.format(c.clicks),seriesKey:`clicks`},{key:`impressions`,label:`Impressions`,value:Aw.format(c.impressions),seriesKey:`impressions`},{key:`ctr`,label:`CTR`,value:Pw(c.ctr),seriesKey:`ctr`},{key:`cpc`,label:`CPC`,value:Nw(c.cpcMicros,m),seriesKey:null}],y={costMicros:{label:`Spend`,color:li[1],axisId:`spend`,formatValue:e=>Nw(e,m)},conversions:{label:`Conversions`,color:li[0],axisId:`conversions`,formatValue:e=>jw.format(e)},clicks:{label:`Clicks`,color:li[2],axisId:`clicks`,formatValue:e=>Aw.format(e)},impressions:{label:`Impressions`,color:li[3],axisId:`impressions`,formatValue:e=>Aw.format(e)},ctr:{label:`CTR`,color:li[4],axisId:`ctr`,formatValue:e=>Pw(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 `,Aw.format(h.queried),` of`,` `,Aw.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:kw[`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 ${Rw(e.change,e.direction)}`,children:Fw(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)(di,{data:l,xKey:`date`,series:b,xTickFormatter:fi,labelFormatter:yi}),(0,Q.jsx)(`ul`,{className:`sr-only`,children:l.map(e=>(0,Q.jsxs)(`li`,{children:[yi(e.date),`:`,` `,b.map(t=>{let n=e[t.dataKey];return`${t.label} ${n===null?Cw: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)(Y,{tone:Iw(e.status),children:Lw(e.status)})}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Aw.format(e.totals.impressions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Aw.format(e.totals.clicks)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:Nw(e.totals.costMicros,m)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:jw.format(e.totals.conversions)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Pw(e.totals.ctr)}),(0,Q.jsx)(`td`,{className:`text-right tabular-nums`,children:e.totals.costMicros>0&&e.totals.conversions===0?(0,Q.jsx)(Y,{tone:`caution`,children:`no conversions`}):(0,Q.jsx)(`span`,{className:`text-secondary`,children:Nw(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:pi(hi(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:yi(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:yi(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 Bw={proposed:{label:`New`,tone:`caution`},confirmed:{label:`Included`,tone:`positive`},excluded:{label:`Excluded`,tone:`neutral`}};function Vw(e){return e.trim().toLocaleLowerCase()}function Hw(e,t){return!t||`${e.name} ${(e.urls??[e.url]).join(` `)}`.toLocaleLowerCase().includes(t)}function Uw({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 Ww({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)(Y,{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)(J,{type:`button`,disabled:d,variant:l?`outline`:`default`,onClick:()=>u(!1),children:`Import sitemap`}),(0,Q.jsx)(J,{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)(qw,{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)(J,{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)(J,{type:`submit`,disabled:f,children:i===`reviewing`?`Reviewing sitemap…`:`Review sitemap`})]})]})}function Gw({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=Vw(r),m=t.filter(e=>Hw(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)(J,{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)(J,{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)(J,{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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:c,onClick:S,children:`Select all shown`}),(0,Q.jsx)(J,{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)(J,{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=Bw[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)(Uw,{property:t})}),(0,Q.jsx)(`td`,{className:`px-3 py-3`,children:(0,Q.jsx)(Y,{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)(J,{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)(J,{type:`button`,variant:`ghost`,disabled:c,onClick:u,children:`Add Properties`}),(0,Q.jsx)(J,{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 Kw(e){return e.activeStep===`import`?(0,Q.jsx)(Ww,{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)(Gw,{...e})}function qw({property:e,onSave:t,onCancel:n}){let r=(0,Z.useId)(),i=(0,Z.useRef)(null),a=(0,Z.useRef)(!1),[o,s]=(0,Z.useState)(e?.name??``),[c,l]=(0,Z.useState)(e?.aliases.join(`
|
|
7
|
+
`)??``),[u,d]=(0,Z.useState)(e?.identityAliases.join(`
|
|
8
|
+
`)??``),[f,p]=(0,Z.useState)(``),[m,h]=(0,Z.useState)(!1),g=`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-copy-14 text-primary focus:border-strong focus:outline-none focus:ring-2 focus:ring-mono-400`;(0,Z.useEffect)(()=>{i.current?.focus()},[]),(0,Z.useEffect)(()=>{!m&&a.current&&(a.current=!1,i.current?.focus())},[m,o]);async function _(){h(!0);try{await t({name:o.trim(),aliases:e?c.split(`
|
|
9
|
+
`).map(e=>e.trim()).filter(Boolean):[o.trim()],identityAliases:u.split(`
|
|
10
|
+
`).map(e=>e.trim()).filter(Boolean),urls:e?[...e.urls]:[f.trim()]})&&!e&&(s(``),p(``),d(``),a.current=!0)}finally{h(!1)}}return(0,Q.jsxs)(`form`,{className:`max-w-2xl space-y-4`,onSubmit:e=>{e.preventDefault(),_()},"aria-busy":m,children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,htmlFor:`${r}-name`,children:[`Property name`,(0,Q.jsx)(`input`,{ref:i,id:`${r}-name`,required:!0,value:o,disabled:m,onChange:e=>s(e.target.value),className:g})]}),e?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,htmlFor:`${r}-names`,children:[`Names that count as a mention`,(0,Q.jsx)(`textarea`,{id:`${r}-names`,value:c,disabled:m,onChange:e=>l(e.target.value),className:g,rows:3,"aria-describedby":`${r}-names-help`})]}),(0,Q.jsx)(`p`,{id:`${r}-names-help`,className:`text-copy-13 text-secondary`,children:`One name per line. Use names for this specific Property; a shared brand name also matches other Properties.`}),(0,Q.jsxs)(`details`,{children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:`Qualified names (optional)`}),(0,Q.jsxs)(`label`,{className:`block text-copy-13 text-secondary`,htmlFor:`${r}-qualified`,children:[`Longer names that distinguish this Property when a plain name is shared.`,(0,Q.jsx)(`textarea`,{id:`${r}-qualified`,value:u,disabled:m,onChange:e=>d(e.target.value),className:g,rows:3})]})]})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,htmlFor:`${r}-url`,children:[`Property page URL`,(0,Q.jsx)(`input`,{id:`${r}-url`,type:`url`,pattern:`https?://.*`,title:`Enter a full http or https page URL`,required:!0,value:f,disabled:m,onChange:e=>p(e.target.value),className:g,placeholder:`https://example.com/products/example`})]}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`The name matches mentions; the page URL matches citations. You can review both before publishing.`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(J,{type:`submit`,disabled:m||!o.trim(),children:m?`Saving…`:e?`Save Property`:`Add Property`}),(0,Q.jsx)(J,{type:`button`,variant:`ghost`,disabled:m,onClick:n,children:`Cancel`})]})]})}function Jw({properties:e,onSave:t,onEditingChange:n}){let[r,i]=(0,Z.useState)(null),[a,o]=(0,Z.useState)(20);function s(e){i(e),n?.(e!==null)}return(0,Q.jsxs)(`section`,{"aria-label":`Property matching`,className:`space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Property matching`}),(0,Q.jsx)(X,{text:`Check the names and URLs used to measure each Property. Display names alone do not change matching.`})]}),(0,Q.jsx)(`ul`,{className:`divide-y divide-subtle border-y border-default`,children:e.slice(0,a).map(e=>(0,Q.jsx)(`li`,{className:`py-3`,children:r===e.id&&t?(0,Q.jsx)(qw,{property:e,onCancel:()=>s(null),onSave:async n=>{let r=await t(e.id,n);return r&&s(null),r}}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-3`,children:[(0,Q.jsx)(`h5`,{className:`text-label-14-strong text-heading`,children:e.name}),t?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:r!==null,"aria-label":`Edit matching for ${e.name}`,onClick:()=>s(e.id),children:`Edit names`}):null]}),(0,Q.jsxs)(`dl`,{className:`grid gap-x-4 gap-y-1 text-copy-13 sm:grid-cols-[auto_minmax(0,1fr)]`,children:[(0,Q.jsx)(`dt`,{className:`text-secondary`,children:`Mention names`}),(0,Q.jsx)(`dd`,{className:`break-words text-primary`,children:e.aliases.length>0?e.aliases.join(`, `):`No names configured`}),e.identityAliases.length>0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`dt`,{className:`text-secondary`,children:`Qualified names`}),(0,Q.jsx)(`dd`,{className:`break-words text-primary`,children:e.identityAliases.join(`, `)})]}):null,(0,Q.jsx)(`dt`,{className:`text-secondary`,children:`Citation URLs`}),(0,Q.jsx)(`dd`,{className:`break-all text-primary`,children:e.urls.length>0?e.urls.join(`, `):`No citation URLs configured`})]})]})},e.id))}),e.length>a?(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>o(e=>e+20),children:`Show more Properties`}):null]})}var Yw=20,Xw=50,Zw=50,Qw=50;function $w(e){return e===`viewer`}function eT(e){return e?.status===`unavailable`}function tT(e,t,n){return n?e.includes(t)?[...e]:[...e,t]:e.filter(e=>e!==t)}function nT(e,t){let n=new Map(t.map(e=>[e.id,e.label])),r=e.map(e=>n.get(e)).filter(e=>!!e);return r.length===0?`Not applied`:r.length>3?`${r.length} Properties`:r.join(`, `)}function rT(e,t,n){if(e.kind===`none`)return[];if(e.kind===`all`)return t.map(e=>e.id);if(e.kind===`specific`)return t.filter(t=>e.propertyIds.includes(t.id)).map(e=>e.id);let r=new Set(e.groupIds),i=new Set(n.filter(e=>r.has(e.id)).flatMap(e=>e.propertyIds));return t.filter(e=>i.has(e.id)).map(e=>e.id)}function iT(e,t,n){if(e.kind===`all`)return`every Property (${n})`;if(e.kind===`specific`)return n===1?`1 Property`:`${n} Properties`;let r=e.groupIds.map(e=>t.find(t=>t.id===e)?.name).filter(e=>!!e);return r.length===0?`selected groups`:r.join(` + `)}function aT(e,t){let n=new Set(t.map(e=>e.id)),r=e.propertyIds.filter(e=>n.has(e)).length;return`${e.name} · ${r===1?`1 Property`:`${r} Properties`}`}function oT(e){return e===`matched`?`positive`:e===`duplicate`?`neutral`:e===`ambiguous`||e===`proposed`||e===`excluded`?`caution`:`negative`}function sT(e){return e===`matched`?`Matched`:e===`duplicate`?`Duplicate`:e===`ambiguous`?`Ambiguous`:e===`proposed`?`Property needs review`:e===`excluded`?`Property excluded`:e===`invalid`?`Invalid row`:`Not matched`}function cT(e){return e.status===`duplicate`&&e.duplicateOfRow?`Duplicates row ${e.duplicateOfRow}.`:e.status===`matched`?null:e.reason===`group-label-ambiguous`?`More than one group matches “${e.group}”. Rename duplicate groups, then preview again.`:e.status===`ambiguous`?`More than one Property matches this row. Add an exact URL to choose one.`:e.status===`unmatched`?`No included Property matches this row.`:e.reason===`group-key-conflict`?`The group name “${e.group}” conflicts with an existing setup identity. Rename the group, then preview again.`:e.status===`invalid`?`Check the Property, group, and optional URL fields.`:e.status===`proposed`?`Review this proposed Property before importing it.`:e.status===`excluded`?`Include this Property before importing it.`:e.reason??null}function lT(e){return e.state===`missing`||e.source===`unavailable-tracked-query`||!e.source}function uT(e){return lT(e)?`Unavailable tracked query`:e.text?.trim()||`Unavailable tracked query`}function dT({properties:e,selectedPropertyIds:t,onSelectedPropertyIdsChange:n,legend:r,showBulkActions:i=!0}){let[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)(!1),l=a.trim().toLocaleLowerCase(),u=l?e.filter(e=>e.label.toLocaleLowerCase().includes(l)):e,d=s?u:u.slice(0,Zw),f=d.length<u.length;function p(){let r=new Set([...t,...d.map(e=>e.id)]);n(e.filter(e=>r.has(e.id)).map(e=>e.id))}return(0,Q.jsxs)(`fieldset`,{children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:r}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-end justify-between gap-3`,children:[(0,Q.jsxs)(`label`,{className:`block min-w-48 flex-1`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search Properties`}),(0,Q.jsx)(`input`,{type:`search`,value:a,onChange:e=>o(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400`})]}),i?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:d.length===0,onClick:p,children:`Select all shown`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:t.length===0,onClick:()=>n([]),children:`Clear selection`})]}):null]}),u.length===0?(0,Q.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`No Properties match this search.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:[`Showing `,d.length,` of `,u.length,` Properties`]}),(0,Q.jsx)(`div`,{className:`mt-2 max-h-96 divide-y divide-default overflow-y-auto border-y border-default`,children:d.map(e=>{let r=t.includes(e.id);return(0,Q.jsxs)(`label`,{className:`flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-label-14 text-primary`,children:[(0,Q.jsxs)(`span`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(`input`,{"aria-label":`Select ${e.label}`,checked:r,type:`checkbox`,onChange:r=>n(tT(t,e.id,r.currentTarget.checked))}),(0,Q.jsx)(`span`,{children:e.label})]}),e.urlCount===void 0?null:(0,Q.jsxs)(`span`,{className:`tabular-nums text-secondary`,children:[e.urlCount,` URLs`]})]},e.id)})}),f?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 pointer-coarse:min-h-11`,onClick:()=>c(!0),children:`Show all Properties`}):null]})]})}function fT(){return(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 text-label-14 text-secondary`,children:[(0,Q.jsx)(Y,{tone:`neutral`,children:`Viewer access`}),(0,Q.jsx)(`span`,{children:`You can inspect this setup.`})]})}function pT({message:e}){return(0,Q.jsxs)(`div`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4 text-label-14 text-caution`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,Q.jsx)(Y,{tone:`caution`,children:`Unavailable`}),(0,Q.jsx)(`h4`,{className:`text-heading-14`,children:`Measurement setup unavailable`})]}),(0,Q.jsx)(`p`,{className:`mt-2 max-w-2xl text-secondary`,children:e})]})}function mT({value:e}){let[t,n]=(0,Z.useState)(0),[r,i]=(0,Z.useState)(0),[a,o]=(0,Z.useState)(null),s=e.preview,c=s?.counts.needsAttention??0,l=s?.rows.filter(e=>e.status===`matched`)??[],u=s?.rows??[],f=u.filter(e=>e.status!==`matched`),p=Math.max(1,Math.ceil(u.length/Xw)),m=Math.min(t,p-1),h=u.slice(m*Xw,(m+1)*Xw),g=Math.max(1,Math.ceil(f.length/Xw)),_=Math.min(r,g-1),v=f.slice(_*Xw,(_+1)*Xw),y=e.csv.trim().length>0&&!e.isReviewing&&!e.isApplying,b=l.length>0&&!e.isApplying,x=s!==null&&a===s.previewChecksum,S=f.length>0&&_===g-1;(0,Z.useEffect)(()=>{n(0),i(0),o(null)},[s?.previewChecksum]);async function C(t){if(t)try{e.onCsvChange(await t.text())}catch{}}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-group-import-title`,className:`border-y border-default py-4`,children:[(0,Q.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-group-import-title`,className:`text-heading-14 text-heading`,children:`Import groups from CSV`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Import group membership once instead of selecting the same Properties repeatedly.`})]}),(0,Q.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`CSV file`}),(0,Q.jsx)(`input`,{"aria-label":`Group membership CSV file`,type:`file`,accept:`.csv,text/csv`,disabled:e.isReviewing||e.isApplying,onChange:e=>{C(e.currentTarget.files?.[0])},className:`mt-1 block min-h-11 w-full text-label-14 text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-label-14-strong file:text-primary`})]}),(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Or paste CSV`}),(0,Q.jsx)(`textarea`,{"aria-label":`Group membership CSV`,rows:5,value:e.csv,disabled:e.isReviewing||e.isApplying,onChange:t=>e.onCsvChange(t.currentTarget.value),placeholder:`property,group,url
|
|
11
|
+
Harbor House,Dallas,https://example.com/harbor-house`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-copy-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:!y,onClick:()=>{e.onReview()},children:e.isReviewing?`Reviewing CSV…`:`Review CSV`}),(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Use columns named property and group. URL is optional.`})]}),e.error?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:e.error}):null,e.notice?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:e.notice}):null]}),s?(0,Q.jsxs)(`div`,{className:`mt-4 border-t border-default pt-4`,"aria-live":`polite`,children:[(0,Q.jsx)(`h5`,{className:`text-heading-14 text-heading`,children:`Review group membership`}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[s.counts.matchedRows,` matched · `,s.counts.groupsReady,` group`,s.counts.groupsReady===1?``:`s`,` ready`,c>0?` · ${c} need${c===1?`s`:``} attention`:``]}),s.groupChanges.length>0?(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Groups and memberships ready to apply`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Change`}),(0,Q.jsx)(`th`,{children:`Properties`}),(0,Q.jsx)(`th`,{children:`New memberships`})]})}),(0,Q.jsx)(`tbody`,{children:s.groupChanges.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.label}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.action===`create`?`Create group`:`Add to existing group`}),(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.targetKeys.length}),(0,Q.jsxs)(`td`,{className:`tabular-nums text-secondary`,children:[e.addedTargetKeys.length,e.unchangedTargetKeys.length>0?` · ${e.unchangedTargetKeys.length} already members`:``]})]},e.groupKey))})]})}):null,s.rows.length>0?(0,Q.jsxs)(`details`,{className:`group/csv-rows mt-3 border-y border-default py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(d,{className:`size-3.5 shrink-0 transition-transform group-open/csv-rows:rotate-90`,"aria-hidden":`true`}),`Review CSV rows (`,s.counts.dataRows,`)`]}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`CSV group membership review`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Row`}),(0,Q.jsx)(`th`,{children:`Property`}),(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Status`})]})}),(0,Q.jsx)(`tbody`,{children:h.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.dataRow}),(0,Q.jsx)(`td`,{className:`text-heading`,children:e.property}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.group}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(Y,{tone:oT(e.status),children:sT(e.status)}),cT(e)?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:cT(e)}):null]})]},e.dataRow))})]})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Page `,m+1,` of `,p,` · `,s.rows.length,` rows`]}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:m===0,onClick:()=>n(e=>Math.max(0,e-1)),children:`Previous 50 rows`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:m===p-1,onClick:()=>n(e=>Math.min(p-1,e+1)),children:`Next 50 rows`})]})]}):null,c>0?(0,Q.jsxs)(`details`,{className:`group/csv-fixes mt-3 border-y border-caution-800/30 py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(d,{className:`size-3.5 shrink-0 transition-transform group-open/csv-fixes:rotate-90`,"aria-hidden":`true`}),`Fix `,c,` row`,c===1?``:`s`,` before applying`]}),(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added.`}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`CSV rows that need attention`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Row`}),(0,Q.jsx)(`th`,{children:`Property`}),(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Issue`})]})}),(0,Q.jsx)(`tbody`,{children:v.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.dataRow}),(0,Q.jsx)(`td`,{className:`text-heading`,children:e.property}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.group}),(0,Q.jsxs)(`td`,{children:[(0,Q.jsx)(Y,{tone:oT(e.status),children:sT(e.status)}),cT(e)?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:cT(e)}):null]})]},e.dataRow))})]})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Exception page `,_+1,` of `,g]}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:_===0,onClick:()=>i(e=>Math.max(0,e-1)),children:`Previous 50 exceptions`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:_===g-1,onClick:()=>i(e=>Math.min(g-1,e+1)),children:`Review next 50 exceptions`})]}),(0,Q.jsxs)(`label`,{className:`mt-3 flex min-h-11 max-w-xl items-center gap-3 text-label-14 text-heading`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:x,disabled:e.isApplying||!S,onChange:e=>o(e.currentTarget.checked?s.previewChecksum:null),className:`size-4 rounded border-default`}),`I reviewed the exceptions and understand that `,c,` row`,c===1?``:`s`,` will be skipped.`]}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 pointer-coarse:min-h-11`,disabled:!b||!x,onClick:()=>{e.onApply(l.map(e=>e.dataRow))},children:e.isApplying?`Applying groups…`:`Apply ${l.length} matched row${l.length===1?``:`s`}`})]}):(0,Q.jsx)(J,{type:`button`,className:`mt-3 pointer-coarse:min-h-11`,disabled:!b,onClick:()=>{e.onApply(l.map(e=>e.dataRow))},children:e.isApplying?`Creating groups…`:`Create ${s.counts.groupsReady} group${s.counts.groupsReady===1?``:`s`} with ${l.length} membership${l.length===1?``:`s`}`})]}):null]})}var hT=`—`;function gT({access:e,availability:t,properties:n,queries:r,selectedQueryIds:i,isApplying:a=!1,isBusy:o=!1,canContinue:s=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:l,onClearQueryAssignments:u,onRemoveQuery:f,onCreateQueries:p,onCreateAndPairQuestions:m,isCreatingQueries:h=!1,createQueriesError:g=null,onManageProjectQueries:_,groups:v,audience:y,onAudienceChange:b,executionOptions:x=[],executionOptionId:S=``,onExecutionOptionChange:C,markets:w=[],marketAssignments:T=[],onSaveMarket:E,marketId:D=``,onMarketChange:O,marketExecutionOptionId:k=``,onMarketExecutionOptionChange:A,onRouteMarket:j,isRoutingMarket:M=!1,isPreviewingMarketRouting:N=!1,marketRoutingImpact:P=null,marketRoutingError:F=null,onRetryMarketRouting:I,marketRoutingNotice:L=null,assignmentImpact:R=null,isPreviewingAssignmentImpact:z=!1,assignmentImpactError:B=null,onRetryAssignmentImpact:ee,assignmentNotice:te=null,onReplaceAssignments:ne,isReplacingAssignments:V=!1,onBack:H,onContinue:re}){let[U,ie]=(0,Z.useState)(``),[ae,oe]=(0,Z.useState)(!1),[se,ce]=(0,Z.useState)(!1),[le,ue]=(0,Z.useState)(``),[de,fe]=(0,Z.useState)(``),[pe,me]=(0,Z.useState)(!1),[he,ge]=(0,Z.useState)(null);if(eT(t))return(0,Q.jsx)(`section`,{"aria-label":`Queries`,children:(0,Q.jsx)(pT,{message:t.message})});let _e=$w(e),ve=y,ye=b,be=rT(ve,n,v),xe=be.length,Se=xe>0&&i.length>0&&!a&&!o&&!z&&R!==null&&B===null,Ce=u??f,we=U.trim().toLocaleLowerCase(),Te=we?r.filter(e=>uT(e).toLocaleLowerCase().includes(we)):r,Ee=Te.filter(e=>(e.propertyIds?.length??0)===0),De=se?Ee:Te,W=ae?De:De.slice(0,Qw),Oe=W.filter(e=>!lT(e)),ke=[...new Set(le.split(`
|
|
12
|
+
`).map(e=>e.trim()).filter(Boolean))],Ae=[...de.matchAll(/\{([a-z][\w-]*)\}/gi)].map(e=>e[1]),G=n.filter(e=>be.includes(e.id)),je=Ae.length===0||de.trim()===``?[]:G.map(e=>({propertyId:e.id,text:Ae.reduce((t,n)=>t.replaceAll(`{${n}}`,e.label),de.trim())})),Me=[...new Set(je.map(e=>e.text))];function Ne(){let e=new Set([...i,...Oe.map(e=>e.id)]);c(r.filter(t=>e.has(t.id)).map(e=>e.id))}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-queries-title`,className:`space-y-5`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`advanced-measurement-queries-title`,children:`Queries`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose queries, then assign them to Properties.`})]})}),_e?(0,Q.jsx)(fT,{}):null,_e?null:(0,Q.jsxs)(`fieldset`,{className:`border-y border-default py-4`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Apply to`}),(0,Q.jsxs)(`div`,{className:`mt-3 grid max-w-2xl gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Properties or group`}),(0,Q.jsxs)(`select`,{"aria-label":`Apply to`,value:ve.kind===`none`?``:ve.kind===`all`?`all`:ve.kind===`specific`?`specific`:`group:${ve.groupIds[0]??``}`,onChange:e=>{let t=e.currentTarget.value;t===`all`?ye({kind:`all`}):t===`specific`?ye({kind:`specific`,propertyIds:[]}):t.startsWith(`group:`)&&ye({kind:`groups`,groupIds:[t.slice(6)]})},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,disabled:!0,children:`Choose where to apply`}),(0,Q.jsxs)(`option`,{value:`all`,children:[`Every Property (`,n.length,`)`]}),v.length>0?(0,Q.jsx)(`optgroup`,{label:`Groups`,children:v.map(e=>{let t=rT({kind:`groups`,groupIds:[e.id]},n,v).length;return(0,Q.jsx)(`option`,{value:`group:${e.id}`,disabled:t===0,children:aT(e,n)},e.id)})}):null,(0,Q.jsx)(`option`,{value:`specific`,children:`Specific Properties…`})]})]}),x.length>0&&C?(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Answer engine`}),(0,Q.jsxs)(`select`,{"aria-label":`Answer engine for these assignments`,value:S,onChange:e=>C(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Keep existing or use portfolio defaults`}),x.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}):null]}),x.length>0?(0,Q.jsx)(`p`,{className:`mt-2 max-w-2xl text-copy-14 text-secondary`,children:`The selected engine applies to these Property assignments.`}):null,ve.kind===`groups`?(0,Q.jsxs)(`div`,{className:`mt-3 max-w-2xl space-y-3`,children:[(0,Q.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:ve.groupIds.map(e=>{let t=v.find(t=>t.id===e);return t?(0,Q.jsxs)(`span`,{className:`inline-flex min-h-11 items-center gap-1 rounded-md border border-default bg-surface px-2 text-label-14 text-primary`,children:[aT(t,n),(0,Q.jsx)(`button`,{type:`button`,"aria-label":`Remove ${t.name}`,className:`-my-px -mr-2 ml-1 inline-flex min-h-11 min-w-11 items-center justify-center rounded text-secondary outline-none hover:text-heading focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>{let e=ve.groupIds.filter(e=>e!==t.id);ye(e.length>0?{kind:`groups`,groupIds:e}:{kind:`none`})},children:`×`})]},t.id):null})}),v.some(e=>!ve.groupIds.includes(e.id)&&rT({kind:`groups`,groupIds:[e.id]},n,v).length>0)?(0,Q.jsxs)(`label`,{className:`block max-w-sm`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Add another group`}),(0,Q.jsxs)(`select`,{"aria-label":`Add another group`,value:``,onChange:e=>{e.currentTarget.value&&ye({kind:`groups`,groupIds:[...ve.groupIds,e.currentTarget.value]})},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a group`}),v.filter(e=>!ve.groupIds.includes(e.id)).map(e=>{let t=rT({kind:`groups`,groupIds:[e.id]},n,v).length;return(0,Q.jsx)(`option`,{value:e.id,disabled:t===0,children:aT(e,n)},e.id)})]})]}):null,xe===0?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-caution`,children:`This group has no included Properties. Add Properties to the group, then try again.`}):null]}):null,ve.kind===`specific`?(0,Q.jsx)(`div`,{className:`mt-4`,children:(0,Q.jsx)(dT,{legend:`Specific Properties`,properties:n,selectedPropertyIds:ve.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:e=>{ye({kind:`specific`,propertyIds:e})}})}):null,ve.kind===`groups`?(0,Q.jsx)(`p`,{className:`mt-3 max-w-2xl text-copy-13 text-secondary`,children:`Assignments use the group’s current Properties. Later membership changes do not change existing assignments.`}):null]}),!_e&&(E||w.length>0)?(0,Q.jsxs)(`details`,{className:`border-b border-default py-3`,children:[(0,Q.jsxs)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:[`Markets`,w.length>0?` (${w.length})`:` (optional)`]}),E?(0,Q.jsx)(_T,{markets:w,assignments:T,groups:v,onSave:E,disabled:o,onEditingChange:me}):null,w.length===0||x.length===0||!O||!A||!j?null:(0,Q.jsxs)(`fieldset`,{className:`border-b border-default pb-4`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Market routing`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose the answer engine for one saved market. Its existing answer-engine locations stay unchanged.`}),(0,Q.jsxs)(`div`,{className:`mt-3 grid max-w-2xl gap-3 sm:grid-cols-2`,children:[(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Market`}),(0,Q.jsxs)(`select`,{"aria-label":`Market to route`,value:D,onChange:e=>O(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Choose a market`}),w.map(e=>(0,Q.jsxs)(`option`,{value:e.id,children:[e.label,` · `,e.measurementCount,` saved measurement`,e.measurementCount===1?``:`s`]},e.id))]})]}),(0,Q.jsxs)(`label`,{className:`block`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Answer engine`}),(0,Q.jsxs)(`select`,{"aria-label":`Answer engine for this market`,value:k,onChange:e=>A(e.currentTarget.value),className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none focus:border-strong focus:ring-2 focus:ring-mono-400`,children:[(0,Q.jsx)(`option`,{value:``,children:`Choose an answer engine`}),x.map(e=>(0,Q.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]})]}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:!D||!k||o||M||N||P===null||P.changedMeasurements===0||F!==null,onClick:()=>{j()},children:M?`Saving market routing…`:`Save market routing`}),L?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:L}):null]}),(0,Q.jsxs)(`div`,{className:`mt-2 min-h-5`,children:[N?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Calculating market impact…`}):null,P?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[P.changedMeasurements,` of `,P.matchedMeasurements,` saved measurement`,P.matchedMeasurements===1?``:`s`,` will change`,` · `,P.addedProviderCalls,` new provider request`,P.addedProviderCalls===1?``:`s`,` · `,P.fullRunProviderCalls,` per full run`]}):F?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:F}),I?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:I,children:`Retry impact`}):null]}):null]})]})]}):null,_e||!p?null:(0,Q.jsxs)(`details`,{open:r.length===0,className:`group/add-queries border-y border-default py-4`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(d,{className:`size-3.5 shrink-0 transition-transform group-open/add-queries:rotate-90`,"aria-hidden":`true`}),`Add queries`]}),(0,Q.jsxs)(`div`,{className:`pt-3`,children:[(0,Q.jsx)(`h4`,{className:`m-0 text-heading-14 text-heading`,children:r.length===0?`Add the queries you want to track`:`Add more queries`}),(0,Q.jsx)(`p`,{className:`mt-1 mb-2 text-copy-14 text-secondary`,children:`One per line. Add them to the project, then apply them to Properties.`}),(0,Q.jsx)(`textarea`,{"aria-label":`New queries, one per line`,className:`w-full rounded border border-strong bg-transparent px-3 py-2 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,rows:4,value:le,onChange:e=>ue(e.currentTarget.value),placeholder:`best tools for team collaboration
|
|
13
|
+
how to compare project management software`}),g?(0,Q.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:g}):null,(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:ke.length===0||h||o,onClick:()=>{Promise.resolve(p(ke)).then(()=>ue(``),()=>{})},children:h?`Adding…`:`Add ${ke.length||``} ${ke.length===1?`query`:`queries`}`.replace(` `,` `)}),_?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:_,children:`Manage project queries`}):null]}),(0,Q.jsxs)(`details`,{className:`mt-4 border-t border-default pt-4`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:`Write one query for every Property`}),(0,Q.jsxs)(`p`,{className:`mt-1 mb-2 text-copy-14 text-secondary`,children:[`Put `,(0,Q.jsx)(`code`,{className:`rounded bg-bg-elevated px-1`,children:`{property}`}),` where the Property name belongs. You get one query per selected Property.`]}),(0,Q.jsx)(`input`,{"aria-label":`Query pattern`,className:`min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:de,onChange:e=>fe(e.target.value),placeholder:`How does {property} compare with alternatives?`}),de.trim()===``?null:Ae.length===0?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-14 text-caution`,children:[`Add `,`{property}`,` to the pattern, or use the box above for a single query.`]}):G.length===0?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-caution`,children:`Select at least one Property to write queries for.`}):(0,Q.jsxs)(`div`,{className:`mt-2 material-base p-3`,children:[(0,Q.jsxs)(`p`,{className:`m-0 text-copy-14 text-secondary`,children:[Me.length,` `,Me.length===1?`query`:`queries`,`, one per selected Property:`]}),(0,Q.jsx)(`ul`,{className:`mt-1 mb-0 list-none space-y-0.5 p-0`,children:Me.slice(0,3).map(e=>(0,Q.jsx)(`li`,{className:`text-label-14 text-strong`,children:e},e))}),Me.length>3?(0,Q.jsxs)(`p`,{className:`mt-1 mb-0 text-copy-14 text-secondary`,children:[`and `,Me.length-3,` more`]}):null]}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`mt-2 pointer-coarse:min-h-11`,disabled:je.length===0||h||o||!m,onClick:()=>{m&&Promise.resolve(m(je)).then(()=>fe(``),()=>{})},children:h?`Adding…`:`Add ${je.length||``} ${je.length===1?`query`:`queries`}`.replace(` `,` `)}),je.length>0?(0,Q.jsxs)(`p`,{className:`mt-2 mb-0 text-copy-14 text-secondary`,children:[`Each query is measured on the one Property it names, so this adds`,` `,je.length,` assignment`,je.length===1?``:`s`,`.`]}):null]})]})]}),_e?null:(0,Q.jsx)(`div`,{className:`space-y-3 border-y border-default py-4`,children:r.length===0?null:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:Oe.length===0,onClick:Ne,children:`Select all shown queries`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:i.length===0,onClick:()=>c([]),children:`Clear query selection`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:!Se,onClick:()=>{l({queryIds:i,propertyIds:be,...ve.kind===`groups`?{groupIds:ve.groupIds}:{}})},children:a?`Assigning queries…`:`Assign ${i.length||``} ${i.length===1?`query`:`queries`}${ve.kind===`none`?``:` to ${iT(ve,v,xe)}`}`.replace(` `,` `)}),(0,Q.jsxs)(`div`,{className:`min-h-[2.75rem]`,children:[z?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Calculating assignment impact…`}):null,R?(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` → `,R.assignmentCount,` Property assignment`,R.assignmentCount===1?``:`s`,` · `,R.addedAssignments,` new, `,R.alreadyPresentAssignments,` already assigned`,` · `,R.fullRunProviderCalls,` provider request`,R.fullRunProviderCalls===1?``:`s`,` per full run`,` · `,R.addedProviderCalls,` new`,ve.kind===`groups`?` · ${R.resolvedPropertyCount} unique ${R.resolvedPropertyCount===1?`Property`:`Properties`}${R.overlapCount>0?`, ${R.overlapCount} in overlapping groups`:``}`:``,`. Existing assignments stay in place.`]}):B?(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:B}),ee?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:ee,children:`Retry impact`}):null,H?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:H,children:`Back to Groups`}):null]}):ve.kind===`none`?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose where to apply first.`}):(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` × `,xe,` Properties = `,i.length*xe,` assignments`]})]}),te?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:te}):null]})}),r.length>0?(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search queries`}),(0,Q.jsx)(`input`,{type:`search`,value:U,onChange:e=>{ie(e.currentTarget.value),oe(!1)},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-label-14 text-primary outline-none placeholder-mono-400 focus:border-strong focus:ring-2 focus:ring-mono-400`,placeholder:`Query text`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsxs)(`p`,{className:`m-0 text-copy-14 text-secondary`,children:[`Showing `,W.length,` of `,De.length,` queries,`,` `,Te.length-Ee.length,` of `,Te.length,` applied`]}),_e||Ee.length===0?null:(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>{ce(e=>!e),oe(!1)},children:se?`Show all queries`:`Show the ${Ee.length} not applied`})]})]}):null,W.length>0?(0,Q.jsx)(`div`,{className:`relative overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[_e?null:(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Select query`})}),(0,Q.jsx)(`th`,{children:`Query`}),(0,Q.jsx)(`th`,{children:`Properties`}),_e?null:(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Clear query assignments`})})]})}),(0,Q.jsx)(`tbody`,{children:W.map(e=>{let t=lT(e),r=uT(e),a=i.includes(e.id),s=(e.propertyIds?.length??0)>0;return(0,Q.jsxs)(`tr`,{children:[_e?null:t?(0,Q.jsx)(`td`,{"aria-hidden":`true`}):(0,Q.jsx)(`td`,{className:`p-0`,children:(0,Q.jsx)(`label`,{className:`flex min-h-11 min-w-11 cursor-pointer items-center justify-center`,children:(0,Q.jsx)(`input`,{"aria-label":`Select query ${r}`,checked:a,type:`checkbox`,onChange:t=>c(tT(i,e.id,t.currentTarget.checked)),className:`size-6 accent-accent`})})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:r})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:nT(e.propertyIds??[],n)}),_e?null:(0,Q.jsx)(`td`,{className:`text-right`,children:s?(0,Q.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-1`,children:[ne?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o||V,onClick:()=>ge({queryId:e.id,propertyIds:[...e.propertyIds??[]]}),"aria-label":`Replace query assignments for ${r}`,children:`Replace assignments`}):null,(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:()=>{Ce(e.id)},"aria-label":`Clear query assignments for ${r}`,children:`Clear assignments`})]}):null})]},e.id)})})]})}):r.length>0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No queries match this search.`}):null,_e||!he?null:(()=>{let e=r.find(e=>e.id===he.queryId),t=e?uT(e):`this query`,i=he.propertyIds.filter(e=>n.some(t=>t.id===e));return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-replace-assignments-title`,className:`border-y border-default py-4`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-replace-assignments-title`,className:`text-heading-14 text-heading`,children:`Replace assigned Properties`}),(0,Q.jsxs)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:[`This replaces every Property assigned to “`,t,`”.`]}),(0,Q.jsx)(`div`,{className:`mt-3`,children:(0,Q.jsx)(dT,{legend:`Properties for this query`,properties:n,selectedPropertyIds:i,onSelectedPropertyIdsChange:e=>ge(t=>t&&{...t,propertyIds:[...e]})})}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:V||o,onClick:()=>ge(null),children:`Keep current assignments`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:i.length===0||V||o||!ne,onClick:()=>{ne&&Promise.resolve(ne({queryId:he.queryId,propertyIds:i}))},children:V?`Replacing assignments…`:`Replace with ${i.length} ${i.length===1?`Property`:`Properties`}`})]})]})})(),W.length<De.length?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:()=>oe(!0),children:`Show all queries`}):null,_e?null:(0,Q.jsxs)(Q.Fragment,{children:[s?null:(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`Apply at least one query to a Property before continuing.`}),pe?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Save or cancel the market before continuing.`}):null,(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${H?`justify-between`:`justify-end`}`,children:[H?(0,Q.jsx)(J,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:H,children:`Back`}):null,(0,Q.jsx)(J,{type:`button`,variant:Se?`outline`:`default`,className:`pointer-coarse:min-h-11`,disabled:!s||o||pe,onClick:re,children:`Continue`})]})]})]})}function _T({markets:e,assignments:t,groups:n,onSave:r,disabled:i,onEditingChange:a}){let[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(``),[u,d]=(0,Z.useState)(!1),f=(0,Z.useRef)(null),p=(0,Z.useRef)(null),m=(0,Z.useRef)(!1),h=e.find(e=>e.id===o?.id),g=n.find(e=>e.id===h?.groupId),_=t.filter(e=>!h?.groupId||e.groupIds.includes(h.groupId)).filter(e=>`${e.property} ${e.query} ${e.context} ${e.queryClass}`.toLocaleLowerCase().includes(c.trim().toLocaleLowerCase())),v=o?.assignmentIds??[];(0,Z.useEffect)(()=>{a(o!==null)},[o,a]),(0,Z.useEffect)(()=>{o!==null&&!m.current&&f.current?.focus(),o===null&&m.current&&p.current?.focus(),m.current=o!==null},[o]);async function y(){if(o){d(!0);try{await r(o)&&s(null)}finally{d(!1)}}}return(0,Q.jsxs)(`div`,{className:`space-y-4 pb-5`,children:[(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`A market reports on the specific Property, query, engine, and location assignments you select.`}),e.length>0?(0,Q.jsx)(`ul`,{className:`divide-y divide-subtle`,children:e.map(e=>(0,Q.jsxs)(`li`,{className:`flex items-center justify-between gap-3 py-2`,children:[(0,Q.jsxs)(`span`,{className:`text-label-14 text-primary`,children:[e.label,` `,(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[`· `,e.measurementCount,` assignments`]})]}),e.assignmentIds?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,disabled:i||o!==null,"aria-label":`Edit ${e.label} market`,onClick:()=>{s({id:e.id,name:e.label,assignmentIds:e.assignmentIds}),l(``)},children:`Edit`}):null]},e.id))}):null,t.length===0?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Publish your initial setup, then return here to choose its saved assignments for a market.`}):o?(0,Q.jsxs)(`form`,{className:`space-y-3`,onSubmit:e=>{e.preventDefault(),y()},children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl text-label-14-strong text-heading`,children:[`Market name`,(0,Q.jsx)(`input`,{ref:f,required:!0,value:o.name,disabled:i||u,onChange:e=>s({...o,name:e.target.value}),className:`mt-1 block min-h-11 w-full rounded border border-default bg-surface px-3 text-label-14 text-primary`})]}),g?(0,Q.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[`Linked group: `,g.name]}):null,(0,Q.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Find assignments`,(0,Q.jsx)(`input`,{type:`search`,value:c,onChange:e=>l(e.target.value),className:`mt-1 block min-h-11 w-full rounded border border-default bg-surface px-3 text-label-14 text-primary`})]}),(0,Q.jsxs)(`fieldset`,{disabled:i||u,children:[(0,Q.jsxs)(`legend`,{className:`text-copy-13 text-secondary`,children:[v.length,` assignments selected`]}),(0,Q.jsxs)(`div`,{className:`mt-2 max-h-80 overflow-y-auto divide-y divide-subtle border-y border-default`,children:[_.map(e=>(0,Q.jsxs)(`label`,{className:`flex min-h-11 cursor-pointer items-start gap-3 py-3 text-label-14 text-primary`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,checked:v.includes(e.id),onChange:t=>s({...o,assignmentIds:tT(v,e.id,t.target.checked)}),className:`mt-1 size-4 shrink-0 accent-accent`}),(0,Q.jsxs)(`span`,{children:[(0,Q.jsxs)(`span`,{className:`block text-label-14-strong`,children:[e.property,` · `,e.query]}),(0,Q.jsxs)(`span`,{className:`text-copy-13 text-secondary`,children:[e.context,` · `,e.queryClass]})]})]},e.id)),_.length===0?(0,Q.jsx)(`p`,{className:`py-3 text-copy-13 text-secondary`,children:`No matching assignments.`}):null]})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,Q.jsx)(J,{type:`submit`,disabled:i||u||!o.name.trim()||v.length===0,children:u?`Saving market…`:`Save market`}),(0,Q.jsx)(J,{type:`button`,variant:`ghost`,disabled:u,onClick:()=>s(null),children:`Cancel`})]})]}):(0,Q.jsx)(J,{ref:p,type:`button`,size:`sm`,variant:`outline`,disabled:i,onClick:()=>{s({name:``,assignmentIds:[]}),l(``)},children:`Add market`})]})}function vT({access:e,availability:t,properties:n,groups:r,groupDraft:i,isSaving:a=!1,onGroupDraftChange:o,onSaveGroup:s,onEditGroup:c,onRemoveGroup:l,onClearGroupDraft:u,membershipImport:f,onBack:p,onContinue:m}){if(eT(t))return(0,Q.jsx)(`section`,{"aria-label":`Groups`,children:(0,Q.jsx)(pT,{message:t.message})});let h=$w(e),g=i.name.trim().length>0&&i.propertyIds.length>0&&!a,_=n.filter(e=>i.propertyIds.includes(e.id)).length,v=i.name.trim().length>0||i.propertyIds.length>0||i.competitorDomains.trim().length>0,y=!h&&(c!==void 0||l!==void 0);function b(){u?u():o({name:``,propertyIds:[],competitorDomains:``})}return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-groups-title`,className:`space-y-5`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h3`,{id:`advanced-measurement-groups-title`,children:`Groups`}),(0,Q.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Use groups to organize Properties, apply queries in bulk, and compare competitors.`})]})}),h?(0,Q.jsx)(fT,{}):null,h?null:(0,Q.jsxs)(`div`,{className:`space-y-4 border-y border-default py-4`,children:[(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Group name`}),(0,Q.jsx)(`input`,{"aria-label":`Group name`,className:`mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:i.name,onChange:e=>o({...i,name:e.currentTarget.value}),placeholder:`e.g. Core products`})]}),(0,Q.jsxs)(`details`,{open:n.length<=10,className:`group/group-properties`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(d,{className:`size-3.5 shrink-0 transition-transform group-open/group-properties:rotate-90`,"aria-hidden":`true`}),_,` of `,n.length,` Properties selected`]}),(0,Q.jsx)(`div`,{className:`pt-3`,children:(0,Q.jsx)(dT,{legend:`Properties in this group`,properties:n,selectedPropertyIds:i.propertyIds,onSelectedPropertyIdsChange:e=>o({...i,propertyIds:e})})})]}),(0,Q.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Competitor domains (optional)`}),(0,Q.jsx)(`input`,{"aria-label":`Competitor domains`,className:`mt-1 min-h-11 w-full rounded border border-strong bg-transparent px-3 py-2 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,value:i.competitorDomains,onChange:e=>o({...i,competitorDomains:e.currentTarget.value}),placeholder:`one.example, two.example`})]}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:!g,onClick:()=>{s(i)},children:a?`Saving group…`:`Save group`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:!v,onClick:b,children:`Clear form`})]}),v?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`Save this group or clear the form before continuing.`}):null]}),r.length>0?(0,Q.jsx)(`div`,{className:`overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Group`}),(0,Q.jsx)(`th`,{children:`Properties`}),(0,Q.jsx)(`th`,{children:`Competitors`}),y?(0,Q.jsx)(`th`,{children:`Actions`}):null]})}),(0,Q.jsx)(`tbody`,{children:r.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.name}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:nT(e.propertyIds,n)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:e.competitors.length>0?e.competitors.join(`, `):`None`}),y?(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsxs)(`div`,{className:`flex justify-end gap-1`,children:[c?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`Edit ${e.name}`,onClick:()=>c(e),children:`Edit`}):null,l?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`Remove ${e.name}`,onClick:()=>{l(e.id)},children:`Remove`}):null]})}):null]},e.id))})]})}):null,h||!f?null:(0,Q.jsxs)(`details`,{className:`border-t border-default pt-3`,children:[(0,Q.jsx)(`summary`,{className:`min-h-11 cursor-pointer text-label-14-strong text-heading`,children:`Import groups from CSV`}),(0,Q.jsx)(mT,{value:f})]}),h?null:(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${p?`justify-between`:`justify-end`}`,children:[p?(0,Q.jsx)(J,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:p,children:`Back`}):null,(0,Q.jsx)(J,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:v,onClick:m,children:r.length===0&&!v?`Continue without groups`:`Continue`})]})]})}function yT({access:e,availability:t,counts:n,flaggedExceptions:r,properties:i,onSaveProperty:a,sitemapReview:o,onBack:s,onReviewChanges:c,isReviewing:l=!1,canReviewChanges:u=!0,reviewedChanges:f,reviewChangesError:p,canPublish:m,sweepActive:h=!1,isPublishing:g=!1,onPublish:_}){let[v,y]=(0,Z.useState)(Yw),[b,x]=(0,Z.useState)(Yw),[S,C]=(0,Z.useState)(Yw),[w,T]=(0,Z.useState)(!1);if(eT(t))return(0,Q.jsx)(`section`,{"aria-label":`Review and publish`,children:(0,Q.jsx)(pT,{message:t.message})});let E=$w(e),D=o?.items??[],O=o?.coverageItems??[],k=D.slice(0,v),A=O.slice(0,b),j=r.slice(0,S),M=c!==void 0,N=f!=null;return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-review-title`,className:`space-y-5`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h3`,{id:`advanced-measurement-review-title`,children:`Review & publish`})})}),E?(0,Q.jsx)(fT,{}):null,i&&i.length>0?(0,Q.jsx)(Jw,{properties:i,onSave:E?void 0:a,onEditingChange:T}):null,o?(0,Q.jsx)(`section`,{"aria-labelledby":`advanced-measurement-sitemap-review-title`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4`,children:(0,Q.jsxs)(`div`,{className:`max-w-2xl space-y-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-sitemap-review-title`,className:`text-heading-14 text-heading`,children:`Sitemap changes need review`}),o.exceptionCount>0?(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[o.exceptionCount,` sitemap `,o.exceptionCount===1?`entry needs`:`entries need`,` review.`]}):null,o.coverageReviewCount>0?(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[o.coverageReviewCount,` `,o.coverageReviewCount===1?`Property has`:`Properties have`,` URL coverage changes.`]}):null]}),o.exceptionCount>0?(0,Q.jsxs)(`details`,{className:`group/sitemap-urls border-y border-caution-800/30 py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(d,{className:`size-3.5 shrink-0 transition-transform group-open/sitemap-urls:rotate-90`,"aria-hidden":`true`}),`URLs not added to Properties (`,o.exceptionCount,`)`]}),D.length>0?(0,Q.jsx)(`ul`,{className:`mt-3 space-y-3 text-label-14`,children:k.map(e=>(0,Q.jsxs)(`li`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-primary`,children:e.url}),(0,Q.jsx)(`p`,{className:`mt-1 text-secondary`,children:e.reason})]},`${e.url}-${e.reason}`))}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Review the affected sitemap URLs before confirming.`}),(0,Q.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,k.length,` of `,D.length]}),k.length<D.length?(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>y(e=>e+Xw),children:`Show next 50 URLs`}):null]})]}):null,E?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`An editor must finish this review before publishing.`}):(0,Q.jsxs)(Q.Fragment,{children:[o.coverageReviewCount>0?(0,Q.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,Q.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`For changed Property URLs`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`This choice applies to all `,o.coverageReviewCount,` changed `,o.coverageReviewCount===1?`Property`:`Properties`,`.`]}),(0,Q.jsxs)(`details`,{className:`group/url-changes border-y border-caution-800/30 py-3`,children:[(0,Q.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer list-none items-center gap-1.5 text-label-14-strong text-heading [&::-webkit-details-marker]:hidden`,children:[(0,Q.jsx)(d,{className:`size-3.5 shrink-0 transition-transform group-open/url-changes:rotate-90`,"aria-hidden":`true`}),`Review Property URL changes (`,o.coverageReviewCount,`)`]}),A.length>0?(0,Q.jsxs)(`div`,{className:`mt-3 space-y-4`,children:[A.map(e=>(0,Q.jsxs)(`section`,{"aria-label":`${e.property} URL changes`,children:[(0,Q.jsx)(`h5`,{className:`text-heading-14 text-primary`,children:e.property}),(0,Q.jsxs)(`div`,{className:`mt-2 grid gap-3 text-label-14 md:grid-cols-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Saved URLs`}),(0,Q.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.savedUrls.map(e=>(0,Q.jsx)(`li`,{className:`break-all text-secondary`,children:e},e))})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Current sitemap URLs`}),e.currentSitemapUrls.length>0?(0,Q.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.currentSitemapUrls.map(e=>(0,Q.jsx)(`li`,{className:`break-all text-secondary`,children:e},e))}):(0,Q.jsx)(`p`,{className:`mt-1 text-secondary`,children:`No matching URL was found.`})]})]})]},e.property)),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,A.length,` of `,O.length]}),A.length<O.length?(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>x(e=>e+Xw),children:`Show next 50 URL changes`}):null]})]}):(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Review the affected Properties before confirming.`})]}),(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14 text-primary`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`advanced-measurement-coverage-resolution`,checked:o.coverageResolution===`keep-existing`,onChange:()=>o.onCoverageResolutionChange(`keep-existing`)}),`Keep existing Property URLs`]}),(0,Q.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14 text-primary`,children:[(0,Q.jsx)(`input`,{type:`radio`,name:`advanced-measurement-coverage-resolution`,checked:o.coverageResolution===`replace-with-imported`,onChange:()=>o.onCoverageResolutionChange(`replace-with-imported`)}),`Use current sitemap URLs`]})]}):null,(0,Q.jsx)(J,{type:`button`,className:`pointer-coarse:min-h-11`,onClick:()=>{o.onResolve()},children:`Confirm sitemap changes`})]})]})}):null,(0,Q.jsx)(`div`,{className:`overflow-x-auto border-y border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[720px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Properties`}),(0,Q.jsx)(`th`,{children:`Queries`}),(0,Q.jsx)(`th`,{children:`Groups`}),(0,Q.jsx)(`th`,{children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[`Assignments`,n.assignments!==void 0&&n.assignments>n.queries?(0,Q.jsx)(X,{text:`An assignment pairs one query with one Property. Applying a query to a group creates one assignment per Property. ${n.queries} ${n.queries===1?`query produces`:`queries produce`} ${n.assignments} assignments here.`}):null]})}),(0,Q.jsx)(`th`,{children:`Provider requests / run`})]})}),(0,Q.jsx)(`tbody`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.properties}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.queries}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.groups}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.assignments??`—`}),(0,Q.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.providerCalls??hT})]})})]})}),n.providerCalls===void 0?(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Review changes to see how many provider requests one run will make.`}):null,f?(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-reviewed-changes-title`,className:`border-y border-default py-4`,"aria-live":`polite`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-reviewed-changes-title`,className:`text-heading-14 text-heading`,children:f.title}),f.items.length>0?(0,Q.jsx)(`ul`,{className:`mt-3 list-disc space-y-2 pl-5 text-label-14 text-secondary`,children:f.items.map((e,t)=>(0,Q.jsx)(`li`,{children:e},`${e}-${t}`))}):null]}):null,r.length>0?(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-flagged-exceptions-title`,className:`space-y-3`,children:[(0,Q.jsx)(`h4`,{id:`advanced-measurement-flagged-exceptions-title`,className:`text-heading-14 text-heading`,children:`Flagged exceptions`}),r.length===0?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No flagged exceptions.`}):(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[(0,Q.jsx)(`div`,{className:`divide-y divide-default border-y border-default`,children:j.map(e=>(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3 py-3`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.title}),e.detail?(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:e.detail}):null]}),(0,Q.jsx)(Y,{tone:e.tone??`caution`,children:`Needs attention`})]},e.id))}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,j.length,` of `,r.length]}),j.length<r.length?(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>C(e=>e+Xw),children:`Show next 50 exceptions`}):null]})]})]}):null,E?null:(0,Q.jsxs)(Q.Fragment,{children:[M&&p?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:p}):null,h?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`A check is queued or running. Publish after it finishes.`}):null,w?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Save or cancel the Property edit before reviewing or publishing.`}):null,(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${s?`justify-between`:`justify-end`}`,children:[s?(0,Q.jsx)(J,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:s,children:`Back`}):null,c!==void 0&&!N?(0,Q.jsx)(J,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:w||l||!u,onClick:()=>{c()},children:l?`Reviewing changes…`:`Review changes`}):(0,Q.jsx)(J,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:w||!m||g,onClick:()=>{_()},children:g?`Publishing setup…`:`Publish setup`})]})]})]})}var bT=[{id:`import`,label:`Import`},{id:`properties`,label:`Properties`},{id:`groups`,label:`Groups`},{id:`queries`,label:`Queries`},{id:`review`,label:`Review and publish`}];function xT({currentStep:e,hasDraft:t,canEdit:n,onDiscard:r,onStepChange:i,children:a}){let o=(0,Z.useRef)(null),s=(0,Z.useRef)(null),c=(0,Z.useRef)(null),l=(0,Z.useRef)(null),u=(0,Z.useRef)(!1),[d,f]=(0,Z.useState)(!1);return(0,Z.useEffect)(()=>{t||f(!1)},[t]),(0,Z.useEffect)(()=>{let e=u.current;u.current=d,d?c.current?.focus():e&&l.current?.focus()},[d]),(0,Z.useEffect)(()=>{let t=o.current;if(o.current=e,t===null||t===e)return;let n=s.current?.querySelector(`h1, h2, h3, [role="heading"]`);n&&(n.tabIndex=-1,n.focus())},[e]),(0,Q.jsxs)(`div`,{className:`space-y-6`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between`,children:[(0,Q.jsx)(`div`,{className:`min-w-0 w-full sm:flex-1`,children:(0,Q.jsx)(`h2`,{children:`Advanced measurement setup`})}),t?(0,Q.jsxs)(`div`,{className:`flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end`,children:[(0,Q.jsx)(Y,{tone:`neutral`,children:`Draft`}),n&&r?d?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":`Confirm discard`,children:[(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Discard all unpublished changes?`}),(0,Q.jsx)(J,{ref:c,type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>f(!1),children:`Keep editing`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:r,children:`Discard unpublished changes`})]}):(0,Q.jsx)(J,{ref:l,type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>f(!0),children:`Discard changes`}):null]}):null]}),(0,Q.jsx)(`div`,{role:`group`,"aria-label":`Advanced measurement setup progress`,className:`overflow-x-auto border-b border-default`,children:(0,Q.jsx)(`ol`,{className:`flex min-w-max gap-6`,children:bT.map(t=>(0,Q.jsx)(`li`,{children:i?(0,Q.jsx)(`button`,{type:`button`,"aria-current":e===t.id?`step`:void 0,onClick:()=>i(t.id),className:`block min-h-11 border-b-2 bg-transparent px-1 py-3 text-left text-button-14 transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${e===t.id?`border-strong text-heading`:`border-transparent text-secondary hover:text-heading`}`,children:t.label}):(0,Q.jsx)(`span`,{"aria-current":e===t.id?`step`:void 0,className:`block min-h-11 border-b-2 px-1 py-3 text-label-14-strong ${e===t.id?`border-strong text-heading`:`border-transparent text-secondary`}`,children:t.label})},t.id))})}),(0,Q.jsx)(`div`,{ref:s,children:a})]})}function ST(e){let t=e.canEdit?`editor`:`viewer`;return e.currentStep===`import`||e.currentStep===`properties`?(0,Q.jsx)(Kw,{...e.importProperties,activeStep:e.currentStep,canEdit:e.canEdit}):e.currentStep===`queries`?(0,Q.jsx)(gT,{...e.queries,access:t,onManageProjectQueries:e.onManageProjectQueries}):e.currentStep===`groups`?(0,Q.jsx)(vT,{...e.groups,access:t}):`review`in e?(0,Q.jsx)(yT,{...e.review,access:t}):null}function CT(e){return(0,Q.jsx)(xT,{currentStep:e.currentStep,hasDraft:e.hasDraft,canEdit:e.canEdit,onDiscard:e.onDiscard,onStepChange:e.onStepChange,children:ST(e)})}var wT={sitemapUrl:``,examplePropertyUrl:``,preferredHost:``,propertyPathPattern:``,additionalHost:``,additionalPathPattern:``,excludedPaths:``},TT={name:``,propertyIds:[],competitorDomains:``},ET=50,DT=[],OT={};function kT(e){let t=e.trim();if(!t)return null;try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLocaleLowerCase()}catch{return null}}function AT(e){let t=e.trim();if(!t)throw Error(`Add a sitemap URL.`);let n;try{n=new URL(t.includes(`://`)?t:`https://${t}`)}catch{throw Error(`Sitemap URL must be a valid web address.`)}return(n.pathname===``||n.pathname===`/`)&&(n.pathname=`/sitemap.xml`),n.toString()}function jT(e){let t=e.propertyPathPattern.trim();if(t){let e=(t.startsWith(`/`)?t:`/${t}`).split(`/`).slice(1);if(e.filter(e=>e===`*`||e===`{slug}`).length!==1||e.some(e=>e.includes(`*`)&&e!==`*`))throw Error(`Property URL pattern must contain exactly one * or {slug} segment.`);return`/${e.map(e=>e===`*`?`{slug}`:e).join(`/`)}`}let n=e.examplePropertyUrl.trim();if(!n)throw Error(`Add one example Property page so Canonry can identify the matching URLs.`);try{let e=new URL(n).pathname.split(`/`).filter(Boolean);if(e.length===0)throw Error();return e[e.length-1]=`{slug}`,`/${e.join(`/`)}`}catch{throw Error(`Example Property page must be a valid web address.`)}}function MT(e){let t=[],n=new Set;for(let r of e.split(/[\n,]+/)){let e=r.trim().replace(/\/+$/,``);if(!e)continue;let i=e.split(`/`).filter(Boolean).at(-1)??e,a=i.startsWith(`*`),o=i.endsWith(`*`),s=i.slice(+!!a,o?-1:void 0).trim();if(!s)throw Error(`Ignored URL patterns must include text besides *.`);let c=a&&o?`contains`:a?`suffix`:o?`prefix`:`exact`,l=`${c}:${s}`;n.has(l)||(n.add(l),t.push({kind:c,value:s}))}return t}function NT(e){let t=AT(e.sitemapUrl),n=e.examplePropertyUrl.trim()?kT(e.examplePropertyUrl):null,r=kT(e.preferredHost)??n??kT(t);if(!r)throw Error(`Add a valid sitemap or Property page URL.`);let i=kT(e.additionalHost),a=e.additionalHost.trim().length>0;if(a!==e.additionalPathPattern.trim().length>0||a&&!i)throw Error(`Add both an additional domain and its Property URL pattern.`);let o=MT(e.excludedPaths);return{sitemapUrl:t,rule:{primary:{host:r,pathTemplate:jT(e)},...i?{aliases:[{host:i,pathTemplate:jT({...e,examplePropertyUrl:``,propertyPathPattern:e.additionalPathPattern})}]}:{},...o.length>0?{excludedSlugPatterns:o}:{}}}}function PT(e){return!e||e.authoring.targets.length===0?`import`:e.authoring.targets.some(e=>e.status===`proposed`)?`properties`:e.authoring.assignments.length===0?`groups`:e.baseActiveRevision===null?`review`:`properties`}function FT(e,t){return!e||e.authoring.targets.length===0?`import`:!e.authoring.targets.some(e=>e.status!==`excluded`)||e.authoring.targets.some(e=>e.status===`proposed`)?`properties`:e.authoring.assignments.length===0&&t===`review`?`groups`:t}function IT(e){return[...new Set([...e.discoveredUrl?[e.discoveredUrl]:[],...e.urlMatchers])]}function LT(e){return e===`included`?`confirmed`:e===`excluded`?`excluded`:`proposed`}function RT(e){return e?.authoring.targets.filter(e=>e.status===`included`).map(e=>e.stableKey)??[]}function zT(e,t){return`${t}-${e.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,`-`).replace(/^-+|-+$/g,``)||`item`}`.slice(0,128)}function BT(e){return kT(e)}function VT(e,t){if(t[0]!==`targets`)return;let n=t[1];if(typeof n==`number`)return e?.targets[n];if(typeof n==`string`)return e?.targets.find(e=>e.stableKey===n)}function HT(e,t){if(t[0]!==`groups`)return;let n=t[1];if(typeof n==`number`)return e?.groups[n];if(typeof n==`string`)return e?.groups.find(e=>e.stableKey===n)}function UT(e,t){return t[0]===`assignments`&&typeof t[1]==`number`?e?.assignments[t[1]]:void 0}function WT(e,t){return e?.targets.find(e=>e.stableKey===t)?.label??`a Property`}function GT(e,t){let n=VT(e.authoring,t.path);if(!n)return;let r=t.path[2],i=t.path[3];if(r===`urlMatchers`&&typeof i==`number`){let e=n.urlMatchers[i];return e?`${n.label} — ${e}`:n.label}if(r===`aliases`&&typeof i==`number`){let e=n.aliases[i];return e?`${n.label} — ${e}`:n.label}return n.label}function KT(e,t){let n=HT(e.authoring,t.path);if(!n)return;let r=t.path[2],i=t.path[3];if(r===`competitors`&&typeof i==`number`){let e=n.competitors.at(i)?.domain;return e?`${n.label} — ${e}`:n.label}if(r===`targetKeys`&&typeof i==`number`){let t=WT(e.authoring,n.targetKeys[i]);return`${n.label} — ${t}`}return n.label}function qT(e,t){let n=UT(e.authoring,t.path);if(!n)return;let r=e.queries.find(e=>e.id===n.queryId)?.query??`an unavailable query`;return`${WT(e.authoring,n.targetKey)} — ${r}`}function JT(e,t){return t.path[0]===`identities`?`Project domain`:GT(e,t)??KT(e,t)??qT(e,t)}function YT(e,t,n){let r=UT(e.authoring,t.path);if(!r)return;let i={...e.authoring?.defaultContext,...r.contextOverride},a=t.path.at(-1);if(n===`models`&&typeof a==`string`)return i.models?.[a];if(n===`locations`&&typeof a==`number`)return i.locations?.[a]}function XT(e,t){let n=JT(t,e);switch(e.ruleId){case`invalid-project-identity`:return{title:`Fix the project domain`,detail:`The project domain is not valid. Update it in project settings, then review again.`,tone:`negative`,affected:n};case`target-limit-exceeded`:return{title:`Reduce Properties`,detail:`This setup exceeds the Properties publishing limit. Remove some Properties, then review again.`,tone:`negative`};case`duplicate-target-key`:return{title:`Resolve duplicate Properties`,detail:`Two Properties use the same setup identifier. Rename or recreate one, then review again.`,tone:`negative`,affected:n};case`no-included-targets`:return{title:`Include a Property`,detail:`Include at least one Property before publishing.`,tone:`negative`};case`target-url-matcher-invalid`:return{title:`Fix a Property URL`,detail:`Use a valid web address, site-wide address, or URL pattern for this Property.`,tone:`negative`,affected:n};case`target-url-matcher-unowned`:return{title:`Use a project domain`,detail:`This Property URL must use the project domain or one of its subdomains.`,tone:`negative`,affected:n};case`target-url-matcher-ambiguous`:return{title:`Separate Property URL coverage`,detail:`This URL is assigned to more than one Property at the same specificity. Update one of the URLs.`,tone:`negative`,affected:n};case`target-alias-ambiguous`:return{title:`Use distinct Property names`,detail:`This name or alias matches another Property. Make each Property name and alias distinct.`,tone:`negative`,affected:n};case`execution-context-no-provider`:return{title:`Choose a provider`,detail:`Choose at least one provider before publishing.`,tone:`negative`,affected:n};case`invalid-provider-model`:return{title:`Fix provider settings`,detail:`Choose the provider that runs this model, or remove the model setting.`,tone:`negative`,affected:[n,YT(t,e,`models`)].filter(Boolean).join(` — `)||void 0};case`invalid-location`:return{title:`Fix a location`,detail:`Choose a location configured for this project, or remove it from the query.`,tone:`negative`,affected:[n,YT(t,e,`locations`)].filter(Boolean).join(` — `)||void 0};case`target-without-aliases`:return{title:`Add Property aliases`,detail:`Add a name or alias to measure mentions.`,tone:`caution`,affected:n};case`duplicate-group-key`:return{title:`Resolve duplicate groups`,detail:`Two groups use the same setup identifier. Rename one group, then review again.`,tone:`negative`,affected:n};case`group-unknown-target`:return{title:`Fix group Properties`,detail:`This group contains a Property that is no longer in setup. Remove it or add the Property back.`,tone:`negative`,affected:n};case`group-excluded-target`:return{title:`Include or remove a grouped Property`,detail:`This group contains an excluded Property. Include it or remove it from the group.`,tone:`negative`,affected:n};case`competitor-invalid-domain`:return{title:`Fix a competitor domain`,detail:`Enter a valid competitor domain.`,tone:`negative`,affected:n};case`competitor-matches-project`:return{title:`Remove a project domain`,detail:`A competitor cannot use the project domain.`,tone:`negative`,affected:n};case`competitor-duplicate`:return{title:`Remove a duplicate competitor`,detail:`List each competitor domain only once in a group.`,tone:`negative`,affected:n};case`duplicate-assignment`:return{title:`Remove a duplicate query`,detail:`Assign each query to a Property only once.`,tone:`negative`,affected:n};case`assignment-unknown-target`:return{title:`Fix a query assignment`,detail:`This query is assigned to a Property that is no longer in setup. Remove the assignment or add the Property back.`,tone:`negative`,affected:n};case`assignment-excluded-target`:return{title:`Include or unassign a Property`,detail:`This query is assigned to an excluded Property. Include it or remove the assignment.`,tone:`negative`,affected:n};case`assignment-unknown-query`:return{title:`Remove an unavailable query`,detail:`This assignment refers to a tracked query that is no longer available. Remove it or add the query back to the project.`,tone:`negative`,affected:n};case`assignment-unclassified`:return{title:`Classify a query`,detail:`Choose Branded or Non-brand for this query before publishing.`,tone:`negative`,affected:n};case`query-limit-exceeded`:return{title:`Reduce queries`,detail:`This setup exceeds the distinct-query publishing limit. Remove some query assignments, then review again.`,tone:`negative`};case`target-without-assignments`:return{title:`Assign queries`,detail:`Assign at least one query to measure a Property.`,tone:`caution`,affected:n};case`invalid-compiled-plan`:return{title:`Fix setup details`,detail:`A setup value could not be validated. Review the affected item, then review again.`,tone:`negative`,affected:n};case`compiled-plan-too-large`:return{title:`Reduce setup size`,detail:`This setup is too large to publish. Remove Properties, queries, or groups, then review again.`,tone:`negative`};case`active-revision-schema-v1`:return{title:`Historical results will be kept`,detail:`Existing results remain visible after you publish this setup.`,tone:`neutral`}}return{title:e.severity===`fail`?`An unexpected setup issue blocks publishing`:`An unexpected setup issue needs review`,detail:e.severity===`fail`?`Review the affected item, make a correction, and review again. If it remains blocked, contact support.`:`Review the affected item before publishing. If it remains, contact support.`,tone:e.severity===`fail`?`negative`:`caution`,affected:n}}function ZT(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function QT(e){let t=[...new Set(e)];return t.length===0?``:t.length===1?` Affected: ${t[0]}.`:t.length<=3?` Affected: ${t.join(`, `)}.`:` Affected: ${t.slice(0,3).join(`, `)}, and ${t.length-3} more.`}function $T(e,t,n,r){return`${(()=>{switch(e){case`execution-context-no-provider`:return`${t} ${ZT(n,`query assignment`)} need${n===1?`s`:``} a provider.`;case`target-without-aliases`:return`${t} ${ZT(n,`Property`,`Properties`)} need${n===1?`s`:``} aliases.`;case`target-without-assignments`:return`${t} ${ZT(n,`Property`,`Properties`)} need${n===1?`s`:``} queries.`;default:return n>1?`${t} ${ZT(n,`item`)} need review.`:t}})()}${QT(r)}`}function eE(e,t){let n=new Map;for(let r of e){let e=XT(r,t),i=[r.ruleId,r.severity,e.title,e.detail].join(`\0`),a=n.get(i)??{ruleId:r.ruleId,severity:r.severity,meaning:e,paths:new Set,affected:new Set};a.paths.add(JSON.stringify(r.path)),e.affected&&a.affected.add(e.affected),n.set(i,a)}return[...n.values()].map((e,t)=>({id:`${e.ruleId}-${e.severity}-${t}`,title:e.meaning.title,detail:$T(e.ruleId,e.meaning.detail,e.paths.size,e.affected),tone:e.meaning.tone}))}function tE(e){if(!e)return;let t=e.discoveredUrl??e.urlMatchers[0];return t?`${e.label} — ${t}`:e.label}function nE(e,t,n){let r=VT(n,e.path),i=HT(n,e.path),a=e.path[2]===`rebind`&&typeof e.path[3]==`string`?e.path[3]:void 0,o=a?n?.targets.find(e=>e.stableKey===a):void 0,s=r?.label??i?.label,c=QT(s?[s]:[]),l={id:`${e.code}-${t}`,tone:`caution`};switch(e.code){case`merge-targets-noop`:return{...l,title:`Choose another Property to merge`,detail:`Select at least one other Property before merging.${c}`};case`excluded-target-has-assignments`:return{...l,title:`Review excluded Property queries`,detail:`An excluded Property still has assigned queries. Include it or remove those queries before publishing.${c}`};case`group-unknown-target`:return{...l,title:`Fix group Properties`,detail:`This group includes a Property that is not in setup. Remove it or add the Property first.${c}`};case`measurement.discovery.proposed_new_target`:{let e=tE(r)??`the proposed Property`;return{...l,title:`Review a new Property`,detail:`Review ${e}. It did not match an existing Property.`}}case`measurement.discovery.proposed_rebind`:{let e=tE(r)??`the proposed Property`,t=o?.label??`an existing Property`;return{...l,title:`Review a moved Property`,detail:`Review ${e}. It may be the same Property as ${t}.`}}case`measurement.discovery.rebind_ambiguous`:{let e=tE(r)??`the proposed Property`,t=o?.label??`an existing Property`;return{...l,title:`Choose an existing Property`,detail:`Review ${e}. It may match ${t}; choose the correct Property.`}}default:return{...l,title:`Unexpected setup warning`,detail:`Review the latest setup change before publishing. If this warning remains, contact support.`}}}function rE(e,t=!1){let n=[],r=e.targets.added.length+e.targets.removed.length+e.targets.changed.length,i=e.groups.added.length+e.groups.removed.length+e.groups.changed.length,a=e.assignments.added+e.assignments.removed+e.assignments.reclassified;return r>0&&n.push(`${r} Property ${r===1?`change`:`changes`}`),a>0&&n.push(`${a} query assignment ${a===1?`change`:`changes`}`),i>0&&n.push(`${i} group ${i===1?`change`:`changes`}`),t&&n.unshift(`Existing results remain visible after you publish this setup.`),{title:t?`Historical results will be kept`:e.activeRevision===null?`New setup ready`:`Changes ready`,items:n.length>0?n:[`No changes from the published setup.`]}}function iE(e){return[...new Set(e)]}function aE(e){return iE(e).sort()}function oE(e,t,n,r){return e.kind===`groups`?{groupKeys:aE(e.groupIds),queryIds:aE(n),...r?{contextOverride:r}:{}}:{targetKeys:aE(e.kind===`all`?t:e.kind===`specific`?e.propertyIds:[]),queryIds:aE(n),...r?{contextOverride:r}:{}}}function sE(e,t){return t===void 0?e:JSON.stringify([e,t])}function cE(e){return{assignmentCount:e.assignments.requested,addedAssignments:e.assignments.added,alreadyPresentAssignments:e.assignments.alreadyPresent,resolvedPropertyCount:e.resolvedTargetKeys.length,overlapCount:e.overlapCount,addedProviderCalls:e.execution.addedProviderCalls,fullRunProviderCalls:e.execution.fullRunProviderCalls}}function lE(e){return e.kind===`exact`?e.url??``:e.kind===`prefix`?`https://${e.host??``}${e.pathPrefix===`/`?``:e.pathPrefix??``}/*`:e.host??``}function uE(e){let t=e.plan;if(t.schemaVersion===2)return{defaultContext:{providers:[],locations:[]},targets:t.targets.map(e=>({stableKey:e.stableKey,label:e.label,status:`included`,aliases:[...e.aliases],urlMatchers:e.urlMatchers.map(lE).filter(Boolean),source:e.discoveryIdentity?`sitemap`:`manual`,...e.discoveryIdentity?{discoveryIdentity:e.discoveryIdentity}:{}})),assignments:t.assignments.map(e=>({targetKey:e.targetKey,queryId:e.queryId,queryClass:e.queryClass,classificationSource:`operator`})),groups:t.groups.map(e=>({stableKey:e.stableKey,label:e.label,targetKeys:[...e.targetKeys],competitors:e.competitors.map(e=>({...e,aliases:[...e.aliases]}))}))};let n=t.targetQuerySelections.flatMap(e=>e.queryIds.map(t=>({targetKey:e.targetKey,queryId:t,queryClass:`unclassified`,classificationSource:`rule`})));return{defaultContext:{providers:[],locations:[]},targets:t.targets.map(e=>({stableKey:e.stableKey,label:e.label,status:`included`,aliases:[...e.aliases],urlMatchers:e.urls.map(lE).filter(Boolean),source:`manual`})),assignments:n,groups:t.groups.map(e=>({stableKey:e.stableKey,label:e.label,targetKeys:[...e.targetKeys],competitors:(e.competitors??[]).map(e=>({stableKey:zT(e,`competitor`),label:e,domain:e,aliases:[]}))}))}}function dE({projectName:e,projectDomain:t,queries:n,isQueryLoading:r,isQueryError:i,onRetryQueries:a,publishedPlan:o,canEdit:s=!0,sweepActive:c=!1,executionProviders:l=DT,executionProviderModels:u=OT,onCreateQueries:d,onManageProjectQueries:f,onPublished:p,service:m=kc}){let[h,g]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(null),[y,b]=(0,Z.useState)(`import`),[x,S]=(0,Z.useState)(!0),[C,w]=(0,Z.useState)(null),[T,E]=(0,Z.useState)(null),[D,O]=(0,Z.useState)([]),[k,A]=(0,Z.useState)(()=>({...wT,sitemapUrl:t&&Ce(t)?`https://${Ce(t)}/sitemap.xml`:``})),[j,M]=(0,Z.useState)(`idle`),[N,P]=(0,Z.useState)(``),[F,I]=(0,Z.useState)(ET),[L,R]=(0,Z.useState)([]),[z,B]=(0,Z.useState)([]),[ee,te]=(0,Z.useState)({kind:`none`}),[ne,V]=(0,Z.useState)(``),[H,re]=(0,Z.useState)(``),[U,ie]=(0,Z.useState)(``),[ae,oe]=(0,Z.useState)(null),[se,ce]=(0,Z.useState)(null),[le,ue]=(0,Z.useState)(!1),[de,fe]=(0,Z.useState)(null),[pe,me]=(0,Z.useState)(0),[he,ge]=(0,Z.useState)(null),[_e,ve]=(0,Z.useState)(null),[ye,be]=(0,Z.useState)(null),[xe,Se]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(null),[Ee,De]=(0,Z.useState)(0),[W,Oe]=(0,Z.useState)(null),[ke,Ae]=(0,Z.useState)({...TT}),[G,je]=(0,Z.useState)(null),[Me,Ne]=(0,Z.useState)(``),[Pe,Fe]=(0,Z.useState)(null),[Ie,Le]=(0,Z.useState)(!1),[Re,ze]=(0,Z.useState)(!1),[Be,Ve]=(0,Z.useState)(null),[He,Ue]=(0,Z.useState)(null),[We,Ge]=(0,Z.useState)(null),[Ke,Je]=(0,Z.useState)(null),[Ye,Ze]=(0,Z.useState)(null),Qe=(0,Z.useRef)(0),$e=(0,Z.useRef)(0),et=(0,Z.useRef)(0),tt=_?.draft??null,nt=_?.etag??null,rt=(0,Z.useMemo)(()=>!s&&o?{baseActiveRevision:o.revision,authoring:uE(o)}:null,[s,o]),K=tt??rt;async function it(t){let n=++Qe.current;S(!0),w(null);try{let[r,i]=await Promise.all([m.loadSetup(e),m.loadDraft(e)]);if(!i.draft&&t&&s&&(await m.createDraft(e,r.activeRevision),[r,i]=await Promise.all([m.loadSetup(e),m.loadDraft(e)])),n!==Qe.current)return;g(r),v(i),b(PT(i.draft));let a=RT(i.draft);R(a)}catch(e){if(n!==Qe.current)return;w(wc(e,`Could not load advanced measurement setup.`))}finally{n===Qe.current&&S(!1)}}(0,Z.useEffect)(()=>(it(!0),()=>{Qe.current+=1}),[e,s,m]),(0,Z.useEffect)(()=>{!x&&!tt&&rt&&b(`properties`)},[tt,x,rt]);async function at(){let t=await m.loadDraft(e);return v(t),t}async function ot(t){Ze(null);try{let[n,r]=await Promise.all([m.loadSetup(e),m.loadDraft(e)]);g(n),v(r);let i=RT(r.draft);R(i),b(e=>FT(r.draft,e)),E(t)}catch(e){E(wc(e,t))}}async function st(e,t,n,r={}){let{preserveBusyAction:i=!1}=r;if(!s||!nt||We&&!i)return null;i||Ge(e),E(null),Ze(null);try{let e=await t(nt),n=await at();return O((e.warnings??[]).map((e,t)=>nE(e,t,n.draft?.authoring))),n}catch(e){return Oc(e)?await ot(`This setup changed in another session. The latest draft is loaded; review your changes again.`):E(wc(e,n)),null}finally{i||Ge(null)}}let ct=(0,Z.useMemo)(()=>(K?.authoring.targets??[]).map(e=>{let t=IT(e);return{id:e.stableKey,name:e.label,url:t[0]??`No URL`,urls:t,state:LT(e.status)}}),[K]),lt=(0,Z.useMemo)(()=>K?.authoring.targets.filter(e=>e.status===`included`)??[],[K]),ut=(0,Z.useMemo)(()=>lt.map(e=>({id:e.stableKey,label:e.label,urlCount:IT(e).length})),[lt]),dt=K?.authoring.assignments.length??0,ft=(0,Z.useMemo)(()=>{if(!K)return[];let e=new Set(n.map(e=>e.id)),t=n.map(e=>({id:e.id,text:e.query,source:`saved-project-queries`,propertyIds:iE(K.authoring.assignments.filter(t=>t.queryId===e.id).map(e=>e.targetKey))})),r=iE(K.authoring.assignments.map(e=>e.queryId).filter(t=>!e.has(t))).map(e=>({id:e,source:`unavailable-tracked-query`,state:`missing`,propertyIds:iE(K.authoring.assignments.filter(t=>t.queryId===e).map(e=>e.targetKey))}));return[...t,...r]},[n,K]),pt=(0,Z.useMemo)(()=>(K?.authoring.groups??[]).map(e=>({id:e.stableKey,name:e.label,propertyIds:e.targetKeys,competitors:e.competitors.map(e=>e.domain)})),[K]),mt=(0,Z.useMemo)(()=>(K?.authoring.reportingScopes??[]).map(e=>({id:e.stableKey,label:e.label,measurementCount:e.usageEdges.length,assignmentIds:e.usageEdges.map(Ut),groupId:e.groupKey})),[K]),ht=(0,Z.useMemo)(()=>(K?.authoring.assignments??[]).flatMap(e=>{let t=lt.find(t=>t.stableKey===e.targetKey);return t?(e.executionContexts??[]).flatMap(r=>{if(!r.executionNodeKey)return[];let i={executionNodeKey:r.executionNodeKey,targetKey:e.targetKey,queryId:e.queryId};return[{id:Ut(i),edge:i,property:t.label,query:n.find(t=>t.id===e.queryId)?.query??`Unavailable query`,context:`${r.providers.map(e=>`${fr(e)}${r.models[e]&&r.models[e]!==Xe(e)?` · ${mr(r.models[e])}`:``}`).join(`, `)} · ${r.location?.label??`No location`}`,queryClass:e.queryClass===`branded`?`Branded`:e.queryClass===`non-brand`?`Non-brand`:`Unknown class`,groupIds:(K?.authoring.groups??[]).filter(t=>t.targetKeys.includes(e.targetKey)).map(e=>e.stableKey)}]}):[]}),[lt,n,K]),gt=(0,Z.useMemo)(()=>{let e=new Map,t=(t,n={})=>{for(let r of t){if(!qe(r))continue;let t=mn(r)?void 0:n[r],i=sE(r,t);e.has(i)||e.set(i,{id:i,provider:r,label:t?`${fr(r)} · ${mr(t)}`:fr(r),...t?{model:t}:{}})}};t(l,u);let n=K?.authoring.defaultContext;n&&t(n.providers,n.models);for(let e of K?.authoring.assignments??[]){e.contextOverride&&t(e.contextOverride.providers??n?.providers??[],e.contextOverride.models??n?.models);for(let n of e.executionContexts??[])t(n.providers,n.models)}return[...e.values()]},[u,l,K]),_t=(0,Z.useMemo)(()=>{if(!ne)return;let e=gt.find(e=>e.id===ne);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[ne,gt]),vt=(0,Z.useMemo)(()=>{if(!U)return;let e=gt.find(e=>e.id===U);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[gt,U]),yt=(0,Z.useMemo)(()=>H&&vt?{marketKeys:[H],contextOverride:vt}:null,[vt,H]),bt=yt?JSON.stringify(yt):``,xt=(0,Z.useMemo)(()=>!ae||se!==bt||ae.draftEtag!==nt?null:{matchedMeasurements:ae.matchedEdges,changedMeasurements:ae.changedEdges,addedProviderCalls:ae.execution.addedProviderCalls,fullRunProviderCalls:ae.execution.fullRunProviderCalls},[nt,ae,se,bt]);(0,Z.useEffect)(()=>{ne&&!gt.some(e=>e.id===ne)&&V(``)},[ne,gt]),(0,Z.useEffect)(()=>{U&&!gt.some(e=>e.id===U)&&ie(``)},[gt,U]),(0,Z.useEffect)(()=>{H&&!mt.some(e=>e.id===H)&&re(``)},[H,mt]);let St=(0,Z.useMemo)(()=>{if(z.length===0)return null;let e=oE(ee,ut.map(e=>e.id),z,_t);return(e.groupKeys?.length??e.targetKeys?.length??0)>0?e:null},[_t,ee,ut,z]),Ct=St?JSON.stringify(St):``;(0,Z.useEffect)(()=>{let t=St,n=++$e.current;if(!s||!tt||!nt||!t){ve(null),be(null),Te(null),Se(!1);return}ve(null),be(null),Te(null),Se(!0);let r=window.setTimeout(()=>{m.previewAssignments(e,t).then(e=>{n===$e.current&&(e.draftEtag===nt?(ve(e),be(Ct)):(ve(null),be(null),Te(`The setup changed while calculating assignment impact. Refresh the draft and try again.`)))}).catch(e=>{n===$e.current&&(ve(null),be(null),Te(Ec(e)))}).finally(()=>{n===$e.current&&Se(!1)})},250);return()=>{window.clearTimeout(r),$e.current+=1}},[St,Ct,Ee,s,tt,nt,e,m]),(0,Z.useEffect)(()=>{let t=yt,n=++et.current;if(!s||!tt||!nt||!t){oe(null),ce(null),fe(null),ue(!1);return}oe(null),ce(null),fe(null),ue(!0);let r=window.setTimeout(()=>{m.previewMarketRouting(e,t).then(e=>{n===et.current&&(e.draftEtag===nt?(oe(e),ce(bt)):fe(`The setup changed while calculating market impact. Refresh the draft and try again.`))}).catch(e=>{n===et.current&&fe(wc(e,`Could not calculate market routing impact.`))}).finally(()=>{n===et.current&&ue(!1)})},250);return()=>{window.clearTimeout(r),et.current+=1}},[s,tt,nt,yt,pe,bt,e,m]);let wt=(0,Z.useMemo)(()=>[...dt===0?[{id:`no-query-assignments`,title:`Assign at least one query`,detail:`Apply a tracked query to at least one Property before publishing.`,tone:`negative`}]:[],...K?.authoring.assignments.some(e=>e.queryClass===`unclassified`)&&!(rt&&o?.plan.schemaVersion===1)?[{id:`unclassified-query-assignments`,title:`Remove an unavailable query`,detail:`One or more saved assignments no longer have a tracked query. Clear them before publishing.`,tone:`negative`}]:[],...D],[dt,rt,o,D,K]),Tt=r?{status:`unavailable`,message:`Tracked queries are loading.`}:i?{status:`unavailable`,message:`Tracked queries could not be loaded. Retry before assigning Properties.`}:{status:`available`};async function Et(t){let n;try{n=NT(t)}catch(e){E(wc(e,`Check the sitemap details and try again.`));return}A(t),M(`reviewing`);let r=await st(`import`,t=>m.importSitemap(e,t,n),`Could not review this sitemap.`);if(r?.draft){let e=r.draft.authoring.targets.filter(e=>e.status===`included`).map(e=>e.stableKey);R(e),P(``),I(ET),b(`properties`),M(`idle`)}else M(`error`)}async function Dt(t){let n=t.urls[0];if(!n)return E(`Enter the page URL for this Property.`),!1;let r=zT(n,`property`);if(tt?.authoring.targets.some(e=>e.stableKey===r))return E(`This Property page is already in the draft. Select it in Properties.`),!1;let i=await st(`property`,n=>m.upsertTarget(e,n,{stableKey:r,label:t.name,status:`included`,source:`manual`,aliases:t.aliases,urlMatchers:t.urls}),`Could not add this Property.`);return i?.draft?(R(RT(i.draft)),!0):!1}async function Ot(t,n){let r=tt?.authoring.targets.find(e=>e.stableKey===t);if(!r)return!1;let{identityAliases:i,...a}=r;return await st(`property-names`,t=>m.upsertTarget(e,t,{...a,label:n.name,aliases:n.aliases,...n.identityAliases.length>0?{identityAliases:n.identityAliases}:{}}),`Could not save this Property’s names.`)!==null}async function kt(t){let n=tt?.authoring.reportingScopes?.find(e=>e.stableKey===t.id);if(t.id&&!n)return E(`This market is no longer in the draft. Cancel the edit and review the latest setup.`),!1;let r=n?.stableKey??zT(t.name,`market`);if(!n&&tt?.authoring.reportingScopes?.some(e=>e.stableKey===r))return E(`A market with this name already exists. Edit that market or choose another name.`),!1;let i=t.assignmentIds.map(e=>ht.find(t=>t.id===e));return i.some(e=>!e)?(E(`A selected assignment changed. Reopen the market and review its assignments.`),!1):await st(`market`,a=>m.upsertMarket(e,a,{stableKey:r,label:t.name.trim(),kind:`market`,...n?.groupKey?{groupKey:n.groupKey}:{},usageEdges:i.map(e=>e.edge)}),`Could not save this market.`)!==null}async function At(e){if(!d||e.length===0||We)return[];Ge(`create-queries`),Je(null);try{return await d(e)}catch(e){throw Je(Ds(e)),e}finally{Ge(null)}}async function jt(t){if(!tt||!nt||We)return;let n=new Set(t),r=tt.authoring.targets.filter(e=>e.status===`proposed`&&e.discoveryIdentity).map(e=>({discoveryIdentity:e.discoveryIdentity,action:n.has(e.stableKey)?`create`:`ignore`})),i=r.length>0||tt.authoring.targets.some(e=>e.status!==`proposed`&&e.status===`included`!==n.has(e.stableKey));Ge(`properties`),E(null),Ze(null);try{if(!i){R([...n]),te({kind:`none`}),b(`groups`);return}await m.applySitemapSelection(e,nt,r,[...n]);let t=RT((await at()).draft);R(t),te({kind:`none`}),b(`groups`)}catch(e){Oc(e)?await ot(`This setup changed in another session. The latest Properties are loaded.`):E(wc(e,`Could not save the selected Properties.`))}finally{Ge(null)}}async function Mt(t){let n=t.groupIds&&t.groupIds.length>0?{groupKeys:aE(t.groupIds),queryIds:aE(t.queryIds),..._t?{contextOverride:_t}:{}}:{targetKeys:aE(t.propertyIds),queryIds:aE(t.queryIds),..._t?{contextOverride:_t}:{}};!_e||ye!==JSON.stringify(n)||!nt||_e.draftEtag!==nt?E(`Review the latest assignment impact before assigning queries.`):await st(`assignments`,t=>m.applyAssignments(e,t,n),`Could not apply these queries.`)&&(B([]),Oe(`${_e.assignments.added} new assignment${_e.assignments.added===1?``:`s`} added. Existing assignments were kept.`))}async function Nt(t){t.propertyIds.length!==0&&await st(`replace-assignments`,n=>m.replaceAssignments(e,n,{targetKeys:iE(t.propertyIds),queryIds:[t.queryId],..._t?{contextOverride:_t}:{}}),`Could not replace this query assignment.`)&&(B(e=>e.filter(e=>e!==t.queryId)),Oe(`Query assignments replaced.`))}async function Pt(){if(!yt||!ae||se!==JSON.stringify(yt)||!nt||ae.draftEtag!==nt){E(`Review the latest market routing impact before saving.`);return}let t=mt.find(e=>e.id===H);await st(`route-markets`,t=>m.routeMarkets(e,t,yt),`Could not save this market routing.`)&&ge(`${t?.label??`Market`} routing saved. Existing locations were preserved.`)}async function Ft(t,n=!1){if(t.length!==0&&!await st(`paired-assignments`,n=>_t?m.applyPairedAssignments(e,n,[...t],_t):m.applyPairedAssignments(e,n,[...t]),`Could not assign these queries.`,{preserveBusyAction:n}))throw Error(`Could not assign these queries.`)}async function It(e){if(s&&d&&e.length!==0&&!We){Ge(`create-and-pair-questions`),Je(null);try{let t;try{t=await d(iE(e.map(e=>e.text)))}catch(e){throw Je(Ds(e)),e}let n=new Map(t.map(e=>[e.query,e.id])),r=e.map(e=>({targetKey:e.propertyId,queryId:n.get(e.text)})).filter(e=>e.queryId!==void 0);if(r.length!==e.length){let e=Error(`The created queries could not be matched to their Properties.`);throw Je(`The queries were added, but could not be paired with every Property. Try again to pair them.`),e}try{await Ft(r,!0)}catch(e){throw Je(`The queries were added, but could not be assigned to their Properties. Try again to pair them.`),e}}finally{Ge(null)}}}async function Lt(t){if(!tt)return;let n=iE(tt.authoring.assignments.filter(e=>e.queryId===t).map(e=>e.targetKey));n.length!==0&&await st(`remove-${t}`,r=>m.removeAssignment(e,r,n,t),`Could not clear this query assignment.`)&&B(e=>e.filter(e=>e!==t))}async function Rt(t){if(!tt||!nt||We)return;let n=t.name.trim();if(!n)return;let r=G??zT(n,`group`),i=tt.authoring.groups.find(e=>e.stableKey===r);if(i&&G===null){E(`A group named "${i.label}" already exists. Edit it or choose a different name.`);return}let a=t.competitorDomains.split(/[\s,]+/).map(e=>e.trim()).filter(Boolean),o=a.find(e=>BT(e)===null);if(o){E(`"${o}" is not a valid competitor domain.`);return}let s=iE(a.map(e=>BT(e)));Ge(`group`),E(null),Ze(null);try{let a=await m.upsertGroup(e,nt,{stableKey:r,label:n,targetKeys:iE(t.propertyIds),competitors:s.map(e=>i?.competitors.find(t=>t.domain===e)??{stableKey:zT(e,`competitor`),label:e,domain:e,aliases:[]})}),o=await at();O(a.warnings.map((e,t)=>nE(e,t,o.draft?.authoring))),Ae({...TT}),je(null)}catch(e){Oc(e)?await ot(`This setup changed in another session. The latest groups are loaded.`):E(wc(e,`Could not save this group.`))}finally{Ge(null)}}function zt(e){let t=tt?.authoring.groups.find(t=>t.stableKey===e);t&&(je(e),Ae({name:t.label,propertyIds:[...t.targetKeys],competitorDomains:t.competitors.map(e=>e.domain).join(`, `)}))}async function Bt(t){await st(`remove-group`,n=>m.removeGroup(e,n,t),`Could not remove this group.`)&&(te(e=>e.kind===`groups`&&e.groupIds.includes(t)?{kind:`none`}:e),G===t&&(je(null),Ae({...TT})))}function Vt(e){Ne(e),Fe(null),Ve(null),Ue(null)}async function Ht(){if(s&&Me.trim()&&!Ie&&!Re){Le(!0),Ve(null),Ue(null);try{Fe(await m.previewGroupMembership(e,{csv:Me}))}catch(e){Fe(null),Ve(wc(e,`Could not review this CSV.`))}finally{Le(!1)}}}async function Wt(t){if(s&&nt&&Pe&&t.length!==0&&!We){if(Pe.draftEtag!==nt)Ve(`The setup changed while this CSV was open. Review the latest CSV before applying it.`);else{ze(!0),Ge(`group-import`),Ve(null),Ue(null),Ze(null);try{let n=await m.applyGroupMembership(e,nt,{csv:Me,sourceChecksum:Pe.sourceChecksum,previewChecksum:Pe.previewChecksum,acceptedRows:iE(t.map(String)).map(Number)}),r=await at();O(n.warnings.map((e,t)=>nE(e,t,r.draft?.authoring))),Ne(``),Fe(null),Ue(`${n.addedMemberships} membership${n.addedMemberships===1?``:`s`} added${n.unchangedMemberships>0?`; ${n.unchangedMemberships} already present`:``}.`)}catch(e){Oc(e)?(await ot(`This setup changed in another session. The latest draft is loaded; review the CSV again.`),Ve(`The setup changed while this CSV was open. Review the latest CSV before applying it.`)):Ve(wc(e,`Could not apply this CSV.`))}finally{Ge(null),ze(!1)}}}}async function Gt(){if(tt&&nt&&!We&&dt!==0){Ge(`review`),E(null),Ze(null);try{let[t,r]=await Promise.all([m.compilePreview(e),m.diffPreview(e)]),i=[...t.checks,...r.checks],a=i.some(e=>e.ruleId===`active-revision-schema-v1`);if(O(eE(i.filter(e=>e.ruleId!==`active-revision-schema-v1`),{authoring:K?.authoring,queries:n})),!t.ok||!r.ok)return;if(r.diff.activeRevision!==tt.baseActiveRevision){await ot(`The published setup changed while you were reviewing. The latest draft is loaded; review it again.`);return}if(t.compiledChecksum!==r.compiledChecksum){E(`The setup changed while it was being reviewed. Review the latest changes again.`);return}Ze({etag:nt,baseActiveRevision:tt.baseActiveRevision,compiledChecksum:t.compiledChecksum,changes:rE(r.diff,a),providerCalls:t.plan.executionNodes.reduce((e,t)=>e+t.expectedSnapshots,0)})}catch(e){E(wc(e,`Could not review this setup.`))}finally{Ge(null)}}}async function Kt(){if(tt&&nt&&Ye&&!We){if(nt!==Ye.etag||tt.baseActiveRevision!==Ye.baseActiveRevision)Ze(null),E(`The setup changed after review. Review the latest changes before publishing.`);else{Ge(`publish`),E(null);try{await m.publish(e,nt,{expectedActiveRevision:Ye.baseActiveRevision,expectedCompiledChecksum:Ye.compiledChecksum}),v({draft:null,etag:null}),Ze(null),p?.()}catch(e){Oc(e)?await ot(`The setup changed before it could be published. Review the latest draft and publish again.`):E(wc(e,`Could not publish this setup.`))}finally{Ge(null)}}}}async function qt(){if(nt&&!We){Ge(`discard`),E(null);try{await m.discard(e,nt),v({draft:null,etag:null}),Ze(null),p?.()}catch(e){Oc(e)?await ot(`This setup changed in another session. The latest draft is loaded.`):E(wc(e,`Could not discard these changes.`))}finally{Ge(null)}}}async function Jt(){if(tt&&nt&&h&&!We){Ge(`restart`),E(null),Ze(null);try{await m.discard(e,nt),await m.createDraft(e,h.activeRevision),A({...wT}),P(``),R([]),B([]),te({kind:`none`}),ve(null),Te(null),Oe(null),Ae({...TT}),je(null),Ne(``),Fe(null),Ve(null),Ue(null),await it(!1)}catch(e){Oc(e)?await ot(`The setup changed again. Reloaded the latest draft and published setup.`):E(wc(e,`Could not restart this setup.`))}finally{Ge(null)}}}if(x)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-loading-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-loading-title`,children:`Advanced measurement setup`})}),(0,Q.jsx)(`div`,{className:`h-28 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Loading advanced measurement setup`})]});if(C)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-error-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-error-title`,children:`Advanced measurement setup`})}),(0,Q.jsxs)(`div`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:C}),(0,Q.jsx)(J,{className:`mt-3 pointer-coarse:min-h-11`,type:`button`,size:`sm`,variant:`outline`,onClick:()=>{it(!0)},children:`Try again`})]})]});if(!K||s&&!nt)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-empty-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-empty-title`,children:`Advanced measurement setup`})}),(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:s?`Start setup from the project Overview.`:`No advanced setup is available to review.`})]});if(s&&tt&&h&&tt.baseActiveRevision!==h.activeRevision)return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-stale-draft-title`,className:`space-y-4`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`advanced-measurement-stale-draft-title`,children:`Advanced measurement setup`})}),(0,Q.jsxs)(`div`,{role:`alert`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`This draft is based on an older published setup.`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Restart from the latest setup before making more changes.`}),(0,Q.jsx)(J,{className:`mt-3 pointer-coarse:min-h-11`,type:`button`,size:`sm`,variant:`outline`,disabled:We===`restart`,onClick:()=>{Jt()},children:We===`restart`?`Restarting…`:`Discard draft and restart`})]}),T?(0,Q.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:T}):null]});let Yt=i&&a?(0,Q.jsx)(`div`,{className:`flex justify-end`,children:(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:a,children:`Retry queries`})}):null;return(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[h?.mode===`active-v1`?(0,Q.jsx)(`p`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-3 text-copy-14 text-secondary`,children:`Review and publish this setup to enable class-filtered reporting.`}):null,T?(0,Q.jsx)(`p`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-3 text-copy-14 text-negative`,children:T}):null,Yt,y===`import`||y===`properties`?(0,Q.jsx)(CT,{currentStep:y,hasDraft:tt!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},importProperties:{importDraft:k,onImportDraftChange:e=>{A(e),M(`idle`),E(null)},onReviewSitemap:e=>{Et(e)},reviewState:j,properties:ct,propertiesState:`ready`,propertiesSearch:N,onPropertiesSearchChange:P,maxVisibleProperties:F,onShowAllProperties:()=>I(ct.length),selectedPropertyIds:L,onSelectedPropertyIdsChange:e=>R([...e]),onContinue:e=>{jt(e)},isContinuing:We!==null,onRetryProperties:()=>{at()},onReturnToImport:()=>b(`import`),onAddProperty:Dt}}):y===`queries`?(0,Q.jsx)(CT,{currentStep:`queries`,hasDraft:tt!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},onManageProjectQueries:f,queries:{onCreateQueries:d?e=>At(e):void 0,isCreatingQueries:We===`create-queries`||We===`create-and-pair-questions`,isBusy:We!==null,createQueriesError:Ke,availability:Tt,properties:ut,queries:ft,selectedQueryIds:z,isApplying:We===`assignments`||We===`paired-assignments`,onSelectedQueryIdsChange:e=>B([...e]),onApplySelectedQueries:e=>Mt(e),groups:pt,audience:ee,onAudienceChange:e=>{te(e),Oe(null)},executionOptions:gt,executionOptionId:ne,onExecutionOptionChange:e=>{V(e),Oe(null)},markets:mt,marketAssignments:ht,onSaveMarket:s?kt:void 0,marketId:H,onMarketChange:e=>{re(e),ge(null)},marketExecutionOptionId:U,onMarketExecutionOptionChange:e=>{ie(e),ge(null)},onRouteMarket:Pt,isRoutingMarket:We===`route-markets`,isPreviewingMarketRouting:le,marketRoutingImpact:xt,marketRoutingError:de,onRetryMarketRouting:()=>me(e=>e+1),marketRoutingNotice:he,assignmentImpact:_e&&ye===Ct&&_e.draftEtag===nt?cE(_e):null,isPreviewingAssignmentImpact:xe,assignmentImpactError:we,onRetryAssignmentImpact:()=>De(e=>e+1),assignmentNotice:W,onReplaceAssignments:Nt,isReplacingAssignments:We===`replace-assignments`,onCreateAndPairQuestions:s&&d?It:void 0,onClearQueryAssignments:Lt,onRemoveQuery:Lt,canContinue:dt>0,onBack:()=>b(`groups`),onContinue:()=>b(`review`)}}):y===`groups`?(0,Q.jsx)(CT,{currentStep:`groups`,hasDraft:tt!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},groups:{properties:ut,groups:pt,groupDraft:ke,isSaving:We===`group`,onGroupDraftChange:Ae,onSaveGroup:Rt,onEditGroup:e=>zt(e.id),onRemoveGroup:Bt,onClearGroupDraft:()=>{je(null),Ae({...TT})},membershipImport:{csv:Me,preview:Pe,isReviewing:Ie,isApplying:Re,error:Be,notice:He,onCsvChange:Vt,onReview:Ht,onApply:Wt},onBack:()=>{b(`properties`)},onContinue:()=>b(`queries`)}}):(0,Q.jsx)(CT,{currentStep:`review`,hasDraft:tt!==null,canEdit:s,onStepChange:s?void 0:b,onDiscard:()=>{qt()},review:{properties:lt.map(e=>({id:e.stableKey,name:e.label,aliases:e.aliases,identityAliases:e.identityAliases??[],urls:e.urlMatchers})),onSaveProperty:s?Ot:void 0,counts:{properties:lt.length,queries:new Set(K.authoring.assignments.map(e=>e.queryId)).size,groups:K.authoring.groups.length,assignments:K.authoring.assignments.length,providerCalls:Ye?.providerCalls},flaggedExceptions:wt,reviewedChanges:Ye?.changes,isReviewing:We===`review`,canReviewChanges:dt>0&&!We,onReviewChanges:Gt,onBack:()=>b(`queries`),canPublish:Ye!==null&&!We&&!c,sweepActive:c,isPublishing:We===`publish`,onPublish:Kt}})]})}var fE=`Mentioned = the property’s name in the answer. Cited = one of the property’s own pages in the sources. Neither implies the other.`,pE=[{key:`label`,label:`Property`,numeric:!1},{key:`mentionCoverage`,label:`Mention`,numeric:!0},{key:`citationCoverage`,label:`Citation`,numeric:!0}];function mE(e){return e.label!==`Complete`}var hE=`__all_properties__`,gE=50,_E=50,vE=20,yE=50,bE=250,xE=5,SE=[{value:`all`,label:`All queries`},{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],CE={"this-property":`Matches this Property`,"another-property":`Matches another Property`,"owned-unassigned":`Site URL not included in a Property`,external:`External URL`,"multiple-properties":`Matches multiple Properties`,"invalid-url":`Invalid URL`},wE={plan_v1:`Setup update required.`,no_completed_run:`Not measured yet.`,no_population:`No matching queries.`,evidence_incomplete:`Evidence incomplete.`,identity_ambiguous:`${Ai}.`,"identity-ambiguous":`${Ai}.`,not_applicable:`Not applicable.`,incomplete:`The latest measurement is incomplete.`,"evidence-incomplete":`Some source evidence is incomplete.`,citation_not_measured:`The engines return no sources.`,"citation-not-measured":`The engines return no sources.`,"no-population":`No measurements are available for this selection.`,unavailable:`This measurement is unavailable.`},TE={numerator:null,denominator:null,reason:`plan_v1`};function EE(e){return e.numerator!==null&&Number.isFinite(e.numerator)&&Number.isFinite(e.denominator)&&e.numerator>=0&&e.denominator>0&&e.numerator<=e.denominator}function DE(e){return EE(e)?`${e.numerator} of ${e.denominator} (${$e(e.numerator/e.denominator)})`:`N/A`}function OE(e){if(EE(e))return``;let t=e.reason??`unavailable`;return wE[t]??t}function kE(e){let t=[];return e.market&&t.push(e.market),e.urls.length>0&&t.push(`${e.urls.length} ${e.urls.length===1?`URL`:`URLs`}`),t.join(` · `)}function AE(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||e<0||t<=0||e>t?null:`${e} of ${t}`}function jE(e){let t=e.trim();return t&&!t.toLocaleLowerCase().includes(`unavailable`)?t:null}function ME(e){return e?.closest?.(`button, a, input, select, textarea, [role="button"]`)!=null}function NE({metric:e,signal:t,compact:n=!1}){let r=n?EE(e)?`text-label-14-strong text-primary`:`text-label-14-strong text-secondary`:EE(e)?`text-label-18-strong text-heading`:`text-label-18-strong text-secondary`,i=EE(e)?oi(e,t):null;return(0,Q.jsxs)(`span`,{className:`inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums`,...EE(e)?{}:{title:OE(e)},children:[(0,Q.jsx)(`span`,{className:r,children:DE(e)}),i?(0,Q.jsx)(X,{tone:`caution`,placement:`bottom`,label:i.label,text:i.text}):null]})}function PE({shown:e,total:t,onShowAll:n,itemLabel:r}){return e>=t?null:(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,e,` of `,t]}),(0,Q.jsxs)(J,{size:`sm`,variant:`outline`,onClick:n,children:[`Show all `,t,` `,r]})]})}function FE({title:e,values:t,emptyLabel:n,valueClassName:r=`text-secondary`}){let[i,a]=(0,Z.useState)(_E),o=t.slice(0,i);return(0,Q.jsxs)(`section`,{"aria-label":e,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:e}),t.length===0?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:n}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`ul`,{className:`mt-2 space-y-1.5 text-label-14`,children:o.map((e,t)=>(0,Q.jsx)(`li`,{className:r,children:e},`${e}:${t}`))}),(0,Q.jsx)(PE,{shown:o.length,total:t.length,itemLabel:e.toLocaleLowerCase(),onShowAll:()=>a(2**53-1)})]})]})}function IE({evidence:e,state:t=`ready`,onRetry:n}){let[r,i]=(0,Z.useState)(_E),a=e.slice(0,r);return(0,Q.jsxs)(`section`,{"aria-label":`Evidence`,children:[(0,Q.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Evidence`}),t===`loading`?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Loading evidence…`}):t===`error`?(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsx)(`span`,{children:`Evidence could not be loaded.`}),n?(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:n,children:`Retry evidence`}):null]}):e.length===0?(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`No source evidence is available.`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`div`,{className:`mt-2 overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[640px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{children:`Query`}),(0,Q.jsx)(`th`,{children:`URL`})]})}),(0,Q.jsx)(`tbody`,{children:a.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`span`,{className:`flex flex-wrap items-center gap-1`,children:[(0,Q.jsx)(Y,{tone:e.tone,children:CE[e.kind]}),e.historical?(0,Q.jsx)(Y,{tone:`caution`,children:`Historical`}):null]})}),(0,Q.jsxs)(`td`,{className:`text-secondary`,children:[(0,Q.jsx)(`span`,{className:`block`,children:e.query}),e.provider||e.location?(0,Q.jsx)(`span`,{className:`mt-1 block text-label-12 text-muted`,children:[e.provider?fr(e.provider):null,e.location].filter(Boolean).join(` · `)}):null]}),(0,Q.jsx)(`td`,{className:`break-all text-secondary`,children:e.url})]},e.id))})]})}),(0,Q.jsx)(PE,{shown:a.length,total:e.length,itemLabel:`evidence items`,onShowAll:()=>i(2**53-1)})]})]})}function LE({property:e,onRetryEvidence:t}){return(0,Q.jsxs)(`div`,{className:`space-y-5 py-2`,children:[(0,Q.jsx)(FE,{title:`Assigned queries`,values:e.assignedQueries,emptyLabel:`No queries are assigned.`}),(0,Q.jsx)(FE,{title:`URLs`,values:e.urls,emptyLabel:`No URLs are assigned.`,valueClassName:`break-all text-secondary`}),(0,Q.jsx)(IE,{evidence:e.evidence,state:e.evidenceState,onRetry:t})]})}function RE({values:e}){return(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-share-of-voice`,className:`border-y border-default py-4`,children:[(0,Q.jsx)(`h2`,{id:`advanced-measurement-share-of-voice`,className:`text-heading-14 text-heading`,children:`Brand share of voice`}),(0,Q.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[420px]`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Name`}),(0,Q.jsx)(`th`,{children:`Share of voice`})]})}),(0,Q.jsx)(`tbody`,{children:e.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.name}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(NE,{metric:e.coverage,signal:`mentioned`,compact:!0})})]},e.name))})]})})]})}function zE({ariaLabelledBy:e,value:t,options:n,onChange:r,disabled:i=!1}){function a(e){if(i)return;let a=n.findIndex(e=>e.value===t),o=null;if(e.key===`ArrowRight`||e.key===`ArrowDown`?o=(a+1)%n.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?o=(a-1+n.length)%n.length:e.key===`Home`?o=0:e.key===`End`&&(o=n.length-1),o===null)return;e.preventDefault();let s=n[o];r(s.value),e.currentTarget.querySelectorAll(`[role="radio"]`)[o].focus()}return(0,Q.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":e,"aria-disabled":i,className:`segmented flex-wrap`,onKeyDown:a,children:n.map(e=>{let n=e.value===t;return(0,Q.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":n,tabIndex:n?0:-1,disabled:i,onClick:()=>r(e.value),className:`segmented-option disabled:cursor-not-allowed disabled:opacity-50 ${n?`segmented-option-active`:``}`,children:e.label},e.value)})})}function BE({outcomes:e}){let t=[{key:`both`,count:e.bothSignals,label:`mentioned and cited`,tone:`text-primary`},{key:`mentioned-only`,count:e.mentionedOnly,label:`mentioned only`,tone:`text-primary`},{key:`cited-only`,count:e.citedOnly,label:`cited only`,tone:`text-primary`},{key:`neither`,count:e.neither,label:`neither signal`,tone:`text-negative`},...e.notMeasured>0?[{key:`not-measured`,count:e.notMeasured,label:`not measured`,tone:`text-faint`}]:[]];return(0,Q.jsx)(`div`,{"aria-label":`Property outcomes`,className:`flex flex-wrap gap-x-8 gap-y-3 py-3`,children:t.map(e=>(0,Q.jsxs)(`div`,{className:`whitespace-nowrap`,children:[(0,Q.jsx)(`p`,{className:`font-mono text-copy-20-strong tabular-nums ${e.tone}`,children:e.count}),(0,Q.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[e.label,e.key===`not-measured`?(0,Q.jsx)(X,{text:`One or both signals missing. Not the same as neither.`}):null]})]},e.key))})}function VE({report:e,canEdit:t,onRunMeasurement:n,onRepublishSetup:r,isRunningMeasurement:i=!1,isRepublishingSetup:a=!1,isViewLoading:o=!1,isLoadingMore:s=!1,isLoadMoreError:c=!1,viewSearch:l,onViewChange:u,onLoadMore:d,onPropertyExpand:f,onRetryEvidence:p,renderPropertyLink:m}){let h=e.currentView!=null,g=e.classReporting===`available`&&(h||e.classScopes!=null),[_,v]=(0,Z.useState)(e.currentView?.queryClass??`all`),[b,x]=(0,Z.useState)(e.currentView?.scope.key??hE),[S,C]=(0,Z.useState)(l??``),[w,T]=(0,Z.useState)(gE),[E,D]=(0,Z.useState)(vE),[O,k]=(0,Z.useState)(e.currentView?.sort??`label-asc`),[A,j]=(0,Z.useState)(null),M=(0,Z.useRef)(l??``),N=g&&!h&&_!==`all`?_===`non-brand`?e.classScopes.nonBrand:e.classScopes.branded:e.overall,P=h?{aggregate:e.currentView.aggregate,groups:[]}:N,F=(0,Z.useCallback)(e=>{if(!h||!u)return;let t=e.scope??(b===hE?`all`:`group`),n=e.search??S;M.current=n,u({scope:t,...t===`group`?{groupKey:e.groupKey??b}:{},queryClass:e.queryClass??_,...n?{search:n}:{},...e.sort?{sort:e.sort}:{}})},[u,S,_,b,h]);(0,Z.useEffect)(()=>{e.currentView&&!o&&(v(e.currentView.queryClass),x(e.currentView.scope.key??hE),e.currentView.sort&&k(e.currentView.sort))},[o,e.currentView]),(0,Z.useEffect)(()=>{l!==void 0&&(M.current=l,C(e=>e.trim()===l.trim()?e:l))},[l]),(0,Z.useEffect)(()=>{if(!h||!u||S===M.current)return;let e=window.setTimeout(()=>F({search:S}),bE);return()=>window.clearTimeout(e)},[u,F,S,h]);let I=e.availableGroups??P.groups;(0,Z.useEffect)(()=>{b===hE||I.some(e=>e.id===b)||x(hE)},[I,b]);let L=h?void 0:P.groups.find(e=>e.id===b),R=L?.aggregate??P.aggregate,z=e=>g?e:TE,B=O,ee=S.trim().toLocaleLowerCase(),te=(0,Z.useMemo)(()=>!h&&ee?R.properties.filter(e=>e.name.toLocaleLowerCase().includes(ee)):R.properties,[R.properties,ee,h]),ne=h?te:te.slice(0,w),V=(h?e.currentView?.scope.kind===`group`:L!=null)&&_===`non-brand`&&g&&(h||L.confirmedCompetitorCount>0)&&(R.shareOfVoice?.length??0)>0,H=g?R.unavailablePropertyCount??0:0,re=e.flaggedResults.reduce((e,t)=>e+(t.count??1),0),U=e.flaggedResultsTotal??re,ie=[z(R.metrics.propertiesMentioned),z(R.metrics.mentionCoverage),z(R.metrics.citationCoverage)].map(OE).find(Boolean),ae=g?e.nextActionText??ie??(H>0?`${H} ${H===1?`property is`:`properties are`} unavailable.`:U>0?`${U} flagged ${U===1?`result needs`:`results need`} review.`:null):wE.plan_v1,oe=e.latestMeasurement.status.tone!==`negative`&&e.latestMeasurement.completedSlots<e.latestMeasurement.totalSlots?AE(e.latestMeasurement.completedSlots,e.latestMeasurement.totalSlots):null,se=jE(e.latestMeasurement.date),ce=[{value:hE,label:`All properties`},...I.map(e=>({value:e.id,label:e.label}))],le=I.length>xE;function ue(e){x(e),F(e===hE?{scope:`all`}:{scope:`group`,groupKey:e})}function de(e){v(e),F({queryClass:e})}function fe(e){let t=A!==e;j(t?e:null),t&&f?.(e)}return(0,Q.jsxs)(`section`,{"aria-label":`Advanced measurement overview`,"aria-busy":o,className:`space-y-5`,children:[(0,Q.jsx)(`header`,{className:`border-b border-default pb-4`,children:(0,Q.jsx)(`div`,{role:`status`,"aria-label":`Measurement status and next action`,className:`flex flex-wrap items-center gap-x-3 gap-y-2`,children:o?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Updating results…`}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(Y,{tone:e.latestMeasurement.status.tone,children:e.latestMeasurement.status.label}),e.latestMeasurement.includesBridgedHistory?(0,Q.jsx)(Y,{tone:`caution`,children:`Includes historical data`}):null,oe?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:oe}):null,se?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:se}):null,ae?(0,Q.jsx)(`span`,{className:`text-label-14 text-secondary`,children:ae}):null,t&&g&&n?(0,Q.jsx)(J,{className:`ml-auto`,size:`sm`,onClick:()=>{n()},disabled:i,children:i?`Starting measurement…`:`Run measurement`}):t&&!g?(0,Q.jsx)(J,{className:`ml-auto`,size:`sm`,onClick:()=>{r?.()},disabled:!r||a,children:a?`Opening setup…`:`Republish setup`}):null]})})}),(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-end gap-4 border-b border-default pb-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsx)(`label`,{id:`advanced-measurement-group-label`,htmlFor:le?`advanced-measurement-group`:void 0,className:`block text-label-14-strong text-heading`,children:`Group`}),le?(0,Q.jsx)(`select`,{id:`advanced-measurement-group`,value:b,onChange:e=>ue(e.target.value),className:`h-9 rounded-md border border-default bg-surface px-3 text-label-14 text-primary focus:outline-none focus:ring-2 focus:ring-mono-400`,children:ce.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,Q.jsx)(zE,{ariaLabelledBy:`advanced-measurement-group-label`,value:b,options:ce,onChange:ue})]}),(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[(0,Q.jsx)(`label`,{id:`advanced-measurement-class-label`,className:`block text-label-14-strong text-heading`,children:`Query type`}),(0,Q.jsx)(zE,{ariaLabelledBy:`advanced-measurement-class-label`,value:_,options:SE,onChange:de,disabled:!g})]}),(0,Q.jsxs)(`div`,{className:`ml-auto min-w-52 max-w-xs flex-1 space-y-1`,children:[(0,Q.jsx)(`label`,{htmlFor:`advanced-measurement-search`,className:`block text-label-14-strong text-heading`,children:`Search properties`}),(0,Q.jsx)(`input`,{id:`advanced-measurement-search`,type:`search`,value:S,onChange:e=>C(e.target.value),placeholder:`Search properties`,className:`h-9 w-full rounded-md border border-default bg-surface px-3 text-label-14 text-primary placeholder-mono-400 focus:outline-none focus:ring-2 focus:ring-mono-400`})]})]}),!o&&V?(0,Q.jsx)(RE,{values:R.shareOfVoice??[]}):null,o?(0,Q.jsx)(`div`,{className:`h-44 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Updating Property results`}):(0,Q.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-properties-title`,children:[(0,Q.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,Q.jsxs)(`div`,{className:`flex items-center`,children:[(0,Q.jsx)(`h2`,{id:`advanced-measurement-properties-title`,className:`text-heading-16 text-heading`,children:`Properties`}),(0,Q.jsx)(X,{text:fE})]}),(0,Q.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[e.currentView?.propertyTotal??te.length,` `,(e.currentView?.propertyTotal??te.length)===1?`property`:`properties`]})]}),e.currentView?.outcomes?(0,Q.jsx)(BE,{outcomes:e.currentView.outcomes}):null,(0,Q.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,Q.jsxs)(`table`,{className:`evidence-table min-w-[720px]`,children:[(0,Q.jsx)(`caption`,{className:`sr-only`,children:`Property measurement results`}),(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[pE.map(e=>{let t=B.startsWith(`${e.key}-`),n=t&&B.endsWith(`-desc`)?`descending`:t?`ascending`:`none`;return(0,Q.jsx)(`th`,{"aria-sort":n,className:(e.numeric,void 0),children:u?(0,Q.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1 text-inherit hover:text-heading`,onClick:()=>{let n=`${e.key}-${t&&B.endsWith(`-asc`)?`desc`:`asc`}`;k(n),F({sort:n})},"aria-label":`Sort by ${e.label.toLowerCase()}`,children:[e.label,(0,Q.jsx)(y,{className:`h-3 w-3 transition-transform ${t?`opacity-100`:`opacity-0`} ${n===`ascending`?`rotate-180`:``}`,"aria-hidden":`true`})]}):e.label},e.key)}),(0,Q.jsx)(`th`,{children:(0,Q.jsx)(`span`,{className:`sr-only`,children:`Details`})})]})}),(0,Q.jsxs)(`tbody`,{children:[ne.map(e=>{let t=A===e.id;return(0,Q.jsxs)(Z.Fragment,{children:[(0,Q.jsxs)(`tr`,{className:`cursor-pointer transition-colors hover:bg-surface-subtle`,onClick:t=>{ME(t.target)||fe(e.id)},children:[(0,Q.jsxs)(`td`,{className:`text-label-14-strong text-heading`,children:[m?m({id:e.id,name:e.name}):e.name,mE(e.status)||e.historical?(0,Q.jsxs)(`span`,{className:`ml-2 inline-flex flex-wrap items-center gap-1 align-middle`,children:[mE(e.status)?(0,Q.jsx)(Y,{tone:e.status.tone,children:e.status.label}):null,e.historical?(0,Q.jsx)(Y,{tone:`caution`,children:`Historical`}):null]}):null,kE(e)?(0,Q.jsx)(`div`,{className:`mt-0.5 text-label-12 text-faint`,children:kE(e)}):null]}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(NE,{metric:e.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(NE,{metric:e.citationCoverage,signal:`cited`,compact:!0})}),(0,Q.jsx)(`td`,{className:`text-right`,children:(0,Q.jsx)(J,{size:`icon`,variant:`ghost`,"aria-expanded":t,"aria-label":t?`Hide details for ${e.name}`:`Show details for ${e.name}`,onClick:()=>fe(e.id),children:(0,Q.jsx)(y,{className:`h-4 w-4 transition-transform duration-200 motion-reduce:transition-none ${t?`rotate-180`:``}`,"aria-hidden":`true`})})})]},e.id),t?(e.providers??[]).map(t=>(0,Q.jsxs)(`tr`,{className:`measurement-subrow`,children:[(0,Q.jsx)(`td`,{className:`measurement-subrow-name`,children:fr(t.provider)}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(NE,{metric:t.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,Q.jsx)(`td`,{className:`text-secondary`,children:(0,Q.jsx)(NE,{metric:t.citationCoverage,signal:`cited`,compact:!0})}),(0,Q.jsx)(`td`,{})]},`${e.id}:${t.provider}`)):null,t?(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`bg-surface-subtle px-4`,children:(0,Q.jsx)(LE,{property:e,onRetryEvidence:p})})},`${e.id}:details`):null]},e.id)}),ne.length===0?(0,Q.jsx)(`tr`,{children:(0,Q.jsx)(`td`,{colSpan:4,className:`py-8 text-center text-label-14 text-secondary`,children:`No properties match this search.`})}):null]})]})}),h&&e.currentView.nextCursor&&d?(0,Q.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing `,ne.length,` of `,e.currentView.propertyTotal]}),c?(0,Q.jsx)(`span`,{role:`alert`,children:`Could not load more properties.`}):null,(0,Q.jsx)(J,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>d(e.currentView.nextCursor),children:s?`Loading…`:c?`Retry loading more properties`:`Show 50 more`})]}):h?ne.length<e.currentView.propertyTotal?(0,Q.jsxs)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:[`Showing `,ne.length,` of `,e.currentView.propertyTotal]}):null:(0,Q.jsx)(PE,{shown:ne.length,total:te.length,itemLabel:`properties`,onShowAll:()=>T(2**53-1)})]}),!o&&!ee&&U>0?(0,Q.jsx)(`section`,{"aria-label":`Flagged results`,className:`border-t border-default pt-4`,children:(0,Q.jsxs)(`details`,{children:[(0,Q.jsxs)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading`,children:[`Flagged results (`,U,`)`]}),(0,Q.jsx)(`ul`,{className:`mt-3 space-y-3`,children:e.flaggedResults.slice(0,E).map(e=>(0,Q.jsxs)(`li`,{className:`flex flex-wrap items-start gap-2 text-label-14`,children:[(0,Q.jsx)(Y,{tone:e.tone,children:`Flagged`}),(0,Q.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.property}),(0,Q.jsx)(`span`,{className:`text-secondary`,children:e.summary})]},e.id))}),E<e.flaggedResults.length?(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing details for `,e.flaggedResults.slice(0,E).reduce((e,t)=>e+(t.count??1),0),` of `,U,` flagged results`]}),(0,Q.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>D(t=>Math.min(e.flaggedResults.length,t+yE)),children:`Show 50 more`})]}):re<U?(0,Q.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-label-14 text-secondary`,children:[(0,Q.jsxs)(`span`,{children:[`Showing details for `,re,` of `,U,` flagged results`]}),h&&e.currentView.nextCursor&&d?(0,Q.jsx)(J,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>d(e.currentView.nextCursor),children:s?`Loading…`:c?`Retry loading more Properties`:`Load more Properties`}):null]}):null]})}):null]})}function HE(e){return e===`continue`?`Continue setup`:e===`edit`?`Edit setup`:e===`republish`?`Republish setup`:`Set up advanced measurement`}function UE(e){return e.activePlanSchemaVersion===null?{surface:`simple-overview`,setupAction:e.hasDraft?`continue`:`set-up`}:e.activePlanSchemaVersion<2?{surface:`advanced-overview-v1`,setupAction:`republish`}:{surface:`advanced-overview`,setupAction:e.hasDraft?`continue`:`edit`}}function WE(e){let t=e.targets.length,n=e.groups.filter(e=>e.parentGroupKey===void 0).length,r=[`${t} ${t===1?`property`:`properties`}`];return n>0&&r.push(`${n} ${n===1?`market`:`markets`}`),r.join(` · `)}function GE({mode:e,canEdit:t,simpleOverview:n,report:r,reportState:i=`ready`,onOpenSetup:a,onRunMeasurement:o,onRetryReport:s,onViewChange:c,onLoadMore:l,onPropertyExpand:u,onRetryEvidence:d,renderPropertyLink:f,isRunningMeasurement:p,isOpeningSetup:m,isViewLoading:h,isLoadingMore:g,isLoadMoreError:_,viewSearch:v}){return e.surface===`simple-overview`?n:(0,Q.jsxs)(`div`,{className:`space-y-4`,children:[e.setupAction===`republish`&&!r&&t&&a?(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,disabled:m,onClick:a,children:m?`Opening setup…`:HE(e.setupAction)}),(0,Q.jsx)(`p`,{className:`supporting-copy m-0`,children:`Unpublished changes are waiting to go live.`})]}):null,i===`loading`?(0,Q.jsx)(`div`,{className:`h-32 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Loading advanced measurement report`}):i===`error`&&!r?(0,Q.jsxs)(`div`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,Q.jsx)(`p`,{children:`Could not load the advanced measurement report.`}),s?(0,Q.jsx)(J,{className:`mt-3`,type:`button`,size:`sm`,variant:`outline`,onClick:s,children:`Retry report`}):null]}):r?(0,Q.jsx)(VE,{report:r,canEdit:t,onRunMeasurement:o,onRepublishSetup:a,onViewChange:c,onLoadMore:l,onPropertyExpand:u,onRetryEvidence:d,renderPropertyLink:f,isRunningMeasurement:p,isRepublishingSetup:m,isViewLoading:h,isLoadingMore:g,isLoadMoreError:_,viewSearch:v}):(0,Q.jsx)(`div`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4 text-label-14 text-secondary`,children:`No advanced measurement report is available yet.`})]})}var KE={numerator:null,denominator:null,reason:`plan_v1`};function qE(e){return e.kind===`exact`?e.url:e.kind===`prefix`?`https://${e.host}${e.pathPrefix}`:`https://${e.host}`}function JE(e){return e.numerator===null?{numerator:null,denominator:null,reason:e.reason}:{numerator:e.numerator,denominator:e.denominator,...e.unattributed===void 0?{}:{unattributed:e.unattributed},...e.unchecked===void 0?{}:{unchecked:e.unchecked},...e.citationNotMeasured===void 0?{}:{citationNotMeasured:e.citationNotMeasured}}}function YE(e){return e===`assigned`?`this-property`:e===`sibling`?`another-property`:e===`ownedUnmapped`?`owned-unassigned`:e===`external`?`external`:e===`ambiguous`?`multiple-properties`:`invalid-url`}function XE(e){return e===`assigned`?`positive`:e===`external`?`neutral`:e===`invalid`?`negative`:`caution`}function ZE(e){if(!e)return`Date unavailable`;let t=new Date(e);return Number.isFinite(t.getTime())?t.toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`}):`Date unavailable`}function QE(e){return e.usageEdgeType!==`target`||!e.usageEdgeId.startsWith(`target:`)?null:e.usageEdgeId.slice(7).split(`:`,1)[0]??null}function $E(e){let t=new Map;for(let n of e){let e=QE(n);if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}return t}function eD(e,t){if(e.plan.schemaVersion!==1)throw Error(`Version-one report adapter received a different setup version.`);let n=e.plan,r=new Map(n.targets.map(e=>[e.stableKey,e])),i=new Map(n.querySnapshots.map(e=>[e.queryId,e.queryText])),a=new Map;for(let e of n.targetQuerySelections){let t=a.get(e.targetKey)??[];t.push(...e.queryIds.map(e=>i.get(e)).filter(e=>!!e)),a.set(e.targetKey,[...new Set(t)])}let o=$E(t.evidence),s=n.executionNodes.reduce((e,t)=>e+t.expectedSnapshots,0),c=t.run?.status===`completed`&&s>0,l=c?s:0,u=c?s:0,d=t.targets.map(e=>{let n=r.get(e.id),i=o.get(e.id)??[],s=i.map(e=>({id:`${e.observationId}:${e.usageEdgeId}:${e.sourceUrl}`,kind:YE(e.classification),query:e.queryText,url:e.sourceUrl,tone:XE(e.classification),historical:e.historical||e.bridged})),c=i.some(e=>e.historical||e.bridged),l=t.run?e.completeness.complete?n?.mentionNotApplicable?{label:`No aliases`,tone:`caution`}:{label:`Complete`,tone:`positive`}:{label:`Incomplete · ${e.completeness.executed} of ${e.completeness.expected}`,tone:`caution`}:{label:`Not measured`,tone:`neutral`};return{id:e.id,name:e.label,mentionCoverage:JE(e.mentionCoverage),citationCoverage:JE(e.citationCoverage),status:l,assignedQueries:a.get(e.id)??[],urls:n?.urls.map(qE)??[],evidence:s,historical:c}}),f=new Map(d.map(e=>[e.id,e])),p=new Map(n.groups.map(e=>[e.stableKey,e]));return{classReporting:`plan-v1`,latestMeasurement:{status:t.run?.status===`completed`?{label:`Complete`,tone:`positive`}:t.run?.status===`partial`?{label:`Partial result`,tone:`caution`}:{label:`Not measured`,tone:`neutral`},completedSlots:l,totalSlots:u,date:ZE(t.run?.finishedAt??t.run?.createdAt??null),includesBridgedHistory:t.diagnostics.bridgedObservationIds.length>0||t.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:KE,mentionCoverage:KE,citationCoverage:KE},properties:d},groups:t.groups.map(e=>({id:e.id,label:e.label,confirmedCompetitorCount:p.get(e.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:KE,mentionCoverage:KE,citationCoverage:KE},properties:e.targetIds.map(e=>f.get(e)).filter(e=>!!e)}}))},flaggedResults:[]}}function tD({project:e,onUpdateProject:t}){let[n,r]=(0,Z.useState)(!1),[i,a]=(0,Z.useState)(!1),[o,s]=(0,Z.useState)(null),[c,l]=(0,Z.useState)(e.displayName),[u,d]=(0,Z.useState)(e.canonicalDomain),[f,p]=(0,Z.useState)(e.country),[m,h]=(0,Z.useState)(e.language),[g,_]=(0,Z.useState)(e.ownedDomains??[]),[v,y]=(0,Z.useState)(``),[b,x]=(0,Z.useState)(e.aliases??[]),[S,C]=(0,Z.useState)(``),[w,T]=(0,Z.useState)(null),[E,D]=(0,Z.useState)(!1),[O,k]=(0,Z.useState)(!1),[A,j]=(0,Z.useState)(``),[M,N]=(0,Z.useState)(``),[P,F]=(0,Z.useState)(``),[I,L]=(0,Z.useState)(``),[R,z]=(0,Z.useState)(``),[B,ee]=(0,Z.useState)(null),[te,ne]=(0,Z.useState)(null),V=(0,Z.useId)();(0,Z.useEffect)(()=>{n||(l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]))},[e,n]);function H(){r(!1),s(null),l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]),y(``),C(``)}function re(){let e=v.trim();e&&(g.includes(e)||_([...g,e]),y(``))}function U(e){_(g.filter(t=>t!==e))}function ie(){let e=S.trim();if(!e)return;let t=e.toLowerCase();b.some(e=>e.toLowerCase()===t)||x([...b,e]),C(``)}function ae(e){x(b.filter(t=>t!==e))}async function oe(){if(c.trim()&&u.trim()&&f.trim()&&m.trim()){a(!0),s(null);try{await t(e.name,{displayName:c.trim(),canonicalDomain:u.trim(),ownedDomains:g,aliases:b,country:f.trim(),language:m.trim()}),r(!1),Ni({title:`Project settings saved`,detail:`${c.trim()} was updated.`,tone:`positive`,dedupeKey:`project:update:${e.name}`,dedupeMode:`replace`})}catch(e){s(e instanceof Error?e.message:`Failed to save`)}finally{a(!1)}}}async function se(){let t=A.trim(),n=M.trim(),r=P.trim(),i=I.trim();if(t&&n&&r&&i){D(!0),T(null);try{let a={label:t,city:n,region:r,country:i};R.trim()&&(a.timezone=R.trim()),await An(e.name,a),j(``),N(``),F(``),L(``),z(``),k(!1),Ni({title:`Search location added`,detail:`${t} is now available for ${e.name}.`,tone:`positive`,dedupeKey:`project:location:add:${e.name}:${t}`,dedupeMode:`drop`})}catch(e){T(e instanceof Error?e.message:`Failed to add search location`)}finally{D(!1)}}}async function ce(t){D(!0),T(null);try{await sr(e.name,t),Ni({title:`Search location removed`,detail:`${t} was removed from ${e.name}.`,tone:`positive`,dedupeKey:`project:location:remove:${e.name}:${t}`,dedupeMode:`drop`})}catch(e){T(e instanceof Error?e.message:`Failed to remove search location`)}finally{D(!1)}}async function le(t){D(!0),T(null);try{await jt(e.name,t),Ni({title:`Default search location updated`,detail:`${t} is now the default for ${e.name}.`,tone:`positive`,dedupeKey:`project:location:default:${e.name}`,dedupeMode:`replace`})}catch(e){T(e instanceof Error?e.message:`Failed to set default search location`)}finally{D(!1)}}async function ue(t){ee(t),ne(null);try{await Ye(e.name,t),Ni({title:`${t.toUpperCase()} download started`,detail:`Historical citation and mention results for ${e.displayName}.`,tone:`positive`,dedupeKey:`project:results-export:${e.name}`,dedupeMode:`replace`})}catch(e){ne(e instanceof Error?e.message:`Could not download tracking results.`)}finally{ee(null)}}let de=c!==e.displayName||u!==e.canonicalDomain||f!==e.country||m!==e.language||JSON.stringify(g)!==JSON.stringify(e.ownedDomains??[])||JSON.stringify(b)!==JSON.stringify(e.aliases??[]),fe=!G()&&!tt(),pe=`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`,me=`mb-1 block text-label-14-strong text-secondary`,he=A.trim()&&M.trim()&&P.trim()&&I.trim();return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Project settings`})}),fe&&!n&&(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:`Edit settings`})]}),o&&(0,Q.jsxs)(`div`,{className:`mb-3 rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:[o,(0,Q.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>s(null),children:`×`})]}),fe&&n?(0,Q.jsxs)(`div`,{className:`material-base p-4 space-y-4`,children:[(0,Q.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-display-name`,className:me,children:`Display name`}),(0,Q.jsx)(`input`,{id:`${V}-display-name`,className:pe,type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`My Project`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-main-domain`,className:me,children:`Main domain`}),(0,Q.jsx)(`input`,{id:`${V}-main-domain`,className:pe,type:`text`,value:u,onChange:e=>d(e.target.value),placeholder:`example.com`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-country`,className:me,children:`Country`}),(0,Q.jsx)(`input`,{id:`${V}-country`,className:pe,type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`US`,maxLength:2})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-language`,className:me,children:`Language`}),(0,Q.jsx)(`input`,{id:`${V}-language`,className:pe,type:`text`,value:m,onChange:e=>h(e.target.value),placeholder:`en`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-owned-domain`,className:me,children:`Owned domains`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:g.map(e=>(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:[e,(0,Q.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>U(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(`input`,{id:`${V}-owned-domain`,className:`${pe} flex-1`,type:`text`,placeholder:`docs.example.com`,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),re())}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:!v.trim(),onClick:re,children:`Add`})]})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{htmlFor:`${V}-alias`,className:me,children:`Aliases`}),(0,Q.jsx)(`p`,{className:`mb-1.5 text-copy-14 text-secondary`,children:`Other brand names that may appear in answers.`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:b.map(e=>(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:[e,(0,Q.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>ae(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,Q.jsxs)(`div`,{className:`flex gap-2`,children:[(0,Q.jsx)(`input`,{id:`${V}-alias`,className:`${pe} flex-1`,type:`text`,placeholder:`Facebook`,value:S,onChange:e=>C(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),ie())}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:!S.trim(),onClick:ie,children:`Add`})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 pt-2 border-t border-default`,children:[(0,Q.jsx)(J,{type:`button`,disabled:i||!de||!c.trim()||!u.trim(),onClick:Mi(oe),children:i?`Saving...`:`Save changes`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,disabled:i,onClick:H,children:`Cancel`})]})]}):(0,Q.jsx)(`div`,{className:`material-base overflow-hidden`,children:(0,Q.jsx)(`table`,{className:`w-full text-label-14`,children:(0,Q.jsxs)(`tbody`,{children:[(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong w-40`,children:`Display name`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.displayName||`—`})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Main domain`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.canonicalDomain})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Owned domains`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5`,children:(e.ownedDomains??[]).length>0?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.ownedDomains.map(e=>(0,Q.jsx)(`span`,{className:`rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:e},e))}):(0,Q.jsx)(`span`,{className:`text-muted`,children:`—`})})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Aliases`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5`,children:(e.aliases??[]).length>0?(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.aliases.map(e=>(0,Q.jsx)(`span`,{className:`rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:e},e))}):(0,Q.jsx)(`span`,{className:`text-muted`,children:`—`})})]}),(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Market`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:ke(e.country,e.language)})]}),e.tags?.length?(0,Q.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Tags`}),(0,Q.jsx)(`td`,{className:`px-4 py-2.5`,children:(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.tags.map(e=>(0,Q.jsx)(`span`,{className:`rounded-md border border-mono-700/60 bg-mono-800/40 px-2 py-1 text-label-12 text-neutral`,children:e},e))})})]}):null,(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong align-top pt-3`,children:`Search locations`}),(0,Q.jsxs)(`td`,{className:`px-4 py-2.5`,children:[w&&(0,Q.jsxs)(`div`,{className:`mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-label-12 text-negative`,children:[w,(0,Q.jsx)(`button`,{type:`button`,className:`ml-1 text-negative-400 hover:text-negative-200`,onClick:()=>T(null),children:`×`})]}),(e.locations??[]).length>0?(0,Q.jsxs)(`table`,{className:`w-full text-label-12 mb-2`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{className:`text-faint`,children:[(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Label`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`City`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Region`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Country`}),(0,Q.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Timezone`}),(0,Q.jsx)(`th`,{className:`pb-1`})]})}),(0,Q.jsx)(`tbody`,{children:e.locations.map(t=>(0,Q.jsxs)(`tr`,{className:`border-t border-mono-800/30`,children:[(0,Q.jsx)(`td`,{className:`py-1.5 pr-3`,children:(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-md border px-2 py-1 text-label-12-strong ${t.label===e.defaultLocation?`border-positive-700/60 bg-positive-950/30 text-positive`:`border-mono-700/60 bg-mono-800/40 text-neutral`}`,children:[t.label,t.label===e.defaultLocation?` ★`:``]})}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.city}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.region}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.country}),(0,Q.jsx)(`td`,{className:`py-1.5 pr-3 text-muted`,children:t.timezone??`—`}),(0,Q.jsx)(`td`,{className:`py-1.5`,children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[fe&&t.label!==e.defaultLocation&&(0,Q.jsx)(`button`,{type:`button`,disabled:E,onClick:()=>{le(t.label)},className:`text-button-14 text-secondary hover:text-positive-400 transition-colors disabled:opacity-40`,"aria-label":`Set ${t.label} as default search location`,children:`Set default`}),fe&&(0,Q.jsx)(`button`,{type:`button`,disabled:E,onClick:()=>{ce(t.label)},className:`text-button-14 text-secondary hover:text-negative-400 transition-colors disabled:opacity-40`,"aria-label":`Remove search location ${t.label}`,children:`Remove`})]})})]},t.label))})]}):(0,Q.jsx)(`p`,{className:`text-muted text-copy-13 mb-2`,children:`No search locations configured`}),fe?O?(0,Q.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Add search location`}),(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Label *`}),(0,Q.jsx)(`input`,{className:pe,type:`text`,value:A,onChange:e=>j(e.target.value),placeholder:`nyc`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`City *`}),(0,Q.jsx)(`input`,{className:pe,type:`text`,value:M,onChange:e=>N(e.target.value),placeholder:`New York`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Region *`}),(0,Q.jsx)(`input`,{className:pe,type:`text`,value:P,onChange:e=>F(e.target.value),placeholder:`NY`})]}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Country *`}),(0,Q.jsx)(`input`,{className:pe,type:`text`,value:I,onChange:e=>L(e.target.value),placeholder:`US`,maxLength:2})]}),(0,Q.jsxs)(`div`,{className:`col-span-2`,children:[(0,Q.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Timezone (optional)`}),(0,Q.jsx)(`input`,{className:pe,type:`text`,value:R,onChange:e=>z(e.target.value),placeholder:`America/New_York`})]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 pt-1`,children:[(0,Q.jsx)(J,{type:`button`,size:`sm`,disabled:E||!he,onClick:Mi(se),children:E?`Adding...`:`Add search location`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:E,onClick:()=>{k(!1),T(null)},children:`Cancel`})]})]}):(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>k(!0),children:`+ Add search location`}):null]})]})]})})})]}),(0,Q.jsxs)(`section`,{className:`page-section`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,Q.jsx)(`h2`,{children:`Tracking results`}),(0,Q.jsx)(X,{text:`Each exported row is one query and engine result, including the saved answer and source URLs. Includes completed, partial, and failed checks with saved results. Test runs, provider credentials, and raw provider payloads are excluded.`})]})}),(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`div`,{className:`flex flex-wrap items-center gap-3`,children:(0,Q.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:B!==null,onClick:Mi(()=>ue(`csv`)),children:B===`csv`?`Preparing CSV...`:`Download CSV`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:B!==null,onClick:Mi(()=>ue(`json`)),children:B===`json`?`Preparing JSON...`:`Download JSON`})]})}),te&&(0,Q.jsx)(`p`,{className:`mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-copy-14 text-negative`,children:te})]})]})]})}var nD={edit:`Edit schedule`,pause:`Pause`,resume:`Resume`,save:`Save schedule`},rD=[{value:`daily`,label:`Every day`},{value:`weekly@mon`,label:`Every Monday`},{value:`weekly@wed`,label:`Every Wednesday`},{value:`weekly@fri`,label:`Every Friday`},{value:`twice-daily`,label:`Twice a day (6am & 6pm)`},{value:`calendar`,label:`Every N days`},{value:`custom`,label:`Custom cron expression`}],iD=[`UTC`,`America/New_York`,`America/Chicago`,`America/Denver`,`America/Los_Angeles`,`America/Toronto`,`America/Vancouver`,`Europe/London`,`Europe/Paris`,`Europe/Berlin`,`Asia/Tokyo`,`Asia/Shanghai`,`Asia/Singapore`,`Australia/Sydney`];function aD(e,t){let n=t===`UTC`?`UTC`:t.split(`/`).pop()?.replace(/_/g,` `)??t,r=new Date(`${e.startDate}T00:00:00Z`),i=Number.isNaN(r.getTime())?e.startDate:new Intl.DateTimeFormat(`en-US`,{month:`short`,day:`numeric`,year:`numeric`,timeZone:`UTC`}).format(r),[a,o]=e.time.split(`:`).map(Number),s=Number.isInteger(a)&&Number.isInteger(o)?new Intl.DateTimeFormat(`en-US`,{hour:`numeric`,minute:`2-digit`,timeZone:`UTC`}).format(new Date(Date.UTC(1970,0,1,a,o))):e.time;return`Every ${e.everyDays} days starting ${i} at ${s} · ${n}`}function oD({projectName:e}){let t=(0,Z.useId)(),n=mt(),r=!G()&&!tt()&&!n,i=R(),[a,o]=(0,Z.useState)(!1),[s,c]=(0,Z.useState)(!1),[l,u]=(0,Z.useState)(`daily`),[d,f]=(0,Z.useState)(6),[p,m]=(0,Z.useState)(``),[h,g]=(0,Z.useState)(14),[_,v]=(0,Z.useState)(``),[y,b]=(0,Z.useState)(`00:00`),[x,S]=(0,Z.useState)(`UTC`),[C,w]=(0,Z.useState)(!1),[T,E]=(0,Z.useState)(``),[D,O]=(0,Z.useState)(!1),[k,A]=(0,Z.useState)(!1),[j,M]=(0,Z.useState)(null),[N,P]=(0,Z.useState)(void 0),F=oa({client:q,path:{name:e}}),I=U({...Ba({client:q,path:{name:e}}),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`,retry:!1}),L=I.isPending||I.isFetching,z=I.isError,B=I.data?.find(e=>e.kind===Ct[`answer-visibility`])??null,ee=a&&N!==void 0&&(B?.updatedAt??null)!==N,te=C?T.trim():x,ne={timezone:te,...l===`calendar`?{recurrence:{everyDays:h,startDate:_,time:y}}:l===`custom`?{cron:p.trim()}:{preset:Oi(l,d)}},V=!!te&&(l!==`custom`||!!p.trim())&&(l!==`calendar`||Number.isInteger(h)&&h>=1&&h<=3650&&!!_&&!!y),H=U({queryKey:[`schedule-preview`,e,ne],queryFn:()=>Ze(e,ne),enabled:r&&a&&V,retry:!1,staleTime:0}),re=V&&H.isSuccess&&!H.isFetching&&!!H.data.nextRunAt,ie=e=>{i.setQueryData(F,t=>{let n=(t??[]).filter(e=>e.kind!==Ct[`answer-visibility`]);return e?[...n,e]:n})},ae=e=>{if(e){if(e.recurrence)u(`calendar`),g(e.recurrence.everyDays),v(e.recurrence.startDate),b(e.recurrence.time);else{let t=_i(e.preset??null,e.cronExpr);u(t.freq),f(t.hour),m(t.customCron)}let t=iD.includes(e.timezone);S(t?e.timezone:`Other`),w(!t),E(t?``:e.timezone)}else{u(`daily`),f(6),m(``),g(14),v(``),b(`00:00`);let e=Intl.DateTimeFormat().resolvedOptions().timeZone||`UTC`,t=iD.includes(e);S(t?e:`Other`),w(!t),E(t?``:e)}P(e?.updatedAt??null)},oe=()=>{r&&(ae(B),c(!1),M(null),o(!0))},se=()=>{ae(B),M(null)},ce=async()=>{(await I.refetch()).isError?M(`The schedule changed, but Canonry could not load the latest version. Retry the schedule check.`):M(a?null:`This schedule changed elsewhere. The latest version is now shown; review it and try again.`)},le=async(e,t)=>{e instanceof Pt&&e.code===`SCHEDULE_VERSION_CONFLICT`?await ce():M(e instanceof Error?e.message:t)};return(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Scheduled runs`})}),r&&!L&&!z&&!a&&(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:oe,children:B?nD.edit:`+ Set schedule`})]}),L&&(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Loading…`}),j&&!a&&(0,Q.jsx)(`p`,{className:`mt-2 text-copy-14 text-negative`,role:`alert`,children:j}),!L&&z&&(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Canonry could not verify this schedule.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{I.refetch()},children:`Retry`})]}),!L&&!z&&!a&&B===null&&(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`p`,{className:`supporting-copy`,children:n?`AI Visibility checks are run by your Canonry team`:`No schedule configured. Set one to automatically trigger AI Visibility checks.`})}),!L&&!z&&!a&&B!==null&&(0,Q.jsx)(`div`,{children:(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1`,children:[n&&(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`AI Visibility checks are run by your Canonry team`}),(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:B.recurrence?aD(B.recurrence,B.timezone):ti(B.preset??null,B.cronExpr,B.timezone)}),!B.recurrence&&(0,Q.jsxs)(`details`,{className:`text-copy-13 text-muted`,children:[(0,Q.jsx)(`summary`,{className:`cursor-pointer`,children:`Schedule details`}),(0,Q.jsxs)(`p`,{children:[`Cron: `,(0,Q.jsx)(`span`,{className:`font-mono`,children:B.cronExpr})]})]}),B.enabled&&B.nextRunAt&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Next run: `,hn(B.nextRunAt,B.timezone)]}),B.lastRunAt&&(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Last run: `,new Date(B.lastRunAt).toLocaleString()]})]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,Q.jsx)(Y,{tone:B.enabled?`positive`:`neutral`,children:B.enabled?`Active`:`Paused`}),r&&(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:D,onClick:Mi(async()=>{if(!r||!B)return;if(!B.enabled){ae(B),c(!0),M(null),o(!0);return}let t=B.updatedAt;O(!0),M(null);try{let n=await I.refetch();if(n.isError||n.data===void 0){M(`Canonry could not verify the latest schedule. Try again before updating it.`);return}let r=n.data.find(e=>e.kind===Ct[`answer-visibility`])??null;if(!r||r.updatedAt!==t){M(`This schedule changed elsewhere. Review the latest version and try again.`);return}let i={timezone:r.timezone,enabled:!r.enabled,providers:r.providers,expectedUpdatedAt:t};r.recurrence?i.recurrence=r.recurrence:r.preset?i.preset=r.preset:i.cron=r.cronExpr;let a=await Bn(e,i);ie(a),Ni({title:a.enabled?`Schedule resumed`:`Schedule paused`,detail:a.recurrence?aD(a.recurrence,a.timezone):ti(a.preset??null,a.cronExpr,a.timezone),tone:`positive`,dedupeKey:`schedule:toggle:${e}`,dedupeMode:`replace`})}catch(e){await le(e,`Failed to update schedule`)}finally{O(!1)}}),children:B.enabled?nD.pause:nD.resume}),r&&(0,Q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,disabled:k,onClick:Mi(async()=>{if(!r||!B)return;let t=B.updatedAt;A(!0),M(null);try{await Ie(e,t),ie(null),o(!1),P(void 0),Ni({title:`Schedule removed`,detail:`${e} will no longer run automatically.`,tone:`positive`,dedupeKey:`schedule:remove:${e}`,dedupeMode:`drop`})}catch(e){await le(e,`Failed to remove schedule`)}finally{A(!1)}}),children:k?`Removing…`:`Remove`})]})]})}),r&&a&&(0,Q.jsxs)(`div`,{className:`space-y-3`,children:[ee&&!D&&(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 rounded-md border border-caution bg-caution-soft px-3 py-2 text-label-14 text-caution`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:`This schedule changed elsewhere. Load the latest version before saving.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:se,children:`Load latest schedule`})]}),(0,Q.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Frequency`}),(0,Q.jsx)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Frequency`,value:l,onChange:e=>u(e.target.value),children:rD.map(e=>(0,Q.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),l!==`calendar`&&(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsxs)(`label`,{className:`text-label-13-strong text-secondary`,htmlFor:`${t}-hour`,children:[`Time · `,te||`choose timezone`]}),(0,Q.jsx)(`select`,{id:`${t}-hour`,className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40`,value:d,disabled:l===`twice-daily`||l===`custom`,onChange:e=>f(parseInt(e.target.value)),children:Array.from({length:24},(e,t)=>(0,Q.jsx)(`option`,{value:t,children:si(t)},t))})]})]}),l===`custom`&&(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-13-strong text-secondary`,htmlFor:`${t}-cron`,children:`Cron expression`}),(0,Q.jsx)(`input`,{id:`${t}-cron`,className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14-mono text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`text`,placeholder:`0 9 * * 1-5`,value:p,onChange:e=>m(e.target.value)})]}),l===`calendar`&&(0,Q.jsxs)(`div`,{className:`grid grid-cols-3 gap-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Repeat every`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Repeat every days`,type:`number`,min:`1`,max:`3650`,value:h,onChange:e=>g(Number(e.target.value))}),(0,Q.jsx)(`p`,{className:`text-copy-13 text-muted`,children:`days`})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Start date`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Start date`,type:`date`,value:_,onChange:e=>v(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Time`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Recurrence time`,type:`time`,value:y,onChange:e=>b(e.target.value)})]})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Timezone`}),(0,Q.jsxs)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-label-14 text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Timezone`,value:C?`Other`:x,onChange:e=>{e.target.value===`Other`?(w(!0),S(`Other`)):(w(!1),S(e.target.value))},children:[iD.map(e=>(0,Q.jsx)(`option`,{value:e,children:e},e)),(0,Q.jsxs)(`option`,{value:`Other`,children:[`Other (enter manually)`,`…`]})]}),C&&(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`text`,"aria-label":`Custom timezone`,placeholder:`e.g. America/New_York`,value:T,onChange:e=>E(e.target.value)})]}),V&&(0,Q.jsx)(`div`,{"aria-live":`polite`,className:`text-copy-14`,children:H.isFetching||H.isPending?(0,Q.jsx)(`p`,{role:`status`,className:`text-secondary`,children:`Checking next run…`}):H.isError?(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{role:`alert`,className:`text-negative`,children:Oe(H.error)}),(0,Q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{H.refetch()},children:`Retry preview`})]}):(0,Q.jsxs)(`p`,{className:`text-heading`,children:[`Next run: `,H.data.nextRunAt?(0,Q.jsx)(`time`,{dateTime:H.data.nextRunAt,children:hn(H.data.nextRunAt,H.data.timezone)}):`No future occurrence`]})}),j&&(0,Q.jsx)(`p`,{className:`text-negative-400 text-copy-14`,role:`alert`,children:j}),(0,Q.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{o(!1),P(void 0),M(null)},children:`Cancel`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,disabled:D||I.isFetching||z||ee||!re,onClick:Mi(async()=>{if(r&&!ee&&N!==void 0&&re){O(!0),M(null);try{let t=await I.refetch();if(t.isError||t.data===void 0){M(`Canonry could not verify the latest schedule. Try again before saving.`);return}let n=t.data.find(e=>e.kind===Ct[`answer-visibility`])??null;if((n?.updatedAt??null)!==N)return;let r={...ne,enabled:s||(n?.enabled??!0),providers:n?.providers??[],expectedUpdatedAt:N},i=await Bn(e,r);o(!1),P(void 0),ie(i),Ni({title:`Schedule saved`,detail:i.recurrence?aD(i.recurrence,i.timezone):ti(i.preset??null,i.cronExpr,i.timezone),tone:`positive`,dedupeKey:`schedule:${e}`,dedupeMode:`replace`})}catch(e){await le(e,`Failed to save schedule`)}finally{O(!1)}}}),children:D?`Saving…`:s?`Enable schedule`:nD.save})]})]})]})}var sD=[{value:`citation.lost`,label:`Citation lost`},{value:`citation.gained`,label:`Citation gained`},{value:`run.completed`,label:`Run completed`},{value:`run.failed`,label:`Run failed`}];function cD({projectName:e}){let[t,n]=(0,Z.useState)(`loading`),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(``),[s,c]=(0,Z.useState)([`citation.lost`,`citation.gained`]),[l,u]=(0,Z.useState)(!1),[d,f]=(0,Z.useState)(null),[p,m]=(0,Z.useState)({}),[h,g]=(0,Z.useState)(new Set),_=!G()&&!tt();(0,Z.useEffect)(()=>{be(e).then(n).catch(()=>n([]))},[e]);let v=e=>{c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},y=async()=>{if(a.trim()&&s.length!==0){u(!0),f(null);try{let t=await Un(e,{channel:`webhook`,url:a.trim(),events:s});n(e=>e===`loading`?[t]:[...e,t]),o(``),c([`citation.lost`,`citation.gained`]),i(!1),Ni({title:`Webhook added`,detail:`Notifications will be sent to ${t.url}.`,tone:`positive`,dedupeKey:`notification:add:${e}`,dedupeMode:`drop`})}catch(e){f(e instanceof Error?e.message:`Failed to add webhook`)}finally{u(!1)}}},b=async t=>{if(!h.has(t)){g(e=>new Set(e).add(t));try{await Se(e,t),n(e=>e===`loading`?e:e.filter(e=>e.id!==t)),Ni({title:`Webhook removed`,detail:`${e} no longer sends notifications to this endpoint.`,tone:`positive`,dedupeKey:`notification:remove:${e}:${t}`,dedupeMode:`drop`})}catch(e){f(e instanceof Error?e.message:`Failed to remove webhook`)}finally{g(e=>{let n=new Set(e);return n.delete(t),n})}}},x=async t=>{m(e=>({...e,[t]:{state:`testing`}}));try{let n=await Dt(e,t);m(e=>({...e,[t]:{state:n.ok?`ok`:`fail`,status:n.status}})),n.ok&&Ni({title:`Test notification sent`,detail:`Webhook returned status ${n.status}.`,tone:`positive`,dedupeKey:`notification:test:${e}:${t}`,dedupeMode:`replace`})}catch{m(e=>({...e,[t]:{state:`fail`}}))}};return(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,Q.jsx)(`div`,{children:(0,Q.jsx)(`h2`,{children:`Notifications`})}),_&&t!==`loading`&&(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!r),f(null)},children:r?`Cancel`:`+ Add webhook`})]}),_&&r&&(0,Q.jsxs)(`div`,{className:`mb-3 material-base p-4 space-y-3`,children:[(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Webhook URL`}),(0,Q.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`url`,placeholder:`https://hooks.example.com/canonry`,value:a,onChange:e=>o(e.target.value)})]}),(0,Q.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,Q.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Trigger on`}),(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-3`,children:sD.map(e=>(0,Q.jsxs)(`label`,{className:`flex items-center gap-1.5 cursor-pointer select-none`,children:[(0,Q.jsx)(`input`,{type:`checkbox`,className:`rounded border-mono-600 bg-mono-800`,checked:s.includes(e.value),onChange:()=>v(e.value)}),(0,Q.jsx)(`span`,{className:`text-label-14 text-neutral`,children:e.label})]},e.value))})]}),d&&(0,Q.jsx)(`p`,{className:`text-negative-400 text-copy-14`,children:d}),(0,Q.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!1),f(null)},children:`Cancel`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,disabled:l||!a.trim()||s.length===0,onClick:Mi(y),children:l?`Adding…`:`Add webhook`})]})]}),t===`loading`&&(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`Loading…`}),t!==`loading`&&t.length===0&&!r&&(0,Q.jsx)(rs,{className:`surface-card compact-card`,children:(0,Q.jsx)(`p`,{className:`supporting-copy`,children:`No webhooks configured. Add one to get alerted when citations change or runs complete.`})}),t!==`loading`&&t.length>0&&(0,Q.jsxs)(`div`,{className:`evidence-table-wrap`,children:[(0,Q.jsxs)(`table`,{className:`evidence-table`,children:[(0,Q.jsx)(`thead`,{children:(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`th`,{children:`Endpoint`}),(0,Q.jsx)(`th`,{children:`Events`}),(0,Q.jsx)(`th`,{children:`Status`}),(0,Q.jsx)(`th`,{})]})}),(0,Q.jsx)(`tbody`,{children:t.map(e=>(0,Q.jsxs)(`tr`,{children:[(0,Q.jsx)(`td`,{className:`evidence-query-cell`,children:(0,Q.jsx)(`span`,{className:`text-label-12-mono text-neutral break-all`,title:e.urlHost,children:e.urlDisplay??e.url})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.events.map(e=>(0,Q.jsx)(`span`,{className:`inline-flex items-center rounded-full border border-strong bg-surface-inset px-2 py-0.5 text-label-12-strong text-secondary normal-case`,children:e.replace(`.`,` `)},e))})}),(0,Q.jsx)(`td`,{children:(0,Q.jsx)(Y,{tone:e.enabled?`positive`:`neutral`,children:e.enabled?`Active`:`Paused`})}),(0,Q.jsx)(`td`,{children:(0,Q.jsxs)(`div`,{className:`flex items-center gap-1 justify-end`,children:[p[e.id]&&(()=>{let t=p[e.id],n=t.state===`testing`?`Sending…`:t.state===`ok`?`Delivered${t.status?` (${t.status})`:``}`:`Failed${t.status?` (${t.status})`:``}`;return(0,Q.jsx)(Y,{tone:t.state===`ok`?`positive`:t.state===`fail`?`negative`:`neutral`,children:n})})(),_&&(0,Q.jsx)(J,{variant:`ghost`,size:`sm`,type:`button`,disabled:p[e.id]?.state===`testing`,onClick:()=>{x(e.id)},children:`Test`}),_&&(0,Q.jsx)(J,{variant:`ghost`,size:`sm`,type:`button`,disabled:h.has(e.id),onClick:()=>{b(e.id)},children:h.has(e.id)?`Removing…`:`Remove`})]})})]},e.id))})]}),d&&(0,Q.jsx)(`p`,{className:`text-negative-400 text-copy-14 mt-2`,children:d})]})]})}var lD=e({COMPETITOR_COMPARISON_COPY:()=>vD,ProjectPage:()=>xD,ProjectSubnav:()=>CD,ProjectSweepConfirmation:()=>uD,patchProjectDashboardCache:()=>mD,projectSectionTabs:()=>SD});function uD({open:e,projectLabel:t,onOpenChange:n,onConfirm:r,onClosed:i,disabled:a,leftOut:o=[],preview:s,previewPending:c=!1,previewFailed:l=!1,onRetryPreview:u=()=>{}}){return G()||mt()?null:(0,Q.jsx)(I,{open:e,onOpenChange:n,children:(0,Q.jsxs)(N,{children:[(0,Q.jsx)(j,{className:`fixed inset-0 z-50 bg-overlay-scrim/70 backdrop-blur-sm`}),(0,Q.jsxs)(P,{className:`material-modal fixed left-1/2 top-1/2 z-50 max-h-[85dvh] w-[calc(100%-2rem)] max-w-xl -translate-x-1/2 -translate-y-1/2 overflow-y-auto p-5`,onCloseAutoFocus:e=>{i&&(e.preventDefault(),i())},children:[(0,Q.jsxs)(`div`,{className:`space-y-2`,children:[(0,Q.jsx)(F,{className:`text-heading-20 text-heading`,children:`Review AI Visibility check`}),(0,Q.jsxs)(M,{className:`text-copy-14 text-secondary`,children:[`Checks `,t,` using the scope below. View filters do not limit the check. Provider charges apply.`,o.length>0?` ${o.map(e=>fr(e)).join(` and `)} ${o.length===1?`is`:`are`} left out: ${o.length===1?`it keeps failing on its account`:`they keep failing on their accounts`}.`:null]})]}),(0,Q.jsx)(`div`,{className:`mt-5`,children:(0,Q.jsx)(Ns,{preview:s,pending:c,failed:l,onRetry:u})}),(0,Q.jsx)(`p`,{className:`mt-4 text-copy-13 text-secondary`,children:`Runs once. Your schedule stays unchanged.`}),(0,Q.jsxs)(`div`,{className:`mt-6 flex flex-wrap gap-3`,children:[(0,Q.jsx)(J,{variant:`outline`,onClick:()=>n(!1),children:`Cancel`}),(0,Q.jsx)(Rr,{disabled:a||c||l||s?.canStart!==!0,onClick:r,children:`Run project-wide check`})]})]})]})})}var dD=2e3,fD=3e5;function pD(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function mD(e,t){e.setQueriesData({predicate:e=>e.queryKey[0]===`project-dashboard-full`&&e.queryKey[1]===t.id},e=>!e||typeof e!=`object`||!(`project`in e)?e:{...e,project:t})}function hD({projectName:e}){let t=(0,Z.useId)(),n=R(),[r,i]=(0,Z.useState)(`google`),[a,o]=(0,Z.useState)(!0),[s,c]=(0,Z.useState)(`idle`),[l,u]=(0,Z.useState)(null),d=(0,Z.useRef)(null),[f,p]=(0,Z.useState)(null),[m,h]=(0,Z.useState)(null),[_,v]=(0,Z.useState)(0);async function y(t=!1){t||o(!0),u(null);try{let[t,r]=await Promise.all([n.fetchQuery({...so({client:q,path:{name:e}}),staleTime:Fi}).catch(()=>[]),n.fetchQuery({...vo({client:q,path:{name:e}}),staleTime:Fi}).catch(()=>null)]),i=t.find(e=>e.connectionType===`gsc`)??null;p(i),h(r)}catch(e){u(e instanceof Error?e.message:`Failed to load search engine connections`)}finally{o(!1)}}async function b(){if(s!==`idle`)return;d.current?.abort();let t=new AbortController;d.current=t;let r=t.signal;c(`syncing`),u(null),Ni({title:`Refreshing search coverage`,detail:`Queueing Google and Bing checks, then reloading the workspaces.`,tone:`neutral`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`});let i=[],a=[];try{async function t(){if(!f)return;let t=await sn(e);if(!t?.id)return;let n=Date.now()+fD;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,dD)),r.aborted))return;let e=await St(t.id).catch(()=>null);if(!e)break;if([`completed`,`failed`,`cancelled`].includes(e.status)){e.status!==`completed`&&i.push(`Google sync ${e.status}`);return}}a.push(`Google sync is still running — search data will appear shortly`)}async function o(){if(!m?.connected)return;let t=await Nt(e).catch(()=>null);if(!t?.id){i.push(`Bing check could not be started`);return}let n=Date.now()+fD;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,dD)),r.aborted))return;let e=await St(t.id).catch(()=>null);if(!e)break;if([`completed`,`failed`,`cancelled`,`partial`].includes(e.status)){e.status===`failed`?i.push(`Bing check failed`):e.status===`partial`&&a.push(`Bing check finished with some pages unverified`);return}}a.push(`Bing check is still running. Coverage will update shortly.`)}async function s(){if(!m?.connected||!m.siteUrl)return;let t=await Zt(e).catch(()=>null);if(!t?.id){i.push(`Bing data sync could not be started`);return}let n=Date.now()+fD;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,dD)),r.aborted))return;let e=await St(t.id).catch(()=>null);if(!e)break;if([`completed`,`failed`,`cancelled`,`partial`].includes(e.status)){e.status===`failed`?i.push(`Bing data sync failed`):e.status===`partial`&&a.push(`Bing data sync finished with some sections missing`);return}}a.push(`Bing data sync is still running. Search data will update shortly.`)}let l=await Promise.allSettled([t(),o(),s()]);for(let e of l)e.status===`rejected`&&i.push(e.reason instanceof Error?e.reason.message:`Sync failed`);if(await Promise.all([Pi(n,`gsc`),Pi(n,`bing`),Pi(n,`sitemaps`)]),r.aborted)return;if(c(`reloading`),await y(!0),v(e=>e+1),i.length>0){let t=`Partial refresh: ${[...i,...a].join(`; `)}`;u(t),Ni({title:`Search coverage partially refreshed`,detail:t,tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}else a.length>0?Ni({title:`Search coverage refresh incomplete`,detail:a.join(`; `),tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`}):Ni({title:`Search coverage refreshed`,detail:`Google and Bing workspaces are reloaded with the latest stored coverage.`,tone:`positive`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}catch(t){if(!r.aborted){let n=t instanceof Error?t.message:`Refresh failed`;u(n),Ni({title:`Search coverage refresh failed`,detail:n,tone:`negative`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}}finally{r.aborted||c(`idle`)}}return(0,Z.useEffect)(()=>(y(),()=>{d.current?.abort()}),[e]),(0,Q.jsxs)(`div`,{className:`space-y-6`,children:[(0,Q.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,Q.jsx)(Xc,{id:t,label:`Search engine workspaces`,value:r,onChange:i,className:`flex flex-wrap gap-2`,tabClassName:`project-subnav-link`,activeTabClassName:`project-subnav-link-active`,options:[[`google`,`Google`],[`bing`,`Bing`]]}),!G()&&(0,Q.jsxs)(Rr,{type:`button`,variant:`outline`,size:`sm`,"aria-label":`Refresh search data`,disabled:a||s!==`idle`,onClick:()=>void b(),children:[(0,Q.jsx)(g,{className:`h-3.5 w-3.5 ${s===`idle`?``:`animate-spin`}`,"aria-hidden":`true`}),a?`Loading…`:s===`syncing`?`Refreshing search data…`:s===`reloading`?`Reloading workspaces…`:`Refresh search data`]})]}),l&&(0,Q.jsx)(`div`,{className:`rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:l}),(0,Q.jsxs)(`div`,{id:`${t}-panel`,role:`tabpanel`,"aria-labelledby":`${t}-${r}`,tabIndex:0,children:[r===`google`&&(0,Q.jsx)(_d,{projectName:e,refreshNonce:_}),r===`bing`&&(0,Q.jsx)(Id,{projectName:e,refreshNonce:_})]})]})}function gD(e){return e.total-e.citationNotMeasured}function _D({label:e,summary:t,displayValue:n,tooltip:r}){let{figure:i,sign:a}=ii(t.value),o=t.progress===void 0?0:Math.min(Math.max(t.progress,0),100);return(0,Q.jsxs)(`div`,{className:`aeo-hero-row`,children:[(0,Q.jsxs)(`p`,{className:`aeo-hero-row-label`,children:[e,(r||t.tooltip)&&(0,Q.jsx)(X,{text:r||t.tooltip||``})]}),(0,Q.jsx)(`p`,{className:`aeo-hero-row-value ${_c[t.tone]}`,children:n??(0,Q.jsxs)(Q.Fragment,{children:[i,a?(0,Q.jsx)(`span`,{className:`text-faint`,children:a}):null]})}),(0,Q.jsx)(`div`,{className:`aeo-hero-row-bar`,"aria-hidden":`true`,children:(0,Q.jsx)(`div`,{className:`metric-card-bar-fill progress-fill-${t.tone}`,style:{width:`${o}%`}})})]})}var vD={emptyTitle:`No competitors set`,emptyDetail:`Mention and citation gaps need at least one tracked competitor.`,add:`Add competitors`};function yD({id:e,title:t,meta:n,defaultOpen:r=!1,children:i}){let a=(0,Z.useId)(),o=(0,Z.useId)();return(0,Q.jsxs)(`details`,{id:e,className:`overview-disclosure page-section-divider scroll-mt-24`,open:r||void 0,children:[(0,Q.jsxs)(`summary`,{className:`overview-disclosure-summary`,"aria-labelledby":a,"aria-describedby":n?o:void 0,children:[(0,Q.jsx)(`h2`,{id:a,className:`overview-disclosure-title`,children:t}),(0,Q.jsxs)(`span`,{className:`overview-disclosure-meta`,children:[n&&(0,Q.jsx)(`span`,{id:o,children:n}),(0,Q.jsx)(y,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,Q.jsx)(`div`,{className:`overview-disclosure-body`,children:i})]})}function bD({insights:e,suggestedQueries:t,onManageQueries:n,siteDomain:r}){let{openEvidence:i}=oc(),a=n?t.rows:[];if(e.length===0&&a.length===0)return null;let o=e=>(0,Q.jsxs)(`div`,{className:`py-3`,children:[(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.title}),e.detail?(0,Q.jsx)(`p`,{className:`mt-1 max-w-3xl text-copy-14 text-secondary`,children:e.detail}):null]}),(0,Q.jsx)(Y,{tone:e.tone,children:e.actionLabel})]}),e.affectedPhrases.length>0?(0,Q.jsxs)(`details`,{className:`mt-2`,children:[(0,Q.jsxs)(`summary`,{className:`w-fit cursor-pointer text-label-14-strong text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[`Evidence · `,e.affectedPhrases.length,` affected `,e.affectedPhrases.length===1?`query`:`queries`]}),(0,Q.jsx)(`ul`,{className:`mt-2 divide-y divide-subtle border-y border-subtle`,children:e.affectedPhrases.map((t,n)=>(0,Q.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 py-2`,children:[(0,Q.jsx)(Yc,{state:t.citationState,...r&&t.siteCitation!==!1?{label:ni(r,t.citationState)}:{}}),(0,Q.jsx)(`span`,{className:`min-w-0 flex-1 text-label-14 text-strong`,children:t.query}),t.provider?(0,Q.jsx)(os,{provider:t.provider}):null,!G()&&t.evidenceId?(0,Q.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:e=>{e.currentTarget.focus({preventScroll:!0}),i(t.evidenceId)},children:`View evidence`}):null]},t.evidenceId||`${e.id}-${n}`))})]}):null]},e.id),s=e=>(0,Q.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-3`,children:[(0,Q.jsxs)(`div`,{className:`min-w-0`,children:[(0,Q.jsx)(`p`,{className:`text-label-12-strong normal-case text-muted`,children:`Suggested query`}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-strong`,children:e.query}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:e.reason})]}),n?(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Review in Queries`}):null]},e.query),c=e.slice(0,1),l=a.slice(0,1),u=e.slice(1),d=a.slice(1),f=u.length+d.length;return(0,Q.jsxs)(`section`,{className:`visibility-disclosure-panel`,"aria-labelledby":`overview-signals-title`,children:[(0,Q.jsx)(`div`,{className:`section-head`,children:(0,Q.jsx)(`h2`,{id:`overview-signals-title`,children:`Latest signals`})}),(0,Q.jsxs)(`div`,{className:`divide-y divide-default border-y border-default`,children:[c.map(o),l.map(s)]}),f>0?(0,Q.jsxs)(`details`,{className:`mt-2`,children:[(0,Q.jsxs)(`summary`,{className:`w-fit cursor-pointer text-label-14-strong text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[f,` more `,f===1?`signal`:`signals`]}),(0,Q.jsxs)(`div`,{className:`mt-2 divide-y divide-default border-y border-default`,children:[u.map(o),d.map(s)]})]}):null]})}function xD(e){let{projectName:t}=ne({from:`/projects/$projectName`}),n=fc()?.dashboard.projects.find(e=>e.project.name===t||e.project.id===t)?.project.name??null,r=U({...Mo({client:q}),enabled:!n}),i=n??r.data?.find(e=>e.name===t||e.id===t)?.name??null,a=Ht(),o=Ms(e.tab,a),[s,c]=(0,Z.useState)(null),l=i!==null&&s===i,u=(0,Z.useCallback)(()=>{i&&c(i)},[i]),{commandCenter:d,isLoading:f,overviewLoading:p,overviewError:m,isError:h,latestVisibilityRevision:g,competitorHistoryRevision:_,refetch:v}=$s(i,{overview:o===`overview`&&l}),y=!n&&r.isLoading||f;return!i&&!n&&r.isSuccess&&!f?(0,Q.jsx)(`div`,{className:`page-container`,children:(0,Q.jsxs)(rs,{className:`surface-card empty-card`,children:[(0,Q.jsx)(`h1`,{children:`Project not found`}),(0,Q.jsxs)(`p`,{children:[`Could not find a project named "`,t,`".`]}),(0,Q.jsx)(J,{asChild:!0,children:(0,Q.jsx)(H,{to:`/`,children:`Return to overview`})})]})}):!d&&(h||r.isError)?(0,Q.jsxs)(`div`,{className:`page-container`,role:`alert`,children:[(0,Q.jsx)(`p`,{children:`Could not load this project.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{Promise.all([r.refetch(),v()])},children:`Retry`})]}):!d||y?(0,Q.jsxs)(`div`,{className:`page-skeleton`,children:[(0,Q.jsxs)(`div`,{className:`page-skeleton-header`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text h-6 w-48`}),(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-32`})]}),(0,Q.jsx)(`div`,{className:`grid grid-cols-3 gap-4`,children:[1,2,3].map(e=>(0,Q.jsxs)(`div`,{className:`page-skeleton-card flex flex-col items-center`,children:[(0,Q.jsx)(`div`,{className:`skeleton-circle size-20`}),(0,Q.jsx)(`div`,{className:`skeleton-text w-16 mt-3`})]},e))}),(0,Q.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,Q.jsx)(`div`,{className:`skeleton-text w-28`}),(0,Q.jsx)(`div`,{className:`space-y-2 mt-2`,children:[1,2,3,4].map(e=>(0,Q.jsx)(`div`,{className:`skeleton-text-sm w-full`},e))})]})]}):(0,Q.jsx)(DD,{model:d,refetch:v,latestVisibilityRevision:g,competitorHistoryRevision:_,overviewLoading:p,overviewError:m,overviewRequested:l,onRequestOverview:u,...e})}function SD(e,{journeys:t}){return{primary:[{key:`overview`,label:`AI Visibility`,href:e},{key:`queries`,label:`Queries`,href:`${e}/queries`},{key:`search-console`,label:`Search engines`,href:`${e}/search-console`},{key:`seo-data`,label:`SEO`,href:`${e}/seo-data`},{key:`activity`,label:`Activity`,href:`${e}/activity`},{key:`agent-readiness`,label:`Agent Readiness`,href:`${e}/agent-readiness`},...t?[{key:`journeys`,label:`Journeys`,href:`${e}/journeys`}]:[],{key:`traffic`,label:`Server traffic`,href:`${e}/traffic`}],overflow:[{key:`conversions`,label:`Conversions`,href:`${e}/conversions`},{key:`local`,label:`Local presence`,href:`${e}/local`},{key:`backlinks`,label:`Backlinks`,href:`${e}/backlinks`},{key:`history`,label:`Change history`,href:`${e}/history`}]}}function CD({items:e,overflowItems:t,settingsItem:n,activeTab:r}){let i=(0,Z.useRef)(null),a=(0,Z.useRef)(null),[o,s]=(0,Z.useState)(null),{rowItems:c,menuOverflowItems:l}=(0,Z.useMemo)(()=>{let n=t.find(e=>e.key===r);return{rowItems:n?[...e,n]:e,menuOverflowItems:t.filter(e=>e!==n)}},[e,t,r]);(0,Z.useLayoutEffect)(()=>{let e=i.current,t=a.current;if(!e||!t)return;let o=()=>{let i=e.getBoundingClientRect().width;if(!i)return;let a=Number.parseFloat(getComputedStyle(e).columnGap)||0,o=new Map([...t.querySelectorAll(`[data-project-tab]`)].map(e=>[e.dataset.projectTab,e.getBoundingClientRect().width])),u=e=>o.get(e)??0,d=e=>e.reduce((e,t)=>e+u(t),0)+Math.max(0,e.length-1)*a,f=[...c.map(e=>e.key),...l.length?[`more`]:[],...n?[n.key]:[]],p=c.map(e=>e.key),m=!1;if(d(f)>i){let e=c.find(e=>e.key===r),t=e?[e.key]:[];m=!!(n&&n.key!==r&&d([...t,`more`,n.key])>i);let a=[`more`,...n&&!m?[n.key]:[]];for(let n of c)if(n.key!==e?.key){if(d([...t,n.key,...a])>i)break;t.push(n.key)}p=c.filter(e=>t.includes(e.key)).map(e=>e.key)}s(e=>e?.settingsInMore===m&&e.visibleKeys.join()===p.join()?e:{visibleKeys:p,settingsInMore:m})};if(o(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,o),()=>window.removeEventListener(`resize`,o);let u=new ResizeObserver(o);return u.observe(e),u.observe(t),()=>u.disconnect()},[c,l,n,r]);let u=!!o?.settingsInMore&&n?.key!==r,d=o?c.filter(e=>e.key===r||o.visibleKeys.includes(e.key)):c,f=[...c.filter(e=>!d.includes(e)),...l,...u&&n?[n]:[]];return(0,Q.jsxs)(`nav`,{className:`project-subnav`,"aria-label":`Project sections`,ref:i,children:[(0,Q.jsx)(`div`,{className:`project-subnav-measure`,"aria-hidden":`true`,children:(0,Q.jsxs)(`div`,{className:`project-subnav-measure-row`,ref:a,children:[[...c,...n?[n]:[]].map(e=>(0,Q.jsx)(`span`,{className:`project-subnav-link`,"data-project-tab":e.key,children:e.label},e.key)),(0,Q.jsxs)(`span`,{className:`project-subnav-link project-subnav-more-trigger`,"data-project-tab":`more`,children:[`More`,(0,Q.jsx)(y,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]})]})}),d.map(e=>(0,Q.jsx)(H,{to:e.href,search:e=>({...e,onboarding:void 0}),activeOptions:{exact:!0},className:`project-subnav-link ${e.key===r?`project-subnav-link-active project-subnav-current`:``}`,"aria-current":e.key===r?`page`:void 0,children:(0,Q.jsx)(`span`,{className:`project-subnav-label`,children:e.label})},e.key)),(0,Q.jsxs)(`div`,{className:`project-subnav-trailing`,children:[(0,Q.jsx)(wD,{items:f}),n&&!u&&(0,Q.jsx)(H,{to:n.href,search:e=>({...e,onboarding:void 0}),className:`project-subnav-link ${r===`settings`?`project-subnav-link-active`:``}`,"aria-current":r===`settings`?`page`:void 0,children:n.label})]})]})}function wD({items:e}){let[t,n]=(0,Z.useState)(!1),r=(0,Z.useRef)(null),i=(0,Z.useRef)(null),a=(0,Z.useRef)(`first`),o=(0,Z.useId)(),s=e.map(e=>e.key).join();return(0,Z.useEffect)(()=>{n(!1)},[s]),(0,Z.useEffect)(()=>{if(!t)return;let e=r.current?.querySelectorAll(`[role="menuitem"]`);(a.current===`last`?e?.[e.length-1]:e?.[0])?.focus()},[t]),(0,Z.useEffect)(()=>{if(!t)return;let e=e=>{r.current&&!r.current.contains(e.target)&&n(!1)},a=e=>{e.key===`Escape`&&(n(!1),i.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,a),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,a)}},[t]),e.length===0?null:(0,Q.jsxs)(`div`,{className:`project-subnav-more`,ref:r,children:[(0,Q.jsxs)(`button`,{type:`button`,ref:i,className:`project-subnav-link project-subnav-more-trigger`,"aria-haspopup":`menu`,"aria-expanded":t,"aria-controls":t?o:void 0,onClick:()=>{a.current=`first`,n(e=>!e)},onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),a.current=e.key===`ArrowUp`?`last`:`first`,n(!0))},children:[`More`,(0,Q.jsx)(y,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),t?(0,Q.jsx)(`div`,{className:`project-subnav-menu`,role:`menu`,id:o,"aria-label":`More project sections`,onKeyDown:e=>{let t=[...e.currentTarget.querySelectorAll(`[role="menuitem"]`)],n=t.indexOf(document.activeElement),r=e.key===`Home`?0:e.key===`End`?t.length-1:e.key===`ArrowDown`?(n+1)%t.length:e.key===`ArrowUp`?(n-1+t.length)%t.length:null;r!==null&&(e.preventDefault(),t[r]?.focus())},onBlur:e=>{r.current?.contains(e.relatedTarget)||n(!1)},children:e.map(e=>(0,Q.jsx)(H,{to:e.href,search:e=>({...e,onboarding:void 0}),role:`menuitem`,tabIndex:-1,className:`project-subnav-menu-item`,onClick:()=>n(!1),children:e.label},e.key))}):null]})}var TD=20,ED=5;function DD({tab:e,model:t,refetch:n,latestVisibilityRevision:r,competitorHistoryRevision:i,overviewLoading:a,overviewError:o,overviewRequested:s,onRequestOverview:c}){let l=ee(),u=R(),{account:d,canWrite:f,isAdmin:p}=ji(),[m,h]=(0,Z.useState)(null),g=(0,Z.useRef)(null),v=fc(),b=t.project.name,x=v?.dashboard.projects.some(e=>e.project.name===b)??!1,S=te({strict:!1}),C=Bs(S),w=qc(C),T=U({...wa({client:q,path:{name:b}}),enabled:!G()&&!!b&&(f||e===`portfolio`||e===`overview`||e===`settings`||w),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`}),E=v?v.dashboard.settings.providerStatuses.filter(e=>e.state!==`needs-config`).map(e=>vc(e.name)):void 0,D=T.data?.answerVisibilityProviderReady,O=E,k=t.project.providers.map(vc),A=O?.some(e=>k.length===0||k.includes(e))===!0,j=k.length===0||k.includes(`cdp:chatgpt`),M=U({...Io({client:q}),enabled:!G()&&f&&D===void 0&&j&&!A,staleTime:6e4,retry:!1}),N=j?M.isSuccess?typeof M.data.browserVersion==`string`:!M.isError&&void 0:!1,P=D??Us({projectProviders:k,configuredApiProviders:O,cdpConfigured:N}),F=(0,Z.useMemo)(()=>ps(Ht()),[]),I=(0,Z.useMemo)(()=>_s(Ht()),[]),L=(0,Z.useMemo)(()=>Ms(e,Ht()),[e]),ne=(0,Z.useMemo)(()=>t.competitors.map(e=>e.domain),[t.competitors]),V=(0,Z.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.aliases??[]])),[t.competitors]),ie=(0,Z.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.autoAliases??[]])),[t.competitors]),ae=(0,Z.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,[...e.aliases??[],...e.autoAliases??[]]])),[t.competitors]),[oe,se]=(0,Z.useState)(!1),[ce,le]=(0,Z.useState)(!1),ue=ac(),de=(0,Z.useCallback)((e,t)=>{l({to:`.`,search:t=>As(t,e),replace:t?.replace===!0})},[l]),fe=S.queryWorkspace===`research`||L===`discovery`&&S.queryWorkspace===void 0?`research`:`tracked`,pe=Wc(fe,Uc(d?.role,d?.role===`viewer`?Kt():null)),me=U({...xa({client:q,path:{name:b}}),enabled:!G()&&(L===`queries`||L===`discovery`)&&pe===`tracked`}),he=S.manageQueries===!0,ge=(0,Z.useCallback)(()=>{l({to:`.`,replace:!0,search:e=>({...e,siteHealthRunId:void 0})})},[l]),[ve,ye]=(0,Z.useState)(he),[be,xe]=(0,Z.useState)(``),[Se,Ce]=(0,Z.useState)(!1),[we,Te]=(0,Z.useState)(null),[Ee,De]=(0,Z.useState)(`30d`),[W,Oe]=(0,Z.useState)(void 0),[ke,Ae]=(0,Z.useState)(``),[je,Me]=(0,Z.useState)(!1),[Ne,Pe]=(0,Z.useState)(null),[Fe,Ie]=(0,Z.useState)(!1),Le=Rs(S),[Re,ze]=(0,Z.useState)(void 0),[Be,Ve]=(0,Z.useState)(void 0),He=(0,Z.useCallback)(e=>{ze(e.search),e.sort&&Ve(e.sort),l({to:`.`,search:t=>({...t,...zs(e)}),replace:!1})},[l]),[Ue,We]=(0,Z.useState)(!1),Ge=t?.project.displayName||t?.project.name||b,Ke=sc(),qe=hc(b,m===b&&!G()&&!mt()),Je=U({...Wi({client:q,path:{name:b}}),enabled:L===`portfolio`&&!!b,staleTime:0,refetchOnMount:`always`}),Ye=U({...Qo({client:q,path:{name:b}}),enabled:!G()&&!!b&&(f||tt()||L===`portfolio`||L===`overview`||L===`settings`),staleTime:0,refetchOnMount:`always`}),Xe=Ye.data?.active??null,Ze=Ye.data!==void 0,Qe=new Set(Xe&&Number(Xe.plan.schemaVersion)===2?Xe.plan.groups?.map(e=>e.stableKey)??[]:[]),$e={...Le.scope===`group`&&Le.groupKey&&Ze&&!Qe.has(Le.groupKey)?{scope:`all`,queryClass:Le.queryClass}:Le,...Re?{search:Re}:{}},nt=Xe===null?null:Number(Xe.plan.schemaVersion),rt=Xe?.revision??0,K=Ze?`${b}:${rt}`:null,it=(0,Z.useRef)(null);(0,Z.useEffect)(()=>{let e=it.current;K!==null&&(it.current=K),is(e,K)&&(He({scope:`all`,queryClass:`all`}),We(!1))},[K,He]);let at={client:q,path:{name:b},query:{scope:$e.scope,...$e.groupKey?{groupKey:$e.groupKey}:{},queryClass:$e.queryClass,...$e.search?{search:$e.search}:{},...Be?{sort:Be}:{},limit:50}},ot=B({...qo(at),enabled:!1,initialPageParam:at,getNextPageParam:(e,t)=>{if(!e.properties.nextCursor)return;let n=t[0]?.measurement.displayedRunId;return{path:at.path,query:{...at.query,cursor:e.properties.nextCursor,...n?{runId:n}:{}}}},placeholderData:z,staleTime:0,refetchOnMount:`always`}),lt=ot.data?.pages[0]?.measurement.displayedRunId,ut=U({...Qi({client:q,path:{name:b},query:{revision:rt,...lt?{runId:lt}:{}}}),enabled:L===`overview`&&!!b&&Xe!==null&&nt===1,staleTime:0,refetchOnMount:`always`}),dt=Ye.data!==void 0,ft=Je.data!==void 0,pt=Ye.isPending&&!dt,ht=Ye.isError&&!dt,gt=Je.isPending&&!ft,_t=Je.isError&&!ft,yt=ut.data!==void 0,bt=UE({activePlanSchemaVersion:T.data?.activeSchemaVersion??nt,hasDraft:T.data?.draft!==null&&T.data?.draft!==void 0}),xt=bt.surface===`simple-overview`,St=tt()&&Xe?.plan.schemaVersion===2?WE(Xe.plan):null,wt=T.data===void 0&&Ye.data===void 0&&(Ye.isLoading||T.isLoading);(0,Z.useEffect)(()=>{L===`overview`&&xt&&!wt&&c()},[wt,xt,c,L]);let Tt=Jc({tab:L,surface:wt?`unresolved`:bt.surface,embedded:G(),scoped:w,queryWorkspace:pe,tracking:me.isError?{state:`error`}:me.data?{state:`ready`,mode:me.data.mode,scopeUnavailable:Gc(me.data,C)}:{state:`pending`}}),Et=Ig(b,C,{enabled:Tt.kind===`report-picker`}),Dt=L===`overview`&&xt&&!wt,kt=$s(b,{evidence:Dt}),At=kt.commandCenter?.visibilityEvidence??t.visibilityEvidence,jt=(0,Z.useMemo)(()=>{let e=new Map(At.map(e=>[st(e.query),e.queryClass??null])),n=Pn(nn(t.project));return t=>{let r=e.get(st(t));return r===void 0?n?.classify(t)??null:r}},[At,t.project]),Mt=(0,Z.useMemo)(()=>[...new Set([...At.map(e=>e.query),...t.movementComparison.addedQueries,...t.movementComparison.removedQueries])],[At,t.movementComparison]),Nt=(0,Z.useMemo)(()=>{if(!Pn(nn(t.project)))return!1;let e=new Set(At.map(e=>jt(e.query)));return e.has(`branded`)&&e.has(`non-brand`)},[t.project,At,jt]),Pt=(0,Z.useMemo)(()=>t.visibilitySweeps.map(e=>e.createdAt),[t.visibilitySweeps]),Ft=f&&!G()&&!mt()&&L!==`overview`,Lt=U({...Wi({client:q,path:{name:b}}),enabled:Ft,staleTime:Ii,refetchOnWindowFocus:`always`}),Rt=nt===2&&C.measurementScope===`group`?C.measurementScopeKey:void 0,Bt=nt===2&&C.measurementScope===`project`,Vt=(0,Z.useMemo)(()=>{if(Xe?.plan.schemaVersion===2&&Rt)return Xe.plan.groups.find(e=>e.stableKey===Rt)},[Xe,Rt]),Ut={client:q,path:{name:b},query:{window:Ee,queryClass:nt===2&&C.queryClass!==`unknown`?C.queryClass:`non-brand`,...Rt?{groupKey:Rt}:{},...Bt?{scope:`all-markets`}:{}}},Wt=L===`overview`&&!C.marketKey&&!!b&&(xt||Ze)&&!wt&&(xt||(C.measurementScope===`project`||nt===2&&C.measurementScope===`group`)&&C.queryClass!==`unknown`&&(nt===2||C.queryClass!==`branded`)),[Gt,qt]=(0,Z.useState)(null);(0,Z.useEffect)(()=>{Wt||qt(null)},[Wt]),(0,Z.useEffect)(()=>{qt(null)},[b]);let Jt=Gt===b,Yt=(0,Z.useRef)(null),[Xt,Zt]=(0,Z.useState)(!1);(0,Z.useEffect)(()=>{Xt&&Jt&&(Zt(!1),Yt.current?.querySelector(`:scope > summary`)?.focus())},[Xt,Jt]);let Qt=(0,Z.useId)(),$t=(0,Z.useId)(),en=Wt&&Jt,tn=U({...$o(Ut),enabled:en,staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`});Hs(b,JSON.stringify([i,t.competitors.map(e=>`${e.domain}=${[...e.aliases??[],...e.autoAliases??[]].join(`|`)}`).sort(),t.project.canonicalDomain,t.project.ownedDomains,t.project.aliases,t.project.displayName,rt,T.data?.draft?.etag??null]),en);let rn=tn.isError?tn.data===void 0?`Could not load competitors over time. Your pinned competitors remain available.`:`Could not refresh competitors over time. Showing the last available data.`:void 0,an=(0,Z.useMemo)(()=>t.competitors.map(e=>({domain:e.domain,label:e.domain,surfaceClass:`direct-competitor`,pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:e.citationCount,answeredResults:e.totalQueries,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})),[t.competitors]),on=(0,Z.useMemo)(()=>{if(Xe?.plan.schemaVersion!==2)return an;let e=Rt?Vt?.competitors??[]:Xe.plan.groups.flatMap(e=>e.competitors),t=new Map;for(let n of e){let e=n.domain.trim().toLowerCase();e&&!t.has(e)&&t.set(e,{domain:n.domain,label:n.label,surfaceClass:`direct-competitor`,pinned:!0,mentionCount:0,shareOfVoice:null,citationCount:0,answeredResults:0,firstSeenAt:null,lastSeenAt:null,sampleUrls:[]})}for(let e of an){let n=e.domain.trim().toLowerCase();n&&!t.has(n)&&t.set(n,e)}return[...t.values()]},[Xe,Rt,an,Vt]),sn=nt===2?on:an,cn=re({...Ca({client:q}),meta:{skipGlobalErrorToast:!0}}),ln=T.data===void 0?T.isError?`error`:`pending`:`success`,dn=(0,Z.useMemo)(()=>{let e=ot.data?.pages;return e?!Dc(e):!1},[ot.data]),fn=(0,Z.useMemo)(()=>{let e=ot.data?.pages,t=e?.[0],n=e?.at(-1);if(t&&n&&!dn)return{...t,properties:{...t.properties,items:e.flatMap(e=>e.properties.items),nextCursor:n.properties.nextCursor}}},[dn,ot.data]),pn=(0,Z.useMemo)(()=>{if(Xe)return Xe.plan.schemaVersion===1?ut.data?eD(Xe,ut.data):void 0:fn?Cc({overview:fn,activePlan:Xe,sort:Be,report:ut.data,reportState:fn.measurement.displayedRunId===void 0?`ready`:ut.isFetching&&ut.data===void 0?`loading`:ut.isError&&ut.data===void 0?`error`:ut.data?`ready`:`loading`}):void 0},[Xe,ut.data,ut.isError,ut.isFetching,fn]),mn=nt===2?dn?`error`:ot.isPending?`loading`:ot.isError&&pn===void 0?`error`:`ready`:ut.isPending&&!yt?`loading`:ut.isError&&!yt?`error`:`ready`,hn=(t?.recentRuns??[]).some(e=>e.kind===Ct[`answer-visibility`]&&(e.status===Ot.running||e.status===Ot.queued)),gn=ss(b,!G()&&!mt(),`manual`).data,_n=ss(b,!G(),`scheduled`).data,vn=gn&&_n&&JSON.stringify(gn)!==JSON.stringify(_n),yn=gn?.refused===!0,bn=gn&&!gn.refused?Object.keys(gn.providers):[],Sn=t.queryCounts.total>0,Cn=(0,Z.useMemo)(()=>(t?.project.locations??[]).map(e=>e.label),[t?.project.locations]),wn=(0,Z.useMemo)(()=>new Set(At.map(e=>e.location??``)),[At]),Tn=wn.has(``),En=(0,Z.useMemo)(()=>[...new Set(At.map(e=>e.query))].sort((e,t)=>e.localeCompare(t)),[At]),Dn=En.length>0||t.queryCounts.total>0||(Lt.data?.length??0)>0,On=T.data?.requiresPublication===!0,kn=Dn||Xe!==null,An=f&&!kn&&(Ye.data===void 0&&Ye.isPending||Lt.isLoading||Dt&&kt.evidenceLoading),jn=f&&(T.isError&&!T.isFetching||Ft&&Lt.isError&&!Lt.isFetching),Mn=f&&!jn&&(An||P===void 0||T.isFetching),Nn=!Mn&&!jn&&kn&&!On&&P===!0,Fn=f&&!Mn&&!Nn,In=!G()&&L===`overview`&&Fn&&!kn,Ln=U({...fo({client:q,path:{name:b},query:{limit:TD}}),enabled:In&&!!b,retry:!1}),Rn=Ln.isSuccess&&Ln.data.scans.some(e=>e.status===`completed`||e.status===`partial`),zn=In&&Ln.isSuccess&&!Rn,Bn=In&&Rn,Vn=U({...Ba({client:q,path:{name:b}}),enabled:!G()&&!mt()&&!!b,retry:!1}).data?.find(e=>e.kind===Ct[`answer-visibility`]),Hn=Vn?.enabled&&Vn.nextRunAt?uc(Vn.nextRunAt,Vn.timezone):null,Un=Hn?`Next AI Visibility check ${Hn}`:null,Wn=(0,Z.useMemo)(()=>{let e=[...wn].filter(Boolean);return e.length>1?e:Cn},[wn,Cn]);(0,Z.useEffect)(()=>{!Dt||W===void 0||W===``||!b?(Pe(null),Ie(!1)):(Ie(!0),It(b,W,20).then(e=>{Pe(e),Ie(!1)}).catch(()=>{Pe(null),Ie(!1)}))},[W,b,Dt]);let Gn=(0,Z.useMemo)(()=>{if(!Ne)return null;let e=new Map;for(let t of Ne){for(let[n,r]of Object.entries(t.providerRuns??{}))e.set(`${t.query}::${n}`,r.map(e=>({runId:e.runId,citationState:e.citationState,createdAt:e.createdAt,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:e.visibilityTransition,mentionState:e.mentionState,mentionTransition:e.mentionTransition})));(!t.providerRuns||Object.keys(t.providerRuns).length===0)&&e.set(`${t.query}::`,t.runs.map(e=>({runId:e.runId,citationState:e.citationState,createdAt:e.createdAt,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:e.visibilityTransition,mentionState:e.mentionState,mentionTransition:e.mentionTransition})))}return e},[Ne]),Y=(0,Z.useMemo)(()=>{let e=W===void 0?At:At.filter(e=>W===``?!e.location:e.location===W);return Gn?e.map(e=>{let t=Gn.get(`${e.query}::${e.provider}`)??Gn.get(`${e.query}::`);return t?{...e,runHistory:t}:e}):e},[At,W,Gn]);async function Kn(){if(!(qe.isError||qe.isFetching||qe.data?.canStart!==!0||m!==b||!f||G()||mt()||Ke.isPending||hn||yn||!Nn))try{await Ke.mutateAsync({projectName:b,projectLabel:Ge,sourceAction:`project-run`}),h(null)}catch{}}function qn(){l(On?{to:`/projects/$projectName/portfolio`,params:{projectName:b}}:{to:`/setup`,search:{project:b,track:`ai-visibility`}})}function Jn(){l({to:`/projects/$projectName/agent-readiness`,params:{projectName:b}})}async function Xn(){le(!0);try{await _e(b),Ni({title:`Project deleted`,detail:`${Ge} was removed.`,tone:`positive`,dedupeKey:`project:delete:${b}`,dedupeMode:`drop`}),await l({to:`/`})}catch(e){console.error(`Failed to delete project:`,e)}finally{le(!1)}}async function Zn(){let e=be.split(`
|
|
14
|
+
`).map(e=>e.trim()).filter(Boolean);if(e.length!==0){Ce(!0);try{await Yn(b,e),xe(``)}finally{Ce(!1)}}}async function Qn(e){Te(e);try{await vt(b,[e])}catch(t){Ni({title:`Could not remove query`,detail:t instanceof Error?t.message:`Failed to remove "${e}"`,tone:`negative`,dedupeKey:`query:remove`,dedupeMode:`replace`})}finally{Te(null)}}async function er(e){let t=e.trim();if(!t)return!1;try{return await xn(b,[t]),!0}catch(e){let n=e,r=zt(e);if(r?.reason===`bulk-add-unacknowledged`){let e=typeof r.trackedBefore==`number`?r.trackedBefore:`?`,i=typeof r.trackedAfter==`number`?r.trackedAfter:`?`,a=typeof r.windowHours==`number`?r.windowHours:24;if(window.confirm(`This add would grow tracked competitors from ${e} to ${i} within ${a} hours. Continue?`))try{return await xn(b,[t],{acknowledgeBulkAdd:!0}),!0}catch(e){n=e}}return Ni({title:`Could not add competitor`,detail:n instanceof Error?n.message:`Failed to add ${t}`,tone:`negative`,dedupeKey:`competitor:add`,dedupeMode:`replace`}),!1}}async function tr(e){let n=t.competitors.find(t=>t.domain===e);if(!n)return Ni({title:`Could not remove competitor`,detail:`Could not find ${e} in the tracked competitor list`,tone:`negative`,dedupeKey:`competitor:remove`,dedupeMode:`replace`}),!1;try{return await ct(b,n.id),!0}catch(e){return Ni({title:`Could not remove competitor`,detail:e instanceof Error?e.message:`Failed to remove ${n.domain}`,tone:`negative`,dedupeKey:`competitor:remove`,dedupeMode:`replace`}),!1}}async function nr(e){let t=e.trim();if(!t||!Rt||nt!==2||!f||G()||cn.isPending)return!1;try{let e=await cn.mutateAsync({client:q,path:{name:b},headers:{"Idempotency-Key":pD()},body:{expectedActiveRevision:rt,groupKey:Rt,domain:t}});return Promise.allSettled([T.refetch()]),Ni({title:e.draftCreated?`Competitor added to a market draft`:`Market competitor updated`,detail:`Publish the Advanced Measurement draft before ${t} is used in future market runs.`,tone:`positive`,dedupeKey:`competitor:market-pin:${Rt}:${t}`,dedupeMode:`replace`}),!0}catch(e){return Ni({title:`Could not add market competitor`,detail:e instanceof Error?e.message:`Failed to add ${t} to the market draft.`,tone:`negative`,dedupeKey:`competitor:market-pin:error`,dedupeMode:`replace`}),!1}}async function rr(e,t){let n=await $n(e,t);return u.setQueryData(va({client:q,path:{name:e}}),n),mD(u,n),n}let ir=`/projects/${encodeURIComponent(t.project.name)}`,ar=SD(ir,{journeys:d?.role!==et.viewer}),or=[...ar.primary.filter(e=>xs(e.key,F)),...I===void 0?[]:[{key:`client-queries`,label:`Queries`,href:`${ir}/client-queries`}]],sr=ar.overflow.filter(e=>xs(e.key,F)),cr=f||G()||tt(),lr=cr&&xs(`settings`,F)?{key:`settings`,label:`Settings`,href:`${ir}/settings`}:null;function ur(e){let n=xt?e:(0,Q.jsx)(zg,{projectName:b,selection:C,showUnmeasuredFallback:!Xe&&!Sn&&C.measurementScope===`project`&&C.queryClass===`all`&&!C.provider&&!C.model&&!C.location&&!C.from&&!C.to&&!C.revision&&!C.measurementRunId&&!C.queryKey&&!C.marketKey,onSelectionChange:de,onManageQueries:G()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:b},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:G()?void 0:({id:e,label:t})=>(0,Q.jsx)(H,{to:`/projects/$projectName/properties/$targetKey`,params:{projectName:b,targetKey:e},search:vs,"aria-label":`Property details for ${t}`,className:`inline-flex min-h-11 items-center text-label-14 text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:`Property details`}),trackingChangedAt:G()||mt()?void 0:Xe?.createdAt,nextSweepDate:G()||mt()||hn?void 0:Hn??void 0,fallback:e});if(G())return n;let r=yc(C,xt?`simple`:`advanced`,typeof S.sentimentEvaluationDefinitionId==`string`?S.sentimentEvaluationDefinitionId:void 0);return xt&&(r.location=W===``?`none`:W,r=js(r,Y,ke)),(0,Q.jsx)(fs,{hasSourceEvidence:!xt||!!(r.runId||r.runIds?.length),evidenceReady:!xt||!(kt.isLoading||kt.evidenceLoading||kt.evidenceError),waitForResolvedRun:!xt,projectName:b,runOptions:t.visibilitySweeps.slice(0,ED).map(e=>({id:e.id,label:vi(e.finishedAt??e.createdAt)})),selection:r,children:n})}function dr(){switch(Tt.kind){case`report-picker`:{if(Et.error)return un(zt(Et.error))?(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:Hc.savedScopeUnavailable}):null;let e=Et.data;if(!e)return(0,Q.jsx)(`div`,{className:`skeleton-text h-11 w-56`,role:`status`,"aria-label":`Loading measurement scope`});if(e.selection.availability.state!==`available`||e.scopeOptions.length<=1)return null;let t=Kc(e.scopeOptions,C)??e.selection.scope;return(0,Q.jsx)(Tc,{labelVisibility:`sr-only`,options:e.scopeOptions,selected:t,marketKey:C.marketKey,onSelect:(e,t)=>de({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id,measurementMarketKey:t})})}case`tracking-picker`:{let e=me.data?.scopeOptions??[],t=Kc(e,C);return t?(0,Q.jsx)(Tc,{labelVisibility:`sr-only`,options:e,selected:t,onSelect:e=>de({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id})}):null}case`scope-unavailable`:return(0,Q.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:Hc.savedScopeUnavailable});case`project-wide`:return(0,Q.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,Q.jsx)(`span`,{className:`text-label-13 text-secondary`,children:Hc.projectWide}),(0,Q.jsx)(X,{text:Hc.projectWideHelp})]});case`none`:return null}}let fr=L===`overview`&&!xt&&(C.from||C.to)?`${C.from?.slice(0,10)??`First measurement`} to ${C.to?.slice(0,10)??`Latest measurement`}`:null,pr=dr(),mr=Wt?(0,Q.jsx)(El,{window:Ee,landscape:tn.data,pinnedFallback:sn,competitorAliases:V,competitorAutoAliases:ie,canWrite:f,isEmbed:G(),onWindowChange:De,onPin:Rt&&f&&!G()?nr:!Bt&&f&&!G()?er:void 0,onUnpin:Rt||Bt||!f||G()?void 0:tr,onAddCompetitor:Rt&&f&&!G()?nr:!Bt&&f&&!G()?er:void 0,error:rn,onRetry:en?()=>{tn.refetch()}:void 0,isLoading:en&&tn.isPending&&tn.data===void 0,scopeLabel:Rt?`${Vt?.label??Rt} group`:Bt?`All markets`:`Project-wide`,advancedPortfolio:!xt}):null,hr=G()?null:(0,Q.jsx)(Q.Fragment,{children:(0,Q.jsx)(Rr,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ye(!ve),children:ve?`Done`:`Manage queries`})}),gr=!G()&&ve?(0,Q.jsxs)(`div`,{className:`mb-3 material-base p-3`,children:[En.length>0?(0,Q.jsx)(`ul`,{className:`mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto`,children:En.map(e=>(0,Q.jsxs)(`li`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,Q.jsx)(`span`,{className:`min-w-0 truncate text-label-14 text-strong`,title:e,children:e}),(0,Q.jsx)(`button`,{type:`button`,className:`shrink-0 rounded px-1.5 py-0.5 text-button-14 text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50`,"aria-label":`Remove query ${e}`,title:`Stop tracking "${e}"`,disabled:we!==null,onClick:()=>{Qn(e)},children:we===e?`Removing…`:`Remove`})]},e))}):(0,Q.jsx)(`p`,{className:`mb-3 text-copy-13 text-muted`,children:`No queries tracked yet. Add some below.`}),(0,Q.jsx)(`textarea`,{className:`w-full resize-none rounded border border-strong bg-transparent px-2 py-1.5 text-copy-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,rows:3,placeholder:`Enter queries to add, one per line`,value:be,onChange:e=>xe(e.target.value)}),(0,Q.jsxs)(`div`,{className:`mt-2 flex items-center justify-between`,children:[(0,Q.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[be.split(`
|
|
15
|
+
`).filter(e=>e.trim()).length,` to add`]}),(0,Q.jsx)(Rr,{type:`button`,size:`sm`,disabled:!be.trim()||Se,onClick:Mi(Zn),children:Se?`Adding...`:`Add queries`})]})]}):null;return(0,Q.jsxs)(`div`,{className:`page-container`,children:[G()?(0,Q.jsxs)(`div`,{className:`page-header`,children:[(0,Q.jsxs)(`div`,{className:`page-header-left`,children:[(0,Q.jsx)(`h1`,{className:`page-title`,children:t.project.displayName||t.project.name}),(0,Q.jsxs)(`p`,{className:`page-subtitle`,children:[t.project.canonicalDomain,` · `,t.contextLabel]})]}),(0,Q.jsx)(`div`,{className:mt()?`page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end`:`page-header-right`,children:fr===null?null:(0,Q.jsx)(`p`,{className:`text-copy-14 text-muted`,children:fr})})]}):(0,Q.jsxs)(`div`,{className:`project-context-row`,children:[(0,Q.jsx)(`h1`,{className:`project-context-title md:sr-only`,children:t.project.displayName||t.project.name}),pr===null?null:(0,Q.jsx)(`div`,{className:`project-context-scope`,children:pr}),t.project.canonicalDomain?(0,Q.jsx)(`span`,{className:`project-context-domain`,children:t.project.canonicalDomain}):null,St===null?null:(0,Q.jsxs)(`span`,{className:`project-mode-tag`,children:[(0,Q.jsx)(`span`,{className:`project-mode-tag-label`,children:`Advanced`}),(0,Q.jsx)(`span`,{className:`project-mode-tag-detail`,children:St})]}),(0,Q.jsx)(`div`,{className:`project-context-actions`,"data-project-actions":!0,children:mt()?(0,Q.jsx)(ys,{projectName:b,running:hn,portfolio:!xt}):(0,Q.jsxs)(Q.Fragment,{children:[Un?(0,Q.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Un}):null,zn?(0,Q.jsx)(Rr,{type:`button`,onClick:Jn,children:`Check Agent Readiness`}):Bn?(0,Q.jsx)(Rr,{type:`button`,onClick:Jn,children:`View Agent Readiness score`}):null,L===`agent-readiness`?null:(0,Q.jsx)(Rr,{type:`button`,variant:`outline`,disabled:Ke.isPending||hn||Mn||yn&&!jn&&!Fn,onClick:jn?()=>{Promise.all([T.refetch(),...Ft?[Lt.refetch()]:[]])}:Fn?qn:e=>{g.current=e.currentTarget,h(b)},children:Ke.isPending?`Starting…`:hn?`AI Visibility check running…`:Mn?`Checking AI engines…`:jn?`Retry engine check`:Fn?On?`Review and publish plan`:`Set up AI Visibility`:yn?`AI Visibility checks on hold`:`Run AI Visibility check`})]})})]}),!G()&&!mt()&&(0,Q.jsx)(uD,{open:m===b,projectLabel:Ge,onOpenChange:e=>h(e?b:null),onConfirm:Mi(Kn),onClosed:()=>g.current?.focus(),disabled:Ke.isPending||hn||yn||!Nn,leftOut:bn,preview:qe.data,previewPending:qe.isFetching,previewFailed:qe.isError,onRetryPreview:()=>{qe.refetch()}}),(0,Q.jsx)(CD,{items:or,overflowItems:sr,settingsItem:G()?lr:null,activeTab:L}),L===`portfolio`&&!G()?(0,Q.jsx)(dE,{projectName:b,projectDomain:t.project.canonicalDomain,canEdit:f,queries:Je.data??[],isQueryLoading:gt,isQueryError:_t,onRetryQueries:()=>{Je.refetch()},publishedPlan:Xe,sweepActive:hn,executionProviders:t.project.providers,executionProviderModels:t.project.providerModels,onCreateQueries:async e=>(await ue.mutateAsync({projectName:b,queries:[...e]}),(await Je.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{l({to:`/projects/$projectName`,params:{projectName:b},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([T.refetch(),Ye.refetch()]).finally(()=>{l({to:`/projects/$projectName`,params:{projectName:b}})})}},b):L===`overview`?(0,Q.jsxs)(Q.Fragment,{children:[G()?null:(0,Q.jsxs)(Q.Fragment,{children:[_n?(0,Q.jsx)(gc,{admission:_n,canFix:f&&p,selection:vn||!gn?`scheduled`:void 0}):null,gn&&(vn||!_n)?(0,Q.jsx)(gc,{admission:gn,canFix:f&&p,selection:`manual`}):null]}),wt||xt&&!x&&(!s||a)?(0,Q.jsxs)(`div`,{role:`status`,"aria-live":`polite`,children:[(0,Q.jsx)(`span`,{className:`sr-only`,children:`Loading project overview`}),(0,Q.jsx)(`div`,{className:`h-32 animate-pulse rounded-md bg-surface-subtle`,"aria-hidden":`true`})]}):xt&&o?(0,Q.jsxs)(`div`,{role:`alert`,className:`page-section-divider`,children:[(0,Q.jsx)(`p`,{children:`Could not load AI visibility.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,Q.jsxs)(Q.Fragment,{children:[ht?(0,Q.jsxs)(`div`,{role:`alert`,className:`mb-5 flex flex-wrap items-center gap-3 border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:`Could not check the advanced measurement setup. Existing project-wide results remain available.`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{Ye.refetch()},children:`Retry setup check`})]}):null,ur((0,Q.jsx)(GE,{mode:bt,canEdit:f&&!G()&&!pt&&!ht,simpleOverview:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`section`,{className:`mb-6`,children:(0,Q.jsx)(w_,{projectName:t.project.name,competitorDomains:ne,competitorAliases:ae,analyticsRevision:r,queryTexts:Mt,classifyQuery:jt,sweepTimes:Pt,queryClassSplit:Nt})}),Sn&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`section`,{className:`mb-6`,children:(0,Q.jsxs)(`details`,{className:`av-history`,open:ne.length>0,children:[(0,Q.jsxs)(`summary`,{className:`av-card-head`,"aria-labelledby":Qt,"aria-describedby":$t,children:[(0,Q.jsx)(`h2`,{id:Qt,className:`av-card-title`,children:ne.length>0?`Where competitors are winning`:`Compare competitors`}),(0,Q.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[(0,Q.jsx)(`span`,{id:$t,className:`av-card-meta`,children:`Latest check`}),(0,Q.jsx)(y,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,Q.jsxs)(`div`,{className:`competitive-summary`,children:[(0,Q.jsx)(rl,{summary:t.mentionShareSummary,projectLabel:t.project.displayName||t.project.name,competitorDomains:ne},t.project.name),ne.length>0?(0,Q.jsxs)(`div`,{className:`competitive-gaps`,children:[(0,Q.jsx)(`p`,{className:`competitive-gaps-scope`,children:`All queries`}),(0,Q.jsxs)(`div`,{className:`aeo-hero-rows`,children:[(0,Q.jsx)(_D,{label:`Mention gaps`,summary:t.mentionGaps,displayValue:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`text-primary`,children:t.mentionGaps.value}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` / `,t.queryCounts.total]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:` queries, all queries`})]}),tooltip:`Across all queries, branded and non-brand: a competitor was mentioned in an answer and your brand was not mentioned by any engine. The mention-share query type does not filter these counts.`}),(0,Q.jsx)(_D,{label:`Citation gaps`,summary:t.gapQueries,displayValue:gD(t.queryCounts)===0?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`whitespace-nowrap text-label-13 text-secondary`,children:ei.label}),(0,Q.jsx)(`span`,{className:`sr-only`,children:`, all queries`})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(`span`,{className:`text-primary`,children:t.gapQueries.value}),(0,Q.jsxs)(`span`,{className:`text-secondary`,children:[` / `,gD(t.queryCounts)]}),(0,Q.jsx)(`span`,{className:`sr-only`,children:` queries, all queries`})]}),tooltip:`Across all queries, branded and non-brand: a competitor was cited as a source and your domain was not cited by any engine. The mention-share query type does not filter these counts.`})]})]}):(0,Q.jsxs)(`div`,{className:`competitive-gaps`,children:[(0,Q.jsx)(`p`,{className:`text-label-14-strong text-strong`,children:vD.emptyTitle}),(0,Q.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:vD.emptyDetail}),Wt&&f&&!G()?(0,Q.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{qt(b),Zt(!0)},children:vD.add}):null]})]})]})}),(0,Q.jsx)(`div`,{className:`mb-6`,children:(0,Q.jsx)(Gh,{projectName:t.project.name,revision:r})})]}),(0,Q.jsxs)(yD,{id:`evidence-section`,title:`Query evidence`,meta:`${t.queryCounts.total} measured ${t.queryCounts.total===1?`query`:`queries`}`,defaultOpen:!0,children:[t.project.locations.length>0&&(0,Q.jsxs)(`div`,{className:`filter-row mb-3`,role:`toolbar`,"aria-label":`Location filters`,children:[(0,Q.jsx)(`button`,{className:`filter-chip ${W===void 0?`filter-chip-active`:``}`,type:`button`,"aria-pressed":W===void 0,onClick:()=>{Oe(void 0)},children:`All locations`}),t.project.locations.map(e=>(0,Q.jsx)(`button`,{className:`filter-chip ${W===e.label?`filter-chip-active`:``}`,type:`button`,"aria-pressed":W===e.label,onClick:()=>{Oe(e.label),Me(!1)},children:e.label},e.label)),Tn&&(0,Q.jsx)(`button`,{className:`filter-chip ${W===``?`filter-chip-active`:``}`,type:`button`,"aria-pressed":W===``,onClick:()=>{Oe(``),Me(!1)},children:`No location`}),Wn.length>1&&W===void 0&&(0,Q.jsx)(`button`,{className:`filter-chip filter-chip-compare ${je?`filter-chip-active`:``}`,type:`button`,"aria-pressed":je,onClick:()=>Me(e=>!e),title:`Side-by-side location comparison`,children:`Compare`})]}),kt.evidenceLoading||kt.evidenceError?(0,Q.jsxs)(Q.Fragment,{children:[hr&&(0,Q.jsx)(Zl,{actions:hr}),gr,kt.evidenceLoading?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading query evidence…`}):(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-secondary`,children:[(0,Q.jsx)(`p`,{children:`Could not load query evidence.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{kt.refetch()},children:`Retry`})]})]}):(0,Q.jsx)(Ql,{evidence:Y,compareLocations:je,providerSelection:ke,onProviderSelectionChange:Ae,addedQueries:t.movementComparison.addedQueries,actions:hr,actionPanel:gr})]}),!G()&&(0,Q.jsx)(`div`,{className:`page-section-divider`,children:(0,Q.jsx)(qh,{runs:t.recentRuns,projectName:t.project.name,collapsed:!0})})]}),report:pn,reportState:mn,onOpenSetup:G()?void 0:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:b}})},onRetryReport:()=>{nt===2?Promise.all([ot.refetch(),ut.refetch()]):ut.refetch()},onViewChange:e=>{He({scope:e.scope,...e.groupKey?{groupKey:e.groupKey}:{},queryClass:e.queryClass,...e.search?.trim()?{search:e.search.trim()}:{}})},onLoadMore:e=>{e===fn?.properties.nextCursor&&ot.fetchNextPage()},onPropertyExpand:()=>{Ue&&ut.isError&&ut.refetch(),We(!0)},onRetryEvidence:()=>{ut.refetch()},isViewLoading:ot.isPlaceholderData,isLoadingMore:ot.isFetchingNextPage,isLoadMoreError:ot.isFetchNextPageError,viewSearch:$e.search??``},`${b}:${rt}`)),!xt&&C.measurementScope===`project`?(0,Q.jsxs)(`details`,{className:`visibility-disclosure`,onToggle:e=>{e.currentTarget.open&&c()},children:[(0,Q.jsx)(`summary`,{className:`visibility-disclosure-summary`,children:(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Project signals`})}),!s||a?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading project signals…`}):o?(0,Q.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-secondary`,children:[(0,Q.jsx)(`p`,{children:`Could not load project signals.`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,Q.jsx)(bD,{insights:t.insights,suggestedQueries:t.suggestedQueries,siteDomain:t.project.canonicalDomain||void 0,onManageQueries:G()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:b},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0})})}})]},b):null,mr===null?null:(0,Q.jsxs)(`details`,{ref:Yt,className:`visibility-disclosure${xt?` page-section-divider`:``}`,open:Jt,onToggle:e=>qt(e.currentTarget.open?b:null),children:[(0,Q.jsx)(`summary`,{className:`visibility-disclosure-summary`,children:(0,Q.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Competitor history`})}),(0,Q.jsx)(`div`,{className:`visibility-disclosure-panel`,children:mr})]})]})]}):L===`settings`?cr?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(tD,{project:{...t.project,displayName:t.project.displayName??t.project.name,defaultLocation:t.project.defaultLocation??null},onUpdateProject:async(e,t)=>{await rr(e,t)}}),(0,Q.jsx)(Gs,{project:t.project,onSave:async e=>{await rr(t.project.name,e)}}),(0,Q.jsx)(Js,{project:t.project,onSave:async e=>{await rr(t.project.name,{siteAuditMaxPages:e})}},t.project.id),f&&!G()?(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:`Advanced measurement`}),(0,Q.jsx)(`p`,{className:`supporting-copy mt-1 mb-3`,children:`Measure individual properties, locations, or site sections with separate query sets.`}),ln===`pending`?(0,Q.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading setup…`}):ln===`error`?(0,Q.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,Q.jsx)(`span`,{children:`Could not load advanced measurement setup.`}),(0,Q.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{T.refetch()},children:`Retry`})]}):(0,Q.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:b}})},children:HE(bt.setupAction)})]}):null,(0,Q.jsx)(oD,{projectName:t.project.name}),(0,Q.jsx)(cD,{projectName:t.project.name}),f&&!G()?(0,Q.jsxs)(`section`,{className:`page-section-divider`,children:[(0,Q.jsx)(`h2`,{className:`text-heading-20 text-negative-400`,children:`Delete project`}),(0,Q.jsx)(`p`,{className:`supporting-copy mt-1 mb-3`,children:`Permanently deletes this project and all its queries, competitors, runs, and snapshots.`}),oe?(0,Q.jsxs)(rs,{className:`surface-card p-6 bg-negative-soft`,children:[(0,Q.jsx)(`h3`,{className:`text-heading-16 text-negative-400 mb-2`,children:`Delete project?`}),(0,Q.jsxs)(`p`,{className:`text-copy-14 text-secondary mb-4`,children:[`This will permanently delete `,(0,Q.jsx)(`strong`,{className:`text-strong`,children:t.project.displayName||t.project.name}),` and all its queries, competitors, runs, and snapshots. This cannot be undone.`]}),(0,Q.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,Q.jsx)(J,{type:`button`,variant:`destructive`,disabled:ce,onClick:Mi(Xn),children:ce?`Deleting...`:`Yes, delete project`}),(0,Q.jsx)(J,{type:`button`,variant:`outline`,disabled:ce,onClick:()=>se(!1),children:`Cancel`})]})]}):(0,Q.jsxs)(Rr,{type:`button`,variant:`outline`,onClick:()=>se(!0),children:[(0,Q.jsx)(_,{className:`h-4 w-4 text-secondary`}),`Delete project`]})]}):null]}):(0,Q.jsxs)(rs,{className:`surface-card empty-card`,children:[(0,Q.jsx)(`h2`,{children:`Project settings unavailable`}),(0,Q.jsx)(`p`,{children:`Your account has view-only access to this project.`}),(0,Q.jsx)(J,{asChild:!0,children:(0,Q.jsx)(H,{to:`/projects/$projectName`,params:{projectName:b},children:`Return to overview`})})]}):L===`client-queries`&&I!==void 0?(0,Q.jsx)(Kv,{projectName:b,limit:I}):L===`queries`||L===`discovery`?(0,Q.jsx)(G_,{projectName:b,queryWorkspace:fe,onQueryWorkspaceChange:e=>de({queryWorkspace:e,trackingQueryId:void 0}),researchMode:S.researchMode===`test`?`test`:`find`,onResearchModeChange:e=>de({researchMode:e}),selection:C,onSelectionChange:de,trackingQueryId:typeof S.trackingQueryId==`string`?S.trackingQueryId:void 0,onTrackingQueryIdChange:e=>de({trackingQueryId:e}),publishGuard:{sweepActive:hn}}):L===`agent-readiness`?(0,Q.jsx)(AC,{projectName:t.project.name,projectId:t.project.id,initialRunId:S.siteHealthRunId,onReleaseInitialRun:ge}):L===`conversions`?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(zw,{projectName:t.project.name},`${t.project.id}:performance`),(0,Q.jsx)(bw,{projectId:t.project.id,projectName:t.project.name},t.project.id)]}):L===`history`?(0,Q.jsx)(jC,{projectName:t.project.name}):L===`activity`?(0,Q.jsx)(If,{projectName:t.project.name}):L===`traffic`?(0,Q.jsx)(Rc,{projectName:t.project.name}):L===`backlinks`?(0,Q.jsx)(zp,{projectName:t.project.name}):L===`seo-data`?(0,Q.jsx)(hm,{projectName:t.project.name},t.project.id):L===`journeys`?(0,Q.jsx)(Sh,{projectName:t.project.name},t.project.id):L===`local`?(0,Q.jsx)(op,{projectName:t.project.name,projectId:t.project.id}):L===`search-console`?(0,Q.jsx)(hD,{projectName:t.project.name}):null]})}export{vD as COMPETITOR_COMPARISON_COPY,xD as ProjectPage,CD as ProjectSubnav,uD as ProjectSweepConfirmation,Bb as n,mD as patchProjectDashboardCache,SD as projectSectionTabs,$v as r,lD as t};
|