@canonry/canonry 7.89.0 → 7.90.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +12 -0
- package/assets/assets/{AgentSetupPage-BU1supL8.js → AgentSetupPage-BSfsbQXZ.js} +1 -1
- package/assets/assets/{AuditHistoryPanel-D7or_J3j.js → AuditHistoryPanel-YrEggsyA.js} +1 -1
- package/assets/assets/{BacklinksPage-SOls3ew4.js → BacklinksPage-vXUxxplH.js} +1 -1
- package/assets/assets/{HistoryPage-LNKtQ6a8.js → HistoryPage-VJ_JQ7R3.js} +1 -1
- package/assets/assets/MeasurementPropertyPage-BHPa2zdE.js +4 -0
- package/assets/assets/ProjectPage-C1AI_aAQ.js +11 -0
- package/assets/assets/{RunsPage-B8zUD2gr.js → RunsPage-DKIktkY1.js} +1 -1
- package/assets/assets/SettingsPage-CTXfqNZs.js +1 -0
- package/assets/assets/SiteHealthSection-CRwvLfHd.js +2 -0
- package/assets/assets/{ToneBadge-DawS8vMp.js → ToneBadge-B3rD6bDF.js} +5 -5
- package/assets/assets/{TrafficPage-DJUqxtrQ.js → TrafficPage-C4R3X5lf.js} +4 -4
- package/assets/assets/{TrafficSourceDetailPage-OVY_L73m.js → TrafficSourceDetailPage-C79eQilP.js} +1 -1
- package/assets/assets/{account-context-DoI9S9qY.js → account-context-GstYbqpX.js} +1 -1
- package/assets/assets/{agent-trust-copy-CZpfPr4M.js → agent-trust-copy-Ca4ys8J2.js} +1 -1
- package/assets/assets/{card-ClURYmZN.js → card-CgdGerYK.js} +1 -1
- package/assets/assets/{format-helpers-CscAFAMJ.js → format-helpers-ByAY4dv0.js} +1 -1
- package/assets/assets/index-DdG9gR0r.js +60 -0
- package/assets/assets/query-client-DjRrRIsq.js +1 -0
- package/assets/assets/react-query-B8JD_K7g.js +1 -0
- package/assets/assets/{react-sigma_core.esm.min-6J0MSvMJ.js → react-sigma_core.esm.min-BoCIEnkF.js} +1 -1
- package/assets/assets/{server-traffic-C-_D6pdo.js → server-traffic-Bt9bexaP.js} +1 -1
- package/assets/assets/{service-C7qDx_qB.js → service-SgtD5EOS.js} +1 -1
- package/assets/index.html +7 -7
- package/dist/{ads-XEW2LBKV.js → ads-6BAITIBY.js} +3 -3
- package/dist/{agent-VYADMMPT.js → agent-BE3D65U4.js} +7 -7
- package/dist/{agent-ask-4G57GM3S.js → agent-ask-TT6BAV2T.js} +3 -3
- package/dist/{agent-conversations-MRKRCXQI.js → agent-conversations-GJDAWU36.js} +3 -3
- package/dist/{agent-journeys-WEUEYRMK.js → agent-journeys-UEL27GNY.js} +3 -3
- package/dist/{agent-memory-YLAOXQQ6.js → agent-memory-PB74OP46.js} +3 -3
- package/dist/{agent-providers-AWKQRJDZ.js → agent-providers-5WFMNRRK.js} +3 -3
- package/dist/{agent-transcript-HXYFVCUD.js → agent-transcript-IAGB3JXG.js} +3 -3
- package/dist/{analytics-5G5G5OJU.js → analytics-5BVE7KUN.js} +3 -3
- package/dist/{apply-FCKZG7A2.js → apply-YJJWQ4JX.js} +3 -3
- package/dist/{backfill-3CTZHCJS.js → backfill-6OLGZIEV.js} +10 -10
- package/dist/{backlinks-Q53JT63C.js → backlinks-4JK26OIO.js} +3 -3
- package/dist/{bing-FOY2UVIM.js → bing-NZYYPB2M.js} +12 -3
- package/dist/{bootstrap-FXIT7LDW.js → bootstrap-6KHK63W3.js} +10 -10
- package/dist/{cdp-WWQW3LIZ.js → cdp-PTXWVX6T.js} +7 -7
- package/dist/{chunk-ZYEWB5BK.js → chunk-2UULABPI.js} +7 -3
- package/dist/{chunk-JLBJEQPV.js → chunk-7ASKZHS4.js} +1 -1
- package/dist/{chunk-S7D2ELTC.js → chunk-7VJJXLRP.js} +3 -3
- package/dist/{chunk-WPTCWNA6.js → chunk-AFYKUX2X.js} +2 -2
- package/dist/{chunk-7522CQ2E.js → chunk-CHTADAEC.js} +4 -4
- package/dist/{chunk-GDEYX6E3.js → chunk-DF4B6OGX.js} +4 -4
- package/dist/{chunk-RE24YYIY.js → chunk-DZO6CATO.js} +4 -4
- package/dist/{chunk-YKLYWVLL.js → chunk-ETIIPSWL.js} +71 -4
- package/dist/{chunk-UIULMWJX.js → chunk-F442MSX2.js} +2 -2
- package/dist/{chunk-TCANF22P.js → chunk-F6WNKKGG.js} +33 -7
- package/dist/{chunk-DPKA5CWK.js → chunk-GKX5F7NX.js} +1 -1
- package/dist/{chunk-X6XFWQCE.js → chunk-HUQDD26S.js} +7 -7
- package/dist/{chunk-4INNOSWU.js → chunk-I7DAEE3L.js} +5 -5
- package/dist/{chunk-5GQ2AGWS.js → chunk-L2MDMZFT.js} +3 -3
- package/dist/{chunk-3H5VURTU.js → chunk-LQWMNDZR.js} +1 -1
- package/dist/{chunk-2BZJ4W27.js → chunk-LTZNUDSI.js} +3 -3
- package/dist/{chunk-EWR25OVQ.js → chunk-N7LRPMWR.js} +2 -2
- package/dist/{chunk-GSNKBXGN.js → chunk-NKGQCCUS.js} +6 -6
- package/dist/{chunk-VL4AZGUA.js → chunk-NPX5SL54.js} +1 -1
- package/dist/{chunk-A6DKZ4KQ.js → chunk-OOVWMWMT.js} +1 -1
- package/dist/{chunk-DX46HM7S.js → chunk-PID3C4B7.js} +1 -1
- package/dist/{chunk-MXGME7NG.js → chunk-Q6EZEVXE.js} +1 -1
- package/dist/{chunk-J7V7TYX7.js → chunk-QLVTMPFW.js} +2 -2
- package/dist/{chunk-MNLQY5WG.js → chunk-QWNDNZJ3.js} +2 -2
- package/dist/{chunk-HSOZSLIZ.js → chunk-SDXMG4VX.js} +1064 -873
- package/dist/{chunk-WHN4RF2Y.js → chunk-T7OH3YPX.js} +395 -362
- package/dist/{chunk-3IC7PRTW.js → chunk-TA4L7U2M.js} +1 -1
- package/dist/{chunk-ZX4TZNP4.js → chunk-UG7TZJIG.js} +1 -1
- package/dist/{chunk-ZEWOPHTA.js → chunk-USHY3SH6.js} +62 -1
- package/dist/{chunk-VBM6T5ZP.js → chunk-WNDBACO7.js} +25 -3
- package/dist/{chunk-WE6FSG7J.js → chunk-WYMBWCG5.js} +3 -1
- package/dist/{chunk-Y35D3ZCH.js → chunk-XCEA5OMI.js} +2 -2
- package/dist/{chunk-KAGMYJYG.js → chunk-YB2GAK32.js} +5 -5
- package/dist/{chunk-IK3PYAQU.js → chunk-YFZHRYCM.js} +94 -21
- package/dist/{chunk-YW2IQEWS.js → chunk-ZV6PMFF4.js} +1 -1
- package/dist/{citations-ZZ6ODCGZ.js → citations-WX4VO6ZI.js} +3 -3
- package/dist/{cli-catalog-HEX47BKL.js → cli-catalog-BTRNR2UP.js} +3 -3
- package/dist/{cli-commands-6OLN355M.js → cli-commands-EXWAMK7Z.js} +7 -7
- package/dist/cli.js +13 -13
- package/dist/{competitor-6MRHORU2.js → competitor-HZRZWCEN.js} +3 -3
- package/dist/{content-S2UOGTLN.js → content-NOZDHI3M.js} +3 -3
- package/dist/{dashboard-J4H3FVKH.js → dashboard-TZLWHXP4.js} +6 -6
- package/dist/{demo-7PJJQMLO.js → demo-2PYBQD47.js} +1 -1
- package/dist/{demo-server-55I5LNNS.js → demo-server-JEQNGMMV.js} +12 -12
- package/dist/{discover-O4NFDHGP.js → discover-A2XFXHOC.js} +3 -3
- package/dist/{discover-eval-PE2MW42B.js → discover-eval-A6SBUYXF.js} +3 -3
- package/dist/{doctor-GT4MMJQJ.js → doctor-GZACELPF.js} +3 -3
- package/dist/{evidence-Z344KVJX.js → evidence-RVFMUWIL.js} +3 -3
- package/dist/{export-cmd-Z6WWLI6H.js → export-cmd-X2TFZGNJ.js} +3 -3
- package/dist/{ga-SXIGAF5F.js → ga-TOT3V67A.js} +3 -3
- package/dist/{gbp-CSLWSEKF.js → gbp-KP4YZU6S.js} +3 -3
- package/dist/{google-EAQJ46AR.js → google-GCFSTV5N.js} +4 -4
- package/dist/{google-marketing-NVKB4NLG.js → google-marketing-ANS65KQN.js} +1 -1
- package/dist/{health-cmd-6IYRMZS3.js → health-cmd-UKMNLU6D.js} +3 -3
- package/dist/{history-KLZI7IKJ.js → history-TWGYSAZZ.js} +3 -3
- package/dist/index.d.ts +395 -37
- package/dist/index.js +25 -25
- package/dist/{init-LFLCM6KJ.js → init-2WZWYSDW.js} +12 -12
- package/dist/{insights-C7NN64E2.js → insights-7IOC7WIR.js} +3 -3
- package/dist/intelligence-service-42Q3OVI5.js +16 -0
- package/dist/{journeys-C34YDOM6.js → journeys-NWKT45PT.js} +3 -3
- package/dist/{keys-4RDLFHXO.js → keys-ZZYZUHUK.js} +3 -3
- package/dist/{keyword-BZEJEYAG.js → keyword-F6EIX5KM.js} +3 -3
- package/dist/{logs-5FPZRSZM.js → logs-B45FXS6E.js} +3 -3
- package/dist/{mcp-574UA5Y3.js → mcp-WPNCNWA5.js} +4 -4
- package/dist/mcp.js +9 -9
- package/dist/{measurement-plan-2H4KHD2Y.js → measurement-plan-QT5HJ3KC.js} +5 -5
- package/dist/{notify-TFXL4CSH.js → notify-Z3LIF3SO.js} +3 -3
- package/dist/{organic-evidence-R55KSYFN.js → organic-evidence-R5TM7XUB.js} +3 -3
- package/dist/{overview-NJTCLHAB.js → overview-6TZHJLQN.js} +4 -4
- package/dist/{project-PV36DZDG.js → project-VMPVOQ2A.js} +3 -3
- package/dist/{query-5SVITJ4K.js → query-EXSH5QP7.js} +3 -3
- package/dist/{research-JSET5FNY.js → research-6R6BEL4X.js} +3 -3
- package/dist/{results-export-5EFMXTPG.js → results-export-ZJRL3ECU.js} +3 -3
- package/dist/{run-NOSOG3YH.js → run-C4VXAJE3.js} +4 -4
- package/dist/{schedule-I3ACQC2C.js → schedule-KC6ETWMO.js} +3 -3
- package/dist/{search-EE53K7J5.js → search-SUR6BEQD.js} +3 -3
- package/dist/{serve-SDU77HVC.js → serve-VVG3VYMU.js} +26 -26
- package/dist/{session-FYZCUPVX.js → session-D42KUKCZ.js} +13 -13
- package/dist/{settings-CEI7EKPO.js → settings-LTCG3D5B.js} +3 -3
- package/dist/sitemaps-YMTZLF5S.js +46 -0
- package/dist/{skills-TRTFFZU3.js → skills-THMG3L64.js} +2 -2
- package/dist/{snapshot-2RXVTDTZ.js → snapshot-ZEVB3EE4.js} +3 -3
- package/dist/{src-DYJHW2HG.js → src-HPVSTXVF.js} +6 -2
- package/dist/{status-2VHBSIRY.js → status-LPCPTWKO.js} +4 -4
- package/dist/{technical-aeo-3OMGT4ZT.js → technical-aeo-J6LNT45B.js} +3 -3
- package/dist/{telemetry-5F4EHGR2.js → telemetry-BPY34GDV.js} +4 -4
- package/dist/{tools-C3IIMXBJ.js → tools-K3G43ESI.js} +11 -11
- package/dist/{traffic-S3VUYBG6.js → traffic-BOIFAPAR.js} +5 -5
- package/dist/{trends-RQ4B2QWA.js → trends-A2MDRSQQ.js} +3 -3
- package/dist/{users-T6OOG5YB.js → users-VJOQODJK.js} +3 -3
- package/dist/{visibility-stats-2O24MQCV.js → visibility-stats-YNMJYASA.js} +3 -3
- package/dist/{wordpress-SDENOBFI.js → wordpress-BWG6D7VH.js} +3 -3
- package/package.json +1 -1
- package/assets/assets/MeasurementPropertyPage-CTZzlHWE.js +0 -4
- package/assets/assets/ProjectPage-D79zuY-M.js +0 -11
- package/assets/assets/SettingsPage-BOQgT_7N.js +0 -1
- package/assets/assets/SiteHealthSection-G3_MShnD.js +0 -2
- package/assets/assets/index-y0Wx0ZWq.js +0 -60
- package/assets/assets/query-client-Dm_GqsTu.js +0 -1
- package/assets/assets/react-query-BwhgbuS1.js +0 -1
- package/dist/intelligence-service-ENI35JFR.js +0 -16
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{A as t,C as n,F as r,H as i,I as a,J as o,T as s,X as c,Z as l,a as u,b as d,c as f,ct as p,i as m,n as h,q as g,s as _,t as v,w as y,z as b}from"./vendor-lucide-Bo69m9KC.js";import{r as x}from"./vendor-markdown-BiRP51B0.js";import{E as S,_ as C,b as w,d as T,f as E,g as D,p as O,r as k,u as A,w as j}from"./vendor-tanstack-tBjrfzKu.js";import{c as M,f as N,i as P,l as F,m as I,o as L,p as R,r as z,s as ee,t as te,u as ne}from"./vendor-recharts-CY6tH-r6.js";import{$i as re,$n as B,$r as ie,A as ae,Ai as oe,Ar as V,B as se,Ct as H,Di as ce,Dr as le,Dt as ue,Ei as de,F as fe,Fi as pe,Fr as me,Ft as he,G as ge,Gi as _e,Gn as U,Gs as ve,Hi as ye,Ht as be,Ii as xe,Ir as Se,It as Ce,J as we,Ji as Te,Jn as Ee,Jr as De,Kn as Oe,Ks as ke,Kt as Ae,Li as je,Lr as W,Lt as Me,Mi as Ne,Mr as Pe,N as Fe,Ni as Ie,Nr as Le,Nt as Re,Oi as ze,On as Be,Or as Ve,P as He,Pr as Ue,Pt as We,Qi as Ge,Qn as Ke,Ri as qe,Rr as Je,Rt as Ye,Tr as Xe,Tt as Ze,U as Qe,Un as $e,Ut as et,V as tt,Vt as G,Wi as nt,Wn as rt,Wt as it,Xn as at,Xr as ot,Yi as st,Yn as ct,Yr as lt,Zi as ut,Zn as dt,Zr as ft,_r as pt,_t as mt,a as ht,ai as gt,an as _t,ar as vt,b as yt,br as bt,c as xt,ci as St,cn as Ct,cr as wt,di as Tt,dr as Et,dt as Dt,er as Ot,f as kt,fr as At,gr as jt,gt as Mt,h as Nt,hr as Pt,ht as Ft,ii as It,ir as Lt,it as Rt,j as zt,ji as Bt,jr as Vt,k as Ht,kn as Ut,kr as Wt,l as Gt,li as Kt,ln as qt,lt as Jt,m as Yt,mr as Xt,mt as K,ni as Zt,nn as Qt,nr as $t,nt as en,o as tn,oi as nn,on as rn,or as an,ot as on,p as sn,pr as cn,qi as ln,qn as un,r as q,ri as dn,rr as fn,rt as pn,s as mn,si as hn,sn as gn,sr as _n,t as J,ta as vn,ti as yn,tr as bn,u as xn,ui as Sn,ut as Cn,vn as wn,vr as Tn,wt as Y,yr as En,yt as Dn,zi as On}from"./ToneBadge-DawS8vMp.js";import{_ as kn,a as An,b as jn,d as Mn,g as Nn,h as Pn,i as Fn,l as In,m as Ln,n as Rn,p as zn,r as Bn,s as Vn,t as Hn,u as Un,v as Wn,y as Gn}from"./format-helpers-CscAFAMJ.js";import{n as Kn,r as qn}from"./account-context-DoI9S9qY.js";import{t as Jn}from"./async-handler-Bj3TnIRw.js";import{a as Yn,d as Xn,l as Zn,n as Qn,o as $n,s as er,t as tr,u as nr}from"./query-client-Dm_GqsTu.js";import{$ as rr,A as ir,An as ar,At as or,B as sr,Bt as cr,C as lr,Cn as ur,Ct as dr,D as fr,Dn as pr,Dt as mr,E as hr,En as gr,Et as _r,F as vr,Fn as yr,Ft as br,G as xr,H as Sr,Ht as Cr,I as wr,In as Tr,It as Er,J as Dr,K as Or,L as kr,Ln as Ar,Lt as jr,M as Mr,Mn as Nr,Mt as Pr,N as Fr,Nn as Ir,Nt as Lr,O as Rr,On as zr,Ot as Br,P as Vr,Pn as Hr,Pt as Ur,Q as Wr,R as Gr,Rt as Kr,S as qr,Sn as Jr,St as Yr,T as Xr,Tn as Zr,Tt as Qr,U as $r,Ut as ei,V as ti,Vt as ni,W as ri,X as ii,Y as ai,Z as oi,_ as si,_n as ci,_t as li,an as ui,at as di,b as fi,bn as pi,c as mi,d as hi,dn as gi,et as _i,f as vi,fn as yi,g as bi,gn as xi,gt as Si,h as Ci,in as wi,it as Ti,j as Ei,jn as Di,jt as Oi,k as ki,kn as Ai,kt as ji,l as Mi,m as Ni,mt as Pi,n as Fi,nt as Ii,o as Li,ot as Ri,p as zi,pt as Bi,q as Vi,r as Hi,s as Ui,st as Wi,t as Gi,tn as Ki,tt as qi,u as Ji,un as Yi,ut as Xi,v as Zi,vt as Qi,w as $i,wn as ea,wt as ta,x as na,xn as ra,xt as ia,y as aa,yt as oa,z as sa,zt as ca}from"./react-query-BwhgbuS1.js";import{_ as la,a as ua,c as da,d as fa,f as pa,g as ma,h as ha,i as ga,l as _a,n as va,o as ya,p as ba,r as xa,s as Sa,t as Ca,u as wa}from"./ChartPrimitives-Cs2iavxU.js";import{t as X}from"./InfoTooltip-CNLlIWeP.js";import{t as Z}from"./card-ClURYmZN.js";import{$t as Ta,A as Ea,At as Da,B as Oa,Bt as ka,C as Aa,Ct as ja,D as Ma,Dt as Na,E as Pa,Et as Fa,F as Ia,Ft as La,G as Ra,Gt as za,H as Ba,Ht as Va,I as Ha,It as Ua,J as Wa,Jt as Ga,K as Ka,Kt as qa,L as Ja,Lt as Ya,M as Xa,Mt as Za,N as Qa,Nt as $a,O as eo,Ot as to,P as no,Pt as ro,Q as io,Qt as ao,Rt as oo,St as so,Tt as co,U as lo,Ut as uo,Vt as fo,W as po,Wt as mo,X as ho,Xt as go,Y as _o,Yt as vo,Z as yo,Zt as bo,_ as xo,_t as So,a as Co,an as wo,at as To,b as Eo,bt as Do,c as Oo,dn as ko,dt as Ao,en as jo,et as Mo,fn as No,ft as Po,gt as Fo,ht as Io,i as Lo,j as Ro,jt as zo,k as Bo,kt as Vo,l as Ho,ln as Uo,lt as Wo,nn as Go,o as Ko,on as qo,ot as Jo,pt as Yo,q as Xo,qt as Zo,r as Qo,rn as $o,rt as es,s as ts,sn as ns,st as rs,tn as is,tt as as,u as os,un as ss,ut as cs,vt as ls,wt as us,x as ds,xt as fs,y as ps,yt as ms,z as hs,zt as gs}from"./index-y0Wx0ZWq.js";import{a as _s,c as vs,d as ys,f as bs,i as xs,l as Ss,o as Cs,p as ws,r as Ts,s as Es,t as Ds,u as Os}from"./SiteHealthSection-G3_MShnD.js";import{t as ks}from"./Hint-uoVNfr0U.js";import{t as As}from"./AuditHistoryPanel-D7or_J3j.js";import{a as js,i as Ms,l as Ns,n as Ps,o as Fs,r as Is,t as Ls}from"./service-C7qDx_qB.js";import{a as Rs,c as zs,d as Bs,s as Vs,t as Hs,u as Us}from"./server-traffic-C-_D6pdo.js";import{i as Ws,n as Gs,r as Ks}from"./agent-trust-copy-CZpfPr4M.js";function qs(e){return e.split(/[?#]/)[0]||`/`}var Js=1e6;function Ys(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/Js);if(n.showTinyAsLessThan&&e>0&&i===r.format(0)){let e=10**-(r.resolvedOptions().maximumFractionDigits??0);return`<${r.format(e)}`}return i}var Q=e(p(),1),Xs={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 Zs(e,t){return e!==`viewer`||t!==null}function Qs(e,t){return e===`research`&&!t?`tracked`:e}function $s(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 ec(e,t){return e.find(e=>e.kind===t.measurementScope&&(e.kind===`project`||e.id===t.measurementScopeKey))}function tc(e){return e.measurementScope!==`project`||e.marketKey!==void 0}function nc(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`technical-aeo`: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 $=x();function rc({state:e,label:t,className:n}){return(0,$.jsx)(J,{tone:ns(e),className:n,children:t??Wn(e)})}var ic=[{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],ac={"non-brand":`Non-brand`,branded:`Branded`,pooled:`All queries`},oc={"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.`},sc=`Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.`;function cc(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:St(e.score,ye.percent),numeric:!0,detail:`${e.projectMentionSnapshots} of ${e.combinedMentionSnapshots} brand mentions`,showRows:!0}:{headline:`Add competitors`,numeric:!1,detail:`you were named in ${e.projectMentionSnapshots} of ${e.snapshotsWithAnswerText} answers`,showRows:!1}}function lc({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,$.jsxs)(`table`,{className:`mention-share-table`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Brand mentions by domain, most mentioned first`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`mention-share-row mention-share-row-head`,children:[(0,$.jsx)(`th`,{scope:`col`,className:`mention-share-row-label`,children:`Domain`}),(0,$.jsx)(`th`,{"aria-hidden":`true`}),(0,$.jsxs)(`th`,{scope:`col`,className:`mention-share-count`,children:[`Mentions`,(0,$.jsx)(X,{text:sc})]}),(0,$.jsx)(`th`,{scope:`col`,className:`mention-share-share`,children:`Share`})]})}),(0,$.jsx)(`tbody`,{className:`mention-share-rows`,children:n.map(e=>(0,$.jsxs)(`tr`,{className:`mention-share-row`,children:[(0,$.jsx)(`th`,{scope:`row`,className:`mention-share-row-label ${e.isYou?`text-heading text-label-14-strong`:`text-secondary`}`,children:e.label}),(0,$.jsx)(`td`,{"aria-hidden":`true`,children:(0,$.jsx)(`div`,{className:`mention-share-bar`,children:(0,$.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,$.jsx)(`td`,{className:`mention-share-count`,children:e.mentions}),(0,$.jsx)(`td`,{className:`mention-share-share`,children:St(e.share)})]},e.label))})]})}function uc({summary:e,projectLabel:t,competitorDomains:n}){let[r,i]=(0,Q.useState)(`non-brand`),a=(0,Q.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=cc(u,{hasCompetitors:n.length>0,unavailable:e.unavailable===!0,noRun:e.breakdown.snapshotsTotal===0&&e.branded.snapshotsTotal===0,otherClassHasData:d.snapshotsTotal>0}),p=Nn(f.headline),m=l===`non-brand`?wo[e.tone]:`text-secondary`;function h(e){let t=ic.findIndex(e=>e.value===c),n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%ic.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+ic.length)%ic.length:e.key===`Home`?n=0:e.key===`End`&&(n=ic.length-1),n!==null&&(e.preventDefault(),i(ic[n].value),e.currentTarget.querySelectorAll(`[role="radio"]`)[n]?.focus())}return(0,$.jsxs)(`div`,{className:`mention-share`,children:[(0,$.jsxs)(`div`,{className:`mention-share-head`,children:[(0,$.jsxs)(`div`,{className:`mention-share-label`,children:[(0,$.jsx)(`h3`,{id:a,className:`mention-share-label-text`,children:`Mention share`}),(0,$.jsx)(X,{text:oc[l]})]}),s?(0,$.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":a,className:`segmented flex-wrap`,onKeyDown:h,children:ic.map(e=>{let t=e.value===c;return(0,$.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,$.jsx)(`span`,{className:`mention-share-class`,children:ac[l]})]}),f.numeric?(0,$.jsxs)(`p`,{className:`mention-share-value ${m}`,children:[p.figure,p.sign?(0,$.jsx)(`span`,{className:`text-faint`,children:p.sign}):null]}):(0,$.jsx)(`p`,{className:`mention-share-value-text`,children:f.headline}),(0,$.jsxs)(`p`,{className:`mention-share-caption`,children:[(0,$.jsx)(`span`,{className:`mention-share-caption-scope`,children:ac[l]}),` · ${f.detail}`]}),o&&(0,$.jsx)(`p`,{className:`mention-share-note`,children:`Set a brand name to split branded from non-brand.`}),f.showRows&&(0,$.jsx)(lc,{breakdown:u,projectLabel:t})]})}function dc({items:e,label:t=`Details`}){return e.length===0?null:(0,$.jsxs)(`details`,{className:`av-details`,children:[(0,$.jsx)(`summary`,{children:t}),(0,$.jsx)(`ul`,{className:`av-details-list`,children:e.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]})}var fc=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],pc={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,all:`all checks`},mc={"non-brand":`Non-brand`,branded:`Branded`,all:`All queries`},hc={"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.`},gc={"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`},_c=`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.`,vc=100;function yc(e){return e?e.evidence.answeredResults>0||e.evidence.sourceResults>0?`measured`:`not-measured`:`unavailable`}function bc(e){return e===`unavailable`?`Unavailable`:`Not measured`}function xc(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 Sc(e,t,n){return e===1?t:n}function Cc(e){let t=e.label.trim(),n=nt(e.domain);return t&&t.toLowerCase()!==e.domain.toLowerCase()&&t.toLowerCase()!==n.toLowerCase()?t:null}function wc({row:e,aliases:t=[],autoAliases:n=[]}){let r=Cc(e),i=[...t.map(e=>({alias:e,auto:!1})),...n.map(e=>({alias:e,auto:!0}))],a=i.length>0?(0,$.jsxs)(`span`,{className:`av-of block`,children:[`Also named`,` `,i.map(({alias:e,auto:t},n)=>(0,$.jsxs)(`span`,{children:[n>0?`, `:``,e,t?(0,$.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,$.jsxs)($.Fragment,{children:[r,` `,(0,$.jsx)(`span`,{className:`av-of`,children:e.domain}),a]}):(0,$.jsxs)($.Fragment,{children:[e.domain,a]})}function Tc(e){let t=Cc(e);return t?`${t} (${e.domain})`:e.domain}function Ec(e,t){return t&&e>=vc?(0,$.jsxs)($.Fragment,{children:[`top `,(0,$.jsx)(`strong`,{children:e})]}):(0,$.jsx)(`strong`,{children:e})}function Dc({action:e,domain:t,mutation:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:r,onClick:()=>{s()},children:[e===`pin`?`Pin`:`Unpin`,` `,(0,$.jsx)(`span`,{className:`sr-only`,children:t})]}),a?(0,$.jsx)(`span`,{role:`alert`,className:`sr-only`,children:a}):null]})}function Oc({urls:e}){return(0,$.jsxs)(`details`,{className:`inline-disclosure text-left text-label-12 text-secondary`,children:[(0,$.jsx)(`summary`,{children:`Source URLs`}),(0,$.jsx)(`ul`,{className:`mt-2 max-w-72 space-y-1 text-label-12-mono`,children:e.map(e=>(0,$.jsx)(`li`,{className:`break-all`,children:e},e))})]})}function kc({count:e,of:t,state:n,toneClass:r}){return n===`measured`?(0,$.jsxs)(`span`,{className:`whitespace-nowrap`,children:[(0,$.jsx)(`span`,{className:`av-n-sm ${r}`,children:e}),` `,(0,$.jsxs)(`span`,{className:`av-of`,children:[`of `,t]})]}):(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:bc(n)})}function Ac({percent:e,state:t,toneClass:n}){if(t!==`measured`||e===null)return(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:t===`measured`?`Not measured`:bc(t)});let{figure:r,sign:i}=Nn(St(e,ye.percent));return(0,$.jsxs)(`span`,{className:`av-n-sm ${n}`,children:[r,i?(0,$.jsx)(`span`,{className:`text-faint`,children:i}):null]})}function jc({rows:e,state:t,named:n,cited:r,onPin:i}){return(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`av-grid av-grid-dense`,"aria-label":`Other competitors seen`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Competitor`}),(0,$.jsx)(`th`,{scope:`col`,children:`Type`}),(0,$.jsx)(`th`,{scope:`col`,children:`Named`}),(0,$.jsx)(`th`,{scope:`col`,children:`Cited`}),(0,$.jsx)(`th`,{scope:`col`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:(0,$.jsx)(wc,{row:e})}),(0,$.jsx)(`td`,{className:`text-label-13 text-secondary`,children:xc(e.surfaceClass)}),(0,$.jsx)(`td`,{children:(0,$.jsx)(kc,{count:e.mentionCount,of:n,state:t,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(kc,{count:e.citationCount,of:r,state:t,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`flex min-w-max items-start gap-2`,children:[t===`measured`&&e.sampleUrls.length>0?(0,$.jsx)(Oc,{urls:e.sampleUrls}):null,i?(0,$.jsx)(Dc,{action:`pin`,domain:e.domain,mutation:i}):null]})})]},e.domain))})]})})}function Mc({onAddCompetitor:e}){let t=(0,Q.useId)(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.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,$.jsxs)(`details`,{className:`inline-disclosure`,children:[(0,$.jsx)(`summary`,{children:`Manage competitors`}),(0,$.jsxs)(`form`,{className:`mt-3 flex flex-wrap items-end gap-2`,onSubmit:e=>{e.preventDefault(),c()},"aria-busy":i,children:[(0,$.jsxs)(`label`,{htmlFor:t,className:`min-w-56 flex-1 text-label-14-strong text-heading`,children:[`Competitor domain`,(0,$.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,$.jsx)(q,{type:`submit`,size:`sm`,className:`min-h-10`,disabled:i||!n.trim(),children:i?`Adding…`:`Add competitor`}),o?(0,$.jsx)(`p`,{role:`alert`,className:`w-full text-copy-14 text-negative`,children:o}):null]})]})}function Nc({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,Q.useId)(),_=a&&!o,v=t?.pinned??n,y=t?.observed??[],b=t?.otherSources??[],x=t?.evidence,S=yc(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?wo[qo(t.project.shareOfVoice)]:`text-primary`,M=e=>_?e.pinned?l?(0,$.jsx)(Dc,{action:`unpin`,domain:e.domain,mutation:l}):null:c?(0,$.jsx)(Dc,{action:`pin`,domain:e.domain,mutation:c}):null:null,N=w.some(e=>M(e)!==null),P=[m,E?mc[E]:null,pc[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: ${gc[t.reason]}`}),t&&T.length>0){let e=T.length;F.push({key:`others`,text:O&&e>=vc?`${vc} or more other competitors seen`:`${e} other ${Sc(e,`competitor`,`competitors`)} seen`})}D>0&&F.push({key:`pending`,text:`${t?.scope.kind===`all-markets`?`Pending publication across markets`:`Pending publication`}: ${D} ${Sc(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:wo.caution});let L=[];if(t&&x){L.push(t.runCount===void 0?(0,$.jsxs)($.Fragment,{children:[`Base: `,(0,$.jsx)(`strong`,{children:x.answeredResults}),` `,Sc(x.answeredResults,`answer`,`answers`)]}):(0,$.jsxs)($.Fragment,{children:[`Base: `,(0,$.jsx)(`strong`,{children:t.runCount}),` `,Sc(t.runCount,`check`,`checks`),`, `,(0,$.jsx)(`strong`,{children:x.answeredResults}),` `,Sc(x.answeredResults,`answer`,`answers`)]})),!t.reason&&S===`measured`&&t.project.shareOfVoice!==null&&L.push((0,$.jsxs)($.Fragment,{children:[`Mention share: you `,(0,$.jsx)(`strong`,{children:t.project.mentionCount}),w.map(e=>(0,$.jsxs)(Q.Fragment,{children:[`, `,e.domain,` `,(0,$.jsx)(`strong`,{children:e.mentionCount})]},e.domain)),` `,`of `,(0,$.jsx)(`strong`,{children:x.mentionCredits}),` `,C?`brand mentions`:`tracked-brand mentions`]})),L.push((0,$.jsxs)($.Fragment,{children:[`Answers with source links: `,(0,$.jsx)(`strong`,{children:x.sourceResults})]})),T.length===0&&L.push(`Other competitors seen: none`),x.missingAnswerTextResults>0&&L.push((0,$.jsxs)($.Fragment,{children:[`No answer text: `,(0,$.jsx)(`strong`,{children:x.missingAnswerTextResults}),` `,Sc(x.missingAnswerTextResults,`answer`,`answers`),`, left out of mention share`]})),x.incompleteSourceResults>0&&L.push((0,$.jsxs)($.Fragment,{children:[`Incomplete source lists: `,(0,$.jsx)(`strong`,{children:x.incompleteSourceResults}),` `,Sc(x.incompleteSourceResults,`answer`,`answers`),`, not counted as misses`]}));let e=x.excludedProbeResults+x.excludedNonCompletedResults;e>0&&L.push((0,$.jsxs)($.Fragment,{children:[`Left out: `,(0,$.jsx)(`strong`,{children:e}),` `,Sc(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,$.jsxs)(`details`,{className:`av-subdetails`,children:[(0,$.jsx)(`summary`,{children:`Sample pages cited`}),(0,$.jsx)(`div`,{className:`av-subdetails-body`,children:R.map(({name:e,row:t})=>(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{children:e}),(0,$.jsx)(`ul`,{className:`space-y-1 text-label-12-mono text-muted`,children:t.sampleUrls.map(e=>(0,$.jsx)(`li`,{className:`break-all`,children:e},e))})]},t.domain))})]})),t&&T.length>0&&L.push((0,$.jsxs)(`details`,{className:`av-subdetails`,children:[(0,$.jsxs)(`summary`,{children:[`Other competitors seen: `,Ec(T.length,O)]}),(0,$.jsx)(`div`,{className:`av-subdetails-body`,children:(0,$.jsx)(jc,{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,$.jsxs)(`details`,{className:`av-subdetails`,children:[(0,$.jsxs)(`summary`,{children:[`Company names in answers: `,e>z.length?(0,$.jsxs)($.Fragment,{children:[`top `,(0,$.jsx)(`strong`,{children:z.length}),` of `,(0,$.jsx)(`strong`,{children:e})]}):(0,$.jsx)(`strong`,{children:z.length})]}),(0,$.jsx)(`ul`,{className:`av-subdetails-body`,children:z.map(e=>(0,$.jsxs)(`li`,{children:[e.name,` · `,e.answerCount,` `,Sc(e.answerCount,`answer`,`answers`)]},e.name))})]}))}return b.length>0&&L.push((0,$.jsxs)(`details`,{className:`av-subdetails`,children:[(0,$.jsxs)(`summary`,{children:[`Other sites cited: `,Ec(b.length,O)]}),(0,$.jsx)(`ul`,{className:`av-subdetails-body`,children:b.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsxs)(`span`,{children:[Tc(e),` · `,xc(e.surfaceClass),` · `,e.citationCount,` `,Sc(e.citationCount,`citation`,`citations`)]}),e.sampleUrls.length>0?(0,$.jsx)(`ul`,{className:`mt-1 space-y-1 text-label-12-mono text-muted`,children:e.sampleUrls.map(e=>(0,$.jsx)(`li`,{className:`break-all`,children:e},e))}):null]},e.domain))})]})),(0,$.jsxs)(`section`,{"aria-labelledby":g,"aria-busy":p,className:`overview-brief`,children:[(0,$.jsxs)(`div`,{className:`av-card-head`,children:[(0,$.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,$.jsx)(`h2`,{id:g,className:`av-card-title`,children:`Competitors over time`}),(0,$.jsx)(X,{text:E?`${hc[E]} ${_c}`:_c})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,$.jsx)(`p`,{className:`av-card-meta`,children:P}),(0,$.jsx)(Io,{label:`Competitors over time window`,className:`flex-wrap`,options:fc,value:e,onChange:s})]})]}),(0,$.jsxs)(`div`,{className:`av-card-body space-y-3`,children:[d?(0,$.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,$.jsx)(`span`,{children:d}),f?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:f,children:`Retry competitors over time`}):null]}):null,p&&!t&&v.length===0?(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,className:`h-24 animate-pulse rounded-md bg-surface`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Loading competitors over time`})}):t||w.length>0?(0,$.jsxs)(`table`,{className:`av-grid av-grid-brands`,"aria-label":`Competitors over time`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Brand`})}),(0,$.jsx)(`th`,{scope:`col`,className:`av-brand-type`,children:`Type`}),(0,$.jsx)(`th`,{scope:`col`,children:`Mention share`}),(0,$.jsx)(`th`,{scope:`col`,children:`Named`}),(0,$.jsx)(`th`,{scope:`col`,children:`Cited`}),N?(0,$.jsx)(`th`,{scope:`col`,className:`av-brand-actions`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})}):null]})}),(0,$.jsxs)(`tbody`,{children:[t?(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:t.project.label.trim()?(0,$.jsxs)($.Fragment,{children:[t.project.label.trim(),` `,(0,$.jsx)(`span`,{className:`av-of`,children:`(you)`})]}):`You`}),(0,$.jsx)(`td`,{className:`av-brand-type text-label-13 text-secondary`,children:`Your brand`}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ac,{percent:t.project.shareOfVoice,state:S,toneClass:j})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(kc,{count:t.project.mentionCount,of:k,state:S,toneClass:j})}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(kc,{count:t.project.citationCount,of:A,state:S,toneClass:j}),h&&S===`measured`?(0,$.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:Pn(t.project.domain,`cited`)}):null]}),N?(0,$.jsx)(`td`,{className:`av-brand-actions`}):null]}):null,w.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:(0,$.jsx)(wc,{row:e,aliases:e.pinned?r[e.domain]:void 0,autoAliases:e.pinned?i[e.domain]:void 0})}),(0,$.jsx)(`td`,{className:`av-brand-type text-label-13 text-secondary`,children:xc(e.surfaceClass)}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ac,{percent:e.shareOfVoice,state:S,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(kc,{count:e.mentionCount,of:k,state:S,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(kc,{count:e.citationCount,of:A,state:S,toneClass:`text-primary`})}),N?(0,$.jsx)(`td`,{className:`av-brand-actions`,children:M(e)}):null]},e.domain))]})]}):null,F.length>0?(0,$.jsx)(`div`,{className:`space-y-1 text-label-13 text-secondary`,children:F.map(e=>(0,$.jsx)(`p`,{className:e.className,children:e.text},e.key))}):null]}),(0,$.jsx)(dc,{items:L}),_&&u?(0,$.jsx)(`div`,{className:`border-t border-subtle px-5 py-3`,children:(0,$.jsx)(Mc,{onAddCompetitor:u})}):null]})}function Pc({history:e,maxDots:t=12,signal:n=`citations`}){let r=e.slice(-t);if(r.length===0)return(0,$.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`,lost:`citation lost`,emerging:`new citation`,pending:`citation pending`},o={cited:`bg-positive-400`,"not-cited":`bg-mono-600`,lost:`bg-negative-400`,emerging:`bg-caution-400 ring-1 ring-caution-300/60`},s={cited:`rounded-full`,"not-cited":`rounded-sm`,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}`:``}`}).join(`; `);return(0,$.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,$.jsx)(`span`,{className:`text-label-12 text-secondary shrink-0`,"aria-hidden":`true`,children:l}):null,(0,$.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,$.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}`:null,n?`model changed`:null,i?`latest run`:null].filter(Boolean).join(` · `)},`${e.runId}:${e.createdAt}`)})}),(0,$.jsxs)(`span`,{className:`text-label-12 shrink-0 text-secondary`,"aria-hidden":`true`,children:[u,` `,(0,$.jsx)(`span`,{children:`latest`})]})]})}function Fc(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`:`not-cited`}))}var Ic=320;function Lc(e){return e===`branded`?`Branded`:e===`non-brand`?`Non-brand`:`Unclassified`}function Rc(e){return e===`non-brand`?0:e===`branded`?1:2}function zc(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 Bc(e){return e.phrase}function Vc(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 Hc(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`lost`:return`Lost`;case`emerging`:return`Emerging`;case`pending`:return`Pending`}}function Uc(e,t){return e.map(e=>Wc(e,t))}function Wc(e,t){return t===`citations`?e:{...e,citationState:Vc(e,t),runHistory:e.runHistory.map(e=>({...e,citationState:Vc(e,t)}))}}function Gc(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`};let i=e[e.length-1].citationState,a=e.length>=2?e[e.length-2].citationState:null,o=i===`cited`||i===`emerging`,s=a===`cited`||a===`emerging`;return i===`lost`||a!==null&&s&&!o?{key:t,label:`Lost ${n}`,tone:`negative`}:i===`emerging`||a!==null&&!s&&o?{key:t,label:`New ${n}`,tone:`positive`}:a===null&&o?{key:t,label:`First ${n}`,tone:`positive`}:o?{key:t,label:t===`mentions`?`Still mentioned`:`Still cited`,tone:`neutral`}:{key:t,label:`No ${n}`,tone:`neutral`}}function Kc(e){let t=Fc(Uc(e,`mentions`)),n=Fc(e);return[Gc(t,`mentions`),Gc(n,`citations`)]}function qc({signal:e}){let t=e.tone===`positive`?`text-positive`:e.tone===`negative`?`text-negative`:e.tone===`pending`?`text-caution`:`text-secondary`;return(0,$.jsx)(`span`,{className:t,children:e.label})}function Jc({items:e}){return(0,$.jsx)(`div`,{className:`query-evidence-signals`,"aria-label":`Latest run mention and citation signals`,children:Kc(e).map(e=>(0,$.jsx)(qc,{signal:e},e.key))})}function Yc({queryClass:e,actions:t}){return(0,$.jsxs)($.Fragment,{children:[t?(0,$.jsx)(`div`,{className:`query-evidence-toolbar`,children:(0,$.jsxs)(`div`,{className:`query-evidence-actions`,children:[!e&&(0,$.jsx)(eo,{}),t]})}):null,e?(0,$.jsx)(Bo,{queryClass:e,manage:!!t}):null]})}function Xc({evidence:e,compareLocations:t=!1,defaultDensity:n=`detailed`,providerSelection:r,onProviderSelectionChange:i,addedQueries:a=[],actions:s,actionPanel:c}){let{openEvidence:l}=io(),u=(0,Q.useId)(),[d,f]=(0,Q.useState)(new Set),p=Xa(),[m,h]=(0,Q.useState)(`mentions`),[g,_]=(0,Q.useState)(n),[v,y]=(0,Q.useState)(`all`),[b,x]=(0,Q.useState)(``),S=r??b,C=e=>{x(e),i?.(e)},w=(0,Q.useMemo)(()=>[...new Set([...e.map(e=>e.provider).filter(Boolean),...S?[S]:[]])].sort(),[e,S]),T=(0,Q.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(Wc(r,m)),s.rawItems.push(r),n.set(o,s)}return[...n.values()].sort((e,t)=>Rc(e.queryClass)-Rc(t.queryClass))},[e,m,t,S]),E=(0,Q.useMemo)(()=>T.filter(e=>v===`all`||(v===`unclassified`?e.queryClass===null:e.queryClass===v)),[T,v]),D=ws({rows:E,getSearchText:Bc}),O=(0,Q.useMemo)(()=>{let e=new Map;for(let t of D.filteredRows){let n=e.get(t.queryClass)??new Set;n.add(t.phrase),e.set(t.queryClass,n)}return e},[D.filteredRows]),k=(0,Q.useMemo)(()=>new Set(a.map(Xe)),[a]),A=p?6:5,j=D.rows.map(e=>e.key),M=j.length>0&&j.every(e=>d.has(e)),N=e=>{f(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},P=m===`mentions`?`mentioned`:`cited`,F=m===`mentions`?`Mention History`:`Citation History`,I=m===`mentions`?`mentioned`:`cited`;return(0,$.jsxs)(`div`,{className:`query-evidence`,children:[(0,$.jsx)(Yc,{queryClass:v,actions:s}),c,(0,$.jsxs)(`div`,{className:`query-evidence-view-row`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(`div`,{className:`query-evidence-tabs`,role:`tablist`,"aria-label":`Citation tracking view`,children:[`mentions`,`citations`].map(e=>(0,$.jsx)(`button`,{id:`${u}-${e}`,type:`button`,role:`tab`,"aria-controls":u,"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(`${u}-${n}`)?.focus()},children:e===`mentions`?`Mentions`:`Citations`},e))}),(0,$.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,$.jsxs)(`div`,{className:`query-evidence-display-controls`,children:[(0,$.jsxs)(`label`,{className:`query-evidence-preview-toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:g===`detailed`,onChange:e=>_(e.target.checked?`detailed`:`compact`)}),`Show answer previews`]}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:j.length===0,onClick:()=>{f(e=>{let t=new Set(e);for(let e of j)M?t.delete(e):t.add(e);return t})},children:M?`Collapse page`:`Expand page`})]})]}),e.length>0||S?(0,$.jsxs)(`div`,{className:`query-evidence-filters`,children:[(0,$.jsx)(Os,{value:D.query,onChange:D.setQuery,label:`Find a query`,placeholder:`Find a query`,className:`query-evidence-search`}),(0,$.jsxs)(`label`,{className:`query-evidence-filter`,children:[(0,$.jsx)(`span`,{className:`sr-only`,children:`Answer engine`}),(0,$.jsxs)(`select`,{value:S,onChange:e=>{C(e.target.value),D.setPage(1)},children:[(0,$.jsx)(`option`,{value:``,children:`All engines`}),w.map(e=>(0,$.jsx)(`option`,{value:e,children:oo(e)},e))]})]}),(0,$.jsxs)(`label`,{className:`query-evidence-filter`,children:[(0,$.jsx)(`span`,{className:`sr-only`,children:`Query class`}),(0,$.jsxs)(`select`,{value:v,onChange:e=>{y(e.target.value),D.setPage(1)},children:[(0,$.jsx)(`option`,{value:`all`,children:`All queries`}),(0,$.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,$.jsx)(`option`,{value:`non-brand`,children:`Non-brand`}),(0,$.jsx)(`option`,{value:`unclassified`,children:`Unclassified`})]})]})]}):null,(0,$.jsxs)(`div`,{id:u,role:`tabpanel`,"aria-labelledby":`${u}-${m}`,children:[(0,$.jsx)(`div`,{className:`query-evidence-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evidence-table query-evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Query`}),(0,$.jsx)(`th`,{scope:`col`,children:`Status`}),p&&(0,$.jsx)(`th`,{scope:`col`,"aria-label":`Sentiment`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center`,children:[`Sentiment`,(0,$.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,$.jsx)(`th`,{scope:`col`,children:F}),(0,$.jsx)(`th`,{scope:`col`,children:`Latest run`}),(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Answer`})})]})}),zc(D.rows).map(e=>(0,$.jsxs)(`tbody`,{children:[(0,$.jsx)(`tr`,{className:`query-evidence-group`,children:(0,$.jsxs)(`th`,{scope:`rowgroup`,colSpan:A,children:[Lc(e.queryClass),` (`,O.get(e.queryClass)?.size??0,`)`]})}),e.rows.map(({key:e,phrase:n,queryClass:r,location:i,items:a,rawItems:s})=>{let c=d.has(e),f=j.indexOf(e),h=`${u}-query-${f}`,_=k.has(Xe(n)),v=a.map(e=>e.citationState),y=v.includes(`cited`)?`cited`:v.includes(`emerging`)?`emerging`:v.includes(`lost`)?`lost`:v.every(e=>e===`pending`)?`pending`:`not-cited`,b=[...new Set(s.map(e=>e.queryId).filter(e=>!!e))],x=s.map(e=>e.sourceSnapshotId).filter(e=>!!e),S=Fc(a),C=a.filter(e=>e.citationState===de.cited||e.citationState===`emerging`).length;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{className:`query-evidence-row`,onClick:()=>N(e),children:[(0,$.jsx)(`td`,{className:`evidence-query-cell`,children:(0,$.jsxs)(`button`,{type:`button`,className:`query-evidence-query`,"aria-label":n,"aria-describedby":h,"aria-expanded":c,onClick:t=>{t.stopPropagation(),N(e)},children:[(0,$.jsx)(o,{size:16,"aria-hidden":`true`,className:c?`rotate-90`:``}),(0,$.jsxs)(`span`,{className:`min-w-0`,children:[(0,$.jsx)(`span`,{children:n}),(0,$.jsxs)(`span`,{id:h,className:`query-evidence-meta`,children:[(0,$.jsx)(`span`,{children:Lc(r)}),t&&(0,$.jsx)(`span`,{children:i??`No location`}),a.filter(e=>e.provider).map(e=>(0,$.jsx)(`span`,{children:oo(e.provider)},e.id))]})]})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(rc,{state:y,label:Hc(y,m),className:`rounded-none border-0 bg-transparent p-0 text-label-14`}),(0,$.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,"aria-label":`${C} of ${a.length} engines ${I}`,title:`${C} of ${a.length} engines ${I}`,children:[C,`/`,a.length]})]})}),p&&(0,$.jsx)(`td`,{children:(0,$.jsx)(Ea,{queryId:b.length===1?b[0]:null,sourceSnapshotIds:b.length>1?[]:x,queryClass:r,location:t?i:void 0})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Pc,{history:S,signal:m})}),(0,$.jsx)(`td`,{className:`evidence-change-cell`,children:_?(0,$.jsx)(`span`,{className:`query-evidence-new`,children:`new query`}):(0,$.jsx)(Jc,{items:s})}),(0,$.jsx)(`td`,{})]}),c&&a.map((e,t)=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{className:`query-evidence-engine-row`,children:[(0,$.jsx)(`td`,{className:`evidence-query-cell`,children:(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:e.provider?oo(e.provider):`Awaiting engine`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(rc,{state:e.citationState,className:`rounded-none border-0 bg-transparent p-0 text-label-14`,label:Hc(e.citationState,m)})}),p&&(0,$.jsx)(`td`,{children:(0,$.jsx)(Ma,{queryId:e.queryId,sourceSnapshotIds:e.sourceSnapshotId?[e.sourceSnapshotId]:[],queryClass:e.queryClass,provider:e.provider,location:e.location??null})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Pc,{history:e.runHistory,signal:m})}),(0,$.jsx)(`td`,{className:`evidence-change-cell`,children:_?null:(0,$.jsx)(Jc,{items:[s[t]??e]})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,type:`button`,title:`View ${e.provider?oo(e.provider):`saved`} answer for ${e.query}`,onClick:t=>{t.stopPropagation(),l(e.id)},children:`View`})})]}),g===`detailed`&&(0,$.jsx)(`tr`,{className:`query-evidence-preview-row`,children:(0,$.jsx)(`td`,{colSpan:A,children:(0,$.jsx)($c,{item:e,mode:m,onViewFull:()=>l(e.id)},m)})})]},e.id))]},e)})]},e.queryClass??`unclassified`))]})}),D.totalRows===0&&(D.hasQuery||v!==`all`||S)?(0,$.jsx)(`p`,{className:`supporting-copy mt-3`,children:`No tracked queries match this filter.`}):null,(0,$.jsx)(Ss,{page:D.page,pageSize:D.pageSize,visibleRows:D.rows.length,totalRows:D.totalRows,onPageChange:D.setPage,itemLabel:D.hasQuery||v!==`all`||S?`matches`:`queries`})]}),(0,$.jsxs)(`p`,{className:`sr-only`,"aria-live":`polite`,children:[`Showing `,P===`cited`?`citations (sources)`:`mentions (answer text)`,`.`]})]})}function Zc(e){let t=(e.matchedTerms??[]).filter(e=>e.trim().length>2),n=To(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 Qc(e,t){let n=t.toLowerCase().replace(/^www\./,``);return(e.citedCompetitorDomains??[]).some(e=>e.toLowerCase().replace(/^www\./,``)===n)}function $c({item:e,mode:t,onViewFull:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1);if(t===`mentions`)return(0,$.jsx)(el,{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;return(0,$.jsxs)(`div`,{className:`query-evidence-preview space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-copy-13-strong text-secondary`,children:e.evidenceUrls.length>0?`Cited sources`:s.length>0?`Grounding sources`:`Cited domains`}),s.length>0?(0,$.jsx)(`ul`,{className:`space-y-4`,children:s.slice(0,a?void 0:6).map((t,n)=>(0,$.jsxs)(`li`,{className:`min-w-0`,children:[(0,$.jsx)(Jo,{url:t.uri,title:t.title}),Qc(e,_e(t.uri)??``)&&(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`Competitor source`})]},`${n}-${t.uri}`))}):e.citedDomains.length>0?(0,$.jsx)(`ul`,{className:`space-y-1 text-label-14 text-secondary`,children:e.citedDomains.slice(0,a?void 0:6).map(t=>(0,$.jsxs)(`li`,{className:`[overflow-wrap:anywhere]`,children:[t,Qc(e,t)?` · competitor source`:``]},t))}):(0,$.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,$.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-expanded":a,onClick:()=>o(e=>!e),children:a?`Show fewer sources`:`View all sources`}),e.answerSnippet.trim()?(0,$.jsxs)(`details`,{open:r,className:`border-t border-subtle pt-1`,children:[(0,$.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,$.jsx)(el,{item:e,onViewFull:n,contextOnly:!0})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No answer text captured for this run.`})]})}function el({item:e,onViewFull:t,contextOnly:n=!1}){let{matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}=e,s=(0,Q.useMemo)(()=>Zc({matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}),[r,i,a,o]);if(!(e.answerSnippet.trim().length>0))return(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No answer text captured for this run.`});let c=e.answerSnippet.length>Ic;return(0,$.jsxs)(`div`,{className:`query-evidence-preview space-y-3`,children:[!n&&(0,$.jsx)(`p`,{className:`text-copy-13-strong text-secondary`,children:`Answer text`}),(0,$.jsx)(Ja,{headingLevel:4,highlightGroups:s,previewLength:Ic,children:e.answerSnippet}),(!n&&e.citedDomains.length>0||(e.mentionedCompetitorDomains?.length??0)>0)&&(0,$.jsxs)(`dl`,{className:`space-y-2 text-label-13 text-secondary`,children:[!n&&e.citedDomains.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13-strong`,children:`Cited domains`}),(0,$.jsxs)(`dd`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:[e.citedDomains.slice(0,6).map(t=>(0,$.jsxs)(`span`,{className:`[overflow-wrap:anywhere]`,children:[t,Qc(e,t)?` · competitor source`:``]},`c-${t}`)),e.citedDomains.length>6&&(0,$.jsxs)(`span`,{children:[`+`,e.citedDomains.length-6,` more`]})]})]}),(e.mentionedCompetitorDomains?.length??0)>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13-strong`,children:`Competitors in answer`}),(0,$.jsxs)(`dd`,{className:`flex flex-wrap gap-x-3 gap-y-1`,children:[e.mentionedCompetitorDomains.slice(0,4).map(e=>(0,$.jsx)(`span`,{className:`[overflow-wrap:anywhere]`,children:e},`co-${e}`)),e.mentionedCompetitorDomains.length>4&&(0,$.jsxs)(`span`,{children:[`+`,e.mentionedCompetitorDomains.length-4,` more`]})]})]})]}),c&&(0,$.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:e=>{e.stopPropagation(),t()},children:`View full answer`})]})}function tl({windows:e,value:t,onChange:n,label:r,formatOption:i,disabled:a=!1}){return(0,$.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":r,children:e.map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":t===e,disabled:a,className:`segmented-option ${t===e?`segmented-option-active`:``}`,onClick:()=>{e!==t&&Ut(`window`),n(e)},children:i?i(e):e},e))})}var nl=`baseline`;function rl(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,[nl]:i.get(e)??null};for(let e of n)a[e.dataKey]=t?.[e.key]??0;return a}),series:n}}var il=`text-label-12-strong normal-case text-muted`;function al({id:e,title:t,tooltip:n,meta:r,actions:i}){return(0,$.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-start justify-between gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h2`,{id:e,className:`text-heading-16 text-primary`,children:t}),n&&(0,$.jsx)(X,{text:n})]}),r&&(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:r})]}),i]})}function ol({children:e}){return(0,$.jsx)(`div`,{className:`[&>details:first-child]:border-t-0`,children:e})}function sl({label:e,meta:t,children:n}){let[r,i]=(0,Q.useState)(!1);return(0,$.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":e,onToggle:e=>i(e.currentTarget.open),children:[(0,$.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,$.jsx)(`span`,{className:`visibility-disclosure-label`,children:e}),(0,$.jsx)(`span`,{className:`visibility-disclosure-meta`,children:t})]}),r&&(0,$.jsx)(`div`,{className:`visibility-disclosure-panel`,children:n})]})}var cl={3:`lg:grid-cols-3`,4:`lg:grid-cols-4`,5:`lg:grid-cols-5`};function ll({items:e,label:t}){return(0,$.jsx)(`div`,{role:`group`,"aria-label":t,children:(0,$.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-6 gap-y-4 border-y border-default py-4 sm:grid-cols-3 ${cl[e.length]??`lg:grid-cols-4`}`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-13 text-secondary`,children:[e.label,e.tooltip&&(0,$.jsx)(X,{text:e.tooltip})]}),(0,$.jsx)(`dd`,{className:`mt-1 truncate text-label-20-strong text-primary tabular-nums`,title:e.value,children:e.value}),e.detail&&(0,$.jsx)(`dd`,{className:`mt-0.5 text-label-13 text-secondary tabular-nums`,children:e.detail})]},e.label))})})}function ul({label:e,sortKey:t,current:n,dir:r,onSort:i,align:a}){let o=n===t;return(0,$.jsx)(`th`,{className:`py-2 ${a===`right`?`pl-4 text-right`:`text-left`}`,"aria-sort":o?r===`asc`?`ascending`:`descending`:void 0,children:(0,$.jsxs)(`button`,{type:`button`,className:`${il} 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,$.jsx)(`span`,{"aria-hidden":`true`,className:`ml-0.5`,children:r===`asc`?`↑`:`↓`})]})})}function dl({label:e,align:t}){return(0,$.jsx)(`th`,{className:`py-2 ${t===`right`?`pl-4 text-right`:`text-left`}`,children:(0,$.jsx)(`span`,{className:il,children:e})})}function fl(e,t,n=`desc`){return e.key===t?{key:t,dir:e.dir===`desc`?`asc`:`desc`}:{key:t,dir:n}}function pl(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 ml({groups:e,groupLabel:t,caption:n,childColumns:r,childRowKey:i,renderChildCells:a,pinLast:s}){let l=(0,Q.useId)(),[u,d]=(0,Q.useState)(new Set),[f,p]=(0,Q.useState)({key:`sessions`,dir:`desc`}),m=(0,Q.useMemo)(()=>{let t=pl(f.key,f.dir);return[...e].sort((e,n)=>Number(s?.(e)??!1)-Number(s?.(n)??!1)||t(e,n))},[e,f,s]),h=e=>p(t=>fl(t,e,e===`label`?`asc`:`desc`)),g=e=>d(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:n}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(ul,{label:t,sortKey:`label`,current:f.key,dir:f.dir,onSort:h,align:`left`}),(0,$.jsx)(ul,{label:`Sessions`,sortKey:`sessions`,current:f.key,dir:f.dir,onSort:h,align:`right`}),(0,$.jsx)(ul,{label:`Organic`,sortKey:`organicSessions`,current:f.key,dir:f.dir,onSort:h,align:`right`}),(0,$.jsx)(ul,{label:`Paid`,sortKey:`paidSessions`,current:f.key,dir:f.dir,onSort:h,align:`right`}),(0,$.jsx)(dl,{label:`Share`,align:`right`})]})}),(0,$.jsx)(`tbody`,{children:m.map((e,t)=>{let n=u.has(e.label),s=`${l}-group-${t}`,d=e.sources.length;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-2 pr-3`,children:(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":n,"aria-controls":n?s:void 0,onClick:()=>g(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,$.jsx)(c,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-secondary`}):(0,$.jsx)(o,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-muted`}),(0,$.jsx)(`span`,{className:`truncate`,title:e.label,children:e.label}),(0,$.jsxs)(`span`,{className:`shrink-0 text-label-12 text-secondary tabular-nums`,children:[d,` `,d===1?`source`:`sources`]})]})}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary tabular-nums`,children:e.organicSessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary tabular-nums`,children:e.paidSessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary tabular-nums`,children:St(e.share)})]}),n&&(0,$.jsx)(`tr`,{id:s,children:(0,$.jsx)(`td`,{colSpan:5,className:`pb-3 pl-6`,children:(0,$.jsx)(`div`,{className:`overflow-x-auto material-base px-3 pb-1`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[32rem] text-label-13`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`${e.label} sources`}),(0,$.jsx)(`thead`,{children:(0,$.jsx)(`tr`,{children:r.map(e=>(0,$.jsx)(dl,{label:e.label,align:e.align},e.label))})}),(0,$.jsx)(`tbody`,{children:e.sources.map(e=>(0,$.jsx)(`tr`,{className:`border-t border-subtle`,children:a(e)},i(e)))})]})})})})]},e.label)})})]})})}function hl(e,t){return e===`other`?ga.textDim:ua[t%ua.length]}function gl({input:e,baseline:t,baselineLabel:n,label:r,height:i=224}){let{rows:a,series:o}=(0,Q.useMemo)(()=>rl(e,t),[e,t]),[s,c]=(0,Q.useState)(new Set),[l,u]=(0,Q.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{role:`img`,"aria-label":r,style:{height:i},children:(0,$.jsx)(I,{width:`100%`,height:`100%`,children:(0,$.jsxs)(te,{data:a,margin:{top:4,right:4,bottom:0,left:0},children:[(0,$.jsx)(M,{stroke:xa,vertical:!1}),(0,$.jsx)(P,{dataKey:`date`,tick:va,tickLine:!1,axisLine:{stroke:Ca},tickFormatter:fa,minTickGap:24}),(0,$.jsx)(z,{tick:va,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,$.jsx)(N,{...Sa,labelFormatter:_a,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=hl(e.key,o.indexOf(e));return(0,$.jsx)(L,{type:`monotone`,dataKey:e.dataKey,name:e.dataKey,stackId:`stack`,stroke:t,fill:t,fillOpacity:.35,strokeWidth:1.5},e.dataKey)}),l&&n&&(0,$.jsx)(ee,{type:`monotone`,dataKey:`baseline`,name:`baseline`,stroke:ga.textFaint,strokeWidth:1.5,strokeDasharray:`5 4`,dot:!1,connectNulls:!1})]})})}),(0,$.jsxs)(`fieldset`,{className:`mt-2 flex flex-wrap gap-x-5 text-label-13 text-secondary`,children:[(0,$.jsx)(`legend`,{className:`sr-only`,children:`${r} series`}),o.map((e,t)=>(0,$.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2`,children:[(0,$.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,$.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2.5 shrink-0 rounded-sm`,style:{backgroundColor:hl(e.key,t)}}),e.label]},e.key)),n&&(0,$.jsxs)(`label`,{className:`flex min-h-9 items-center gap-2`,children:[(0,$.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,$.jsx)(`svg`,{"aria-hidden":`true`,width:`18`,height:`10`,viewBox:`0 0 18 10`,className:`shrink-0`,children:(0,$.jsx)(`line`,{x1:`0`,y1:`5`,x2:`18`,y2:`5`,stroke:ga.textFaint,strokeWidth:`2`,strokeDasharray:`5 3`})}),n]})]})]})}var _l=[`sessions`,`activeUsers`,`organicSessions`,`engagementRate`,`keyEvents`],vl=`canonry.siteTraffic.slots`;function yl(e){return typeof e==`string`&&Ve.some(t=>t===e)}function bl(){try{let e=JSON.parse(window.localStorage.getItem(vl)??`null`);if(Array.isArray(e)&&e.length===_l.length&&e.every(yl))return[...e]}catch{}return[..._l]}function xl(e){try{window.localStorage.setItem(vl,JSON.stringify(e))}catch{}}function Sl(e,t,n){let r=me(e,t);return r===null||t===null?{kind:`note`,text:`No earlier data`}:{kind:`delta`,amount:St(Math.abs(t),ye.percent),direction:t>0?`up`:t<0?`down`:`flat`,tone:r===Pe.better?`better`:r===Pe.worse?`worse`:`neutral`,basis:n}}function Cl({overview:e,refreshing:t=!1}){let[n,r]=(0,Q.useState)(bl),[i,a]=(0,Q.useState)(0),o=Je(e.window)?Wt[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,xl(r),r}),u=n.map((t,n)=>({key:t,slot:`slot-${n}`,label:le[t].label,value:Ue(t,e.totals[t],{compact:!0}),exactValue:Ue(t,e.totals[t]),change:Sl(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:Ve.map(e=>({value:e,label:le[e].label})),onChange:e=>{yl(e)&&l(n,e)}},formatValue:e=>Ue(t,e,{compact:!0}),formatExact:e=>Ue(t,e),allowDecimals:le[t].unit!==Le.count})),d=n[i]??_l[0],f=e.current.startDate&&e.current.endDate&&e.previous.startDate&&e.previous.endDate?`${wl(e.current.startDate,e.current.endDate,!0)} vs ${wl(e.previous.startDate,e.previous.endDate,!1)}`:void 0;return(0,$.jsx)(Ts,{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 ${le[d].label.toLowerCase()} yet.`,refreshing:t})}function wl(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 Tl(e){return e?_a(e.slice(0,10)):`—`}function El({children:e,onClick:t,disabled:n,title:r}){return(0,$.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 Dl({rows:e,expanded:t,loading:n,onToggle:r,actions:i,lastReadLabel:a,empty:s}){let l=i?6:5,u=(e,a)=>{let s=t.has(e.url),l=n?.has(e.url)??!1;return(0,$.jsxs)(`tr`,{className:`group`,children:[(0,$.jsx)(`td`,{className:`max-w-md ${a?`pl-9`:``}`,children:(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-0.5`,children:[e.isIndex&&!a&&(0,$.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-label":`${s?`Hide`:`Show`} the sitemaps in ${e.label}`,className:`rounded p-0.5 text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>r(e.url),children:s?(0,$.jsx)(c,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),(0,$.jsx)(ys,{value:e.label,title:e.url,className:`font-mono text-label-13 text-neutral`}),e.isIndex&&(0,$.jsx)(`span`,{className:`shrink-0 text-label-12 text-secondary`,children:l?`Loading…`:e.files?`Index · ${e.files.length} ${e.files.length===1?`sitemap`:`sitemaps`}`:`Index`}),e.kind&&(0,$.jsx)(`span`,{className:`shrink-0 text-label-12 text-secondary`,children:e.kind}),e.isDefault&&(0,$.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 text-label-12 text-secondary`,children:[`Default`,(0,$.jsx)(X,{text:`Canonry uses this sitemap when a command names none.`})]})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5 whitespace-nowrap`,children:[(0,$.jsx)(J,{tone:e.status.tone,children:e.status.label}),e.status.detail&&(0,$.jsx)(`span`,{className:`text-label-12 text-secondary`,children:e.status.detail})]})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.urls===null?`—`:e.urls.toLocaleString()}),(0,$.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:Tl(e.submittedAt)}),(0,$.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:e.lastReadAt?Tl(e.lastReadAt):`Not yet`}),i&&(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(`div`,{className:`flex justify-end gap-0.5 whitespace-nowrap 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,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Sitemap`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Status`}),(0,$.jsx)(`th`,{className:`text-right`,children:`URLs`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Submitted`}),(0,$.jsx)(`th`,{className:`text-left`,children:a}),i&&(0,$.jsx)(`th`,{className:`text-right`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsxs)(`tbody`,{children:[e.length===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:l,className:`py-6 text-center text-secondary`,children:s})}),e.map(e=>(0,$.jsxs)(Q.Fragment,{children:[u(e,null),e.isIndex&&t.has(e.url)&&(e.files??[]).map(t=>u(t,e))]},e.url))]})]})})}function Ol({label:e,items:t,disabled:n=!1,menuLabel:r}){let[i,a]=(0,Q.useState)(!1),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null),l=(0,Q.useId)();return(0,Q.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,$.jsxs)(`div`,{className:`relative inline-flex`,ref:o,children:[(0,$.jsxs)(q,{ref:s,type:`button`,variant:`outline`,size:`sm`,disabled:n,"aria-haspopup":`menu`,"aria-expanded":i,"aria-controls":i?l:void 0,onClick:()=>a(e=>!e),children:[e,(0,$.jsx)(c,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),i&&(0,$.jsx)(`div`,{id:l,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,$.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,$.jsx)(`span`,{children:e.label}),e.description&&(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.description})]},e.key))})]})}function kl(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 Al=`Search Console is not connected yet. Your Canonry team can set this up.`,jl=[`7d`,`30d`,`90d`,`all`],Ml=500,Nl=[{key:`clicks`,label:`Clicks`,color:ua[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:ua[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:ya.caution,format:e=>St(e)},{key:`position`,label:`Avg position`,color:ua[2],inverted:!0,format:e=>e.toFixed(1)}],Pl=25,Fl=`canonry:google-oauth-complete`;function Il(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`?`${Kt(Math.abs(o)).magnitude} pts`:Sn(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:St(Math.abs(s)),direction:s>0?`up`:`down`,tone:a(s>0),basis:i}}var Ll=[{key:`google-indexed`,engine:`google`,color:ua[0]},{key:`bing-indexed`,engine:`bing`,color:ua[6]}];function Rl(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 zl(e){return e.contents?.reduce((e,t)=>e+Number(t.submitted||0),0)??0}function Bl(e){let t=Number(e.errors??0),n=Number(e.warnings??0);return[t>0?`${t} error${t===1?``:`s`}`:``,n>0?`${n} warning${n===1?``:`s`}`:``].filter(Boolean).join(` · `)}function Vl(e){return e.isPending?`Processing`:Number(e.errors??0)>0?`Errors`:Number(e.warnings??0)>0?`Warnings`:`Success`}var Hl={Processing:`neutral`,Errors:`negative`,Warnings:`caution`,Success:`positive`};function Ul(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 Wl(e,t,n,r){let i=Vl(e);return{url:e.path,label:Ul(e.path,t),isIndex:!!e.isSitemapsIndex,status:{label:i,tone:Hl[i],detail:Bl(e)||void 0},urls:zl(e),submittedAt:e.lastSubmitted??null,lastReadAt:e.lastDownloaded??null,isDefault:n===e.path,files:r?.map(e=>Wl({...e,isSitemapsIndex:!1},t,n))}}function Gl({projectName:e,refreshNonce:t}){let n=S(),{isAdmin:r}=qn(),i=Ze(),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)([]),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)([]),[v,y]=(0,Q.useState)([]),[b,x]=(0,Q.useState)(null),[C,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(``),[O,k]=(0,Q.useState)(`30`),[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(`30d`),[I,L]=(0,Q.useState)(null),R=w({...Yi({client:K,path:{name:e},query:I?{surface:`index-coverage`,...I}:{surface:`index-coverage`,window:P}}),staleTime:Qn,placeholderData:j}),[z,ee]=(0,Q.useState)([`clicks`,`impressions`]),[te,ne]=(0,Q.useState)(!0),[re,B]=(0,Q.useState)(null),[ie,ae]=(0,Q.useState)(0),[V,H]=(0,Q.useState)({startDate:``,endDate:``,query:``,page:``}),[le,ue]=(0,Q.useState)(0),[de,fe]=(0,Q.useState)(!1),[pe,me]=(0,Q.useState)(0),[he,ge]=(0,Q.useState)(!1),[_e,U]=(0,Q.useState)(``),[ve,ye]=(0,Q.useState)(!0),[be,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(!1),[we,Te]=(0,Q.useState)(!1),[Ee,De]=(0,Q.useState)(!1),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(!1),[W,Me]=(0,Q.useState)(null),[Ne,Pe]=(0,Q.useState)(!1),[Fe,Ie]=(0,Q.useState)(!1),[Le,Re]=(0,Q.useState)(null),[Be,Ve]=(0,Q.useState)(null),[He,Ue]=(0,Q.useState)([]),[We,Ge]=(0,Q.useState)(new Set),[Ke,qe]=(0,Q.useState)({}),[Je,Xe]=(0,Q.useState)(new Set),[Qe,$e]=(0,Q.useState)(``),[tt,nt]=(0,Q.useState)(null),[rt,it]=(0,Q.useState)(``),[at,ot]=(0,Q.useState)(!1),[st,ct]=(0,Q.useState)(!1),[lt,ut]=(0,Q.useState)(!1),[dt,ft]=(0,Q.useState)(!1),[pt,ht]=(0,Q.useState)(!1),[gt,_t]=(0,Q.useState)(`indexed`),[vt,yt]=(0,Q.useState)(null),bt=!!(V.query.trim()||V.page.trim()||vt),xt=vt!==null,Ct=(0,Q.useMemo)(()=>{if(!vt)return f;let{key:e,dir:t}=vt;return[...f].sort((n,r)=>{let i=e===Rn.CTR?Number.isFinite(n.ctr)?n.ctr:0:n[e],a=e===Rn.CTR?Number.isFinite(r.ctr)?r.ctr:0:r[e];return t===`asc`?i-a:a-i})},[f,vt]),wt=ws({rows:Ct,pageSize:25}),Tt=he?wt.rows:Ct,Et=ws({rows:(Le??[]).filter(e=>e.path.toLowerCase().includes(Qe.trim().toLowerCase())),pageSize:25}),[Ot,kt]=(0,Q.useState)([]),[At,jt]=(0,Q.useState)(null),[Mt,Nt]=(0,Q.useState)(1),Pt=(0,Q.useMemo)(()=>{if(Ot.length<2)return null;let e=Ot[Ot.length-1],t=Ot[Ot.length-2];return{indexed:e.indexed-t.indexed,notIndexed:e.notIndexed-t.notIndexed}},[Ot]);(0,Q.useEffect)(()=>{Nt(1)},[W,gt,At]);let Ft=(0,Q.useMemo)(()=>At?(W?.reasonGroups??[]).find(e=>e.reason===At):void 0,[W,At]),It=(0,Q.useMemo)(()=>W?gt===`indexed`?W.indexed:gt===`deindexed`?W.deindexed:gt===`notIndexed`?At?Ft?.urls??[]:(W.reasonGroups??[]).length===0?W.notIndexed:[]:[]:[],[W,gt,At,Ft]),Lt=Math.max(1,Math.ceil(It.length/Pl)),Rt=Math.min(Math.max(1,Mt),Lt),zt=(Rt-1)*Pl,Bt=(0,Q.useMemo)(()=>W?.indexed.slice(zt,zt+Pl)??[],[W,zt]),Vt=(0,Q.useMemo)(()=>W?.notIndexed.slice(zt,zt+Pl)??[],[W,zt]),Ht=(0,Q.useMemo)(()=>W?.deindexed.slice(zt,zt+Pl)??[],[W,zt]),Ut=(0,Q.useMemo)(()=>(Ft?.urls??[]).slice(zt,zt+Pl),[Ft,zt]),[Wt,Gt]=(0,Q.useState)(!1),[Kt,qt]=(0,Q.useState)(null),[Jt,Yt]=(0,Q.useState)(null),[Xt,$t]=(0,Q.useState)(null),[tn,nn]=(0,Q.useState)(null);function rn(e,t){let n=Us(e),r=kl(n);r?(Yt(r),qt(null)):(Yt(null),qt(n.message||t))}let an=s.find(e=>e.connectionType===`gsc`),on=(an?.scopes??[]).includes(`https://www.googleapis.com/auth/webmasters`),sn=He.length>0?He:(Le??[]).map(e=>e.path),cn=sn.filter(e=>Le?.some(t=>t.path===e&&t.isSitemapsIndex)).length,ln=cn===1?`Resubmit sitemap index`:cn>1?`Resubmit sitemap indexes`:`Resubmit all sitemaps`,un=f.length>0||g.length>0||v.length>0,dn=ps(),fn=Eo();async function pn(t,r=!1){if(i)u([]);else if(!t)u([]),T(``);else{Ce(!0);try{let{sites:i}=await n.fetchQuery({...ii({client:K,path:{name:e}}),staleTime:r?0:Qn});u(i),T(t.propertyId??i[0]?.siteUrl??``),Yt(null)}catch(e){u([]),rn(e,`Failed to load Search Console properties`)}finally{Ce(!1)}}}async function mn(t){De(!0);let r=t??le;try{let t=bt?Ml:25,i=bt?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)),P&&P!==`all`&&!V.startDate&&(a.window=P);let o=await n.fetchQuery({...Dr({client:K,path:{name:e},query:a}),staleTime:Qn}),s=o.rows;bt?(fe(!1),p(s),me(s.length),ge(!0)):(fe(i+s.length<o.totalMatching),p(s),me(0),ge(!1))}catch(e){p([]),fe(!1),me(0),qt(e instanceof Error?e.message:`Failed to load GSC performance data`)}finally{De(!1)}}async function hn(){try{let t={};V.startDate&&(t.startDate=V.startDate),V.endDate&&(t.endDate=V.endDate),P&&P!==`all`&&!V.startDate&&(t.window=P);let r=await n.fetchQuery({...Vi({client:K,path:{name:e},query:t}),staleTime:Qn});h(r),L(t.startDate||t.endDate?{...t.startDate?{startDate:t.startDate}:{},...t.endDate?{endDate:t.endDate}:{}}:null)}catch{h(null)}}async function gn(t=!1){ke(!0);try{let r=_e.trim()||void 0,i={limit:`20`};r&&(i.url=r);let[a,o]=await Promise.all([n.fetchQuery({...Or({client:K,path:{name:e},query:i}),staleTime:t?0:Qn}),n.fetchQuery({...xr({client:K,path:{name:e}}),staleTime:t?0:Qn})]);_(a),y(o)}catch(e){_([]),y([]),qt(e instanceof Error?e.message:`Failed to load GSC inspection history`)}finally{ke(!1)}}async function _n(t=!1){Pe(!0);try{let[r,i]=await Promise.all([n.fetchQuery({...ri({client:K,path:{name:e}}),staleTime:t?0:Qn}),n.fetchQuery({...$r({client:K,path:{name:e}}),staleTime:t?0:Qn}).catch(()=>[])]);Me(r),kt(i)}catch(e){Me(null),kt([]),qt(e instanceof Error?e.message:`Failed to load coverage data`)}finally{Pe(!1)}}async function vn(t){Gt(!0),qt(null);try{let{succeeded:n,failed:r,total:i}=(await Ye(e,{urls:t})).summary;Xn({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){qt(e instanceof Error?e.message:`Failed to request indexing`)}finally{Gt(!1)}}async function yn(){Gt(!0),qt(null);try{let{succeeded:t,failed:n,total:r}=(await Ye(e,{urls:[],allUnindexed:!0})).summary;Xn({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){qt(e instanceof Error?e.message:`Failed to request indexing`)}finally{Gt(!1)}}async function bn(){Ie(!0),qt(null);try{let t=await se(e);n.setQueryData(ai({client:K,path:{name:e}}),t),Re(t.sitemaps),Ve(t.summary),Ue(t.preferredSubmissionUrls),Ge(new Set),qe({}),t.sitemaps.length===0&&$t(`No sitemaps found in this GSC property. Submit one here to start Google processing it.`)}catch(e){qt(e instanceof Error?e.message:`Failed to list sitemaps`)}finally{Ie(!1)}}async function xn(t){let n=We.has(t);if(Ge(e=>{let r=new Set(e);return n?r.delete(t):r.add(t),r}),!(n||Ke[t])){Xe(e=>new Set(e).add(t));try{let n=await se(e,t);qe(e=>({...e,[t]:n.sitemaps}))}catch(e){qt(e instanceof Error?e.message:`Failed to load sitemap files`)}finally{Xe(e=>{let n=new Set(e);return n.delete(t),n})}}}async function Sn(t){if(!on||t.length===0)return;let n=[...new Set(t)];ut(!0),qt(null),nt({completed:0,total:n.length});let r=0,i=0,a=0,o=null;try{for(let t=0;t<n.length;t+=50){let s=n.slice(t,t+50);try{let t=await Qt(e,s);r+=t.summary.accepted,i+=t.summary.failed,a+=s.length,nt({completed:a,total:n.length})}catch(t){a+=s.length;let c=s.length,l=n.length-a,u=t instanceof Error?t.message:`The batch request failed`,d=`${r} accepted, ${i} failed, ${c} unconfirmed, ${l} not attempted. Google may still process accepted sitemaps; indexing is not guaranteed.`;o=`Sitemap submission stopped after a batch request failed. ${d} ${u}`,qt(o),Xn({title:`Sitemap resubmission partially completed`,detail:d,tone:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`});return}}let t=n.length;Xn({title:i===0?`Sitemap submitted to Google`:`Some sitemap submissions need attention`,detail:i===0?`Google accepted the sitemap submission/refetch request; indexing is not guaranteed.`:`Google accepted ${r}/${t} sitemap submissions; ${i} failed. Indexing is not guaranteed.`,tone:i===0?`positive`:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`}),it(``),ot(!1)}catch(e){qt(e instanceof Error?e.message:`Failed to submit sitemap to Google`)}finally{ut(!1),nt(null),await bn(),o&&qt(o)}}async function wn(){ut(!0);let t=Le??[];try{let n=t.filter(e=>e.isSitemapsIndex),r=[];for(let t=0;t<n.length;t+=4)(await Promise.all(n.slice(t,t+4).map(async t=>{let n=Ke[t.path];if(n)return n;let r=await se(e,t.path);return qe(e=>({...e,[t.path]:r.sitemaps})),r.sitemaps}))).forEach((e,i)=>{r.push(...e.length>0?e.map(e=>e.path):[n[t+i].path])});await Sn([...t.filter(e=>!e.isSitemapsIndex).map(e=>e.path),...r])}catch(e){qt(e instanceof Error?e.message:`Failed to load sitemap files`),ut(!1)}}async function Tn(t){ct(!0),qt(null);try{await et(e,`gsc`,t),await Zn(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,sitemapUrl:t}:e)),Xn({title:`Default sitemap updated`,detail:t,tone:`positive`,dedupeKey:`gsc:sitemap-default:${e}`,dedupeMode:`replace`})}catch(e){qt(e instanceof Error?e.message:`Failed to set the default sitemap`)}finally{ct(!1)}}async function Y(t){try{await fn.mutateAsync({projectName:e,projectLabel:e,opts:t?{sitemapUrl:t}:void 0})}catch{}}async function En(){try{let t=(await n.fetchQuery({...mr({client:K,path:{name:e},query:{kind:ce[`gsc-sync`],limit:1}}),staleTime:Qn}))[0];nn(t?.status===ze.failed&&t.error?`Last saved Search Console sync failed: ${oe(t.error)}`:null)}catch{nn(`Saved Search Console sync status is unavailable.`)}}async function Dn(){ye(!0),qt(null);try{let[t,a]=await Promise.all([i||!r?Promise.resolve(null):en().catch(()=>null),n.fetchQuery({...Sr({client:K,path:{name:e}}),staleTime:Qn}).catch(()=>[])]);o(!!t?.google?.configured),c(a);let s=a.find(e=>e.connectionType===`gsc`);T(s?.propertyId??``),await Promise.all([!i&&s&&!s.propertyId?pn(s):Promise.resolve(),!i&&s?En():Promise.resolve(),mn(),hn(),gn(),_n()])}finally{ye(!1)}}(0,Q.useEffect)(()=>{u([]),ft(!1),Re(null),Ve(null),Ue([]),nn(null),Yt(null),$t(null)},[e]);let On=(0,Q.useRef)(t);(0,Q.useEffect)(()=>{Dn(),On.current!==t&&(On.current=t,R.refetch())},[e,t,r]),(0,Q.useEffect)(()=>{ue(0),B(null),H(e=>e.startDate||e.endDate?{...e,startDate:``,endDate:``}:e),ae(e=>e+1),hn()},[P]);let kn=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{kn.current?(ue(0),wt.setPage(1),mn(0)):kn.current=!0},[ie]);function jn(e){let t=re===e?null:e;B(t),H(e=>({...e,startDate:t??``,endDate:t??``})),ae(e=>e+1)}let Nn=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{Nn.current?(ue(0),mn(0)):Nn.current=!0},[xt]);async function Pn(){if(!a)qt(`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`);else{xe(!0),qt(null),$t(null);try{let{authUrl:t,redirectUri:r}=await Cn(e,`gsc`);if(!t.startsWith(`https://accounts.google.com/`)){qt(`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(),$t(e?`Google connected. Refreshing access…`:`Refreshing Google connection…`);try{await Zn(n,`google`),await Dn()}finally{$t(null)}}};function u(e){if(e.source!==i||e.origin!==a||!e.data||typeof e.data!=`object`)return;let t=e.data;t.type===Fl&&t.connectionType===`gsc`&&l(!0)}window.addEventListener(`message`,u),$t(`Finish the Google consent flow in the popup. This page will refresh automatically.`),s=window.setInterval(()=>{i.closed&&l(!1)},1e3)}catch(e){qt(e instanceof Error?e.message:`Failed to start OAuth flow`)}finally{xe(!1)}}}async function Fn(){qt(null),$t(null);try{await Dt(e,`gsc`),await Zn(n,`google`),c(e=>e.filter(e=>e.connectionType!==`gsc`)),u([]),T(``)}catch(e){qt(e instanceof Error?e.message:`Failed to disconnect`)}}async function In(){if(C){Te(!0),qt(null);try{await G(e,`gsc`,C),await Zn(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,propertyId:C}:e)),Xn({title:`GSC property updated`,detail:`${e} is now linked to ${C}.`,tone:`positive`,dedupeKey:`gsc:property:${e}`,dedupeMode:`drop`})}catch(e){qt(e instanceof Error?e.message:`Failed to save GSC property`)}finally{Te(!1)}}}async function Ln(){qt(null),$t(null);try{await dn.mutateAsync({projectName:e,projectLabel:e,opts:{days:parseInt(O,10)||void 0,full:M||void 0}}),await Zn(n,`gsc`)}catch{}}async function zn(){if(E.trim()){je(!0),qt(null),$t(null);try{let t=await mt(e,E.trim());await Zn(n,`gsc`),x(t),D(``),await gn()}catch(e){qt(e instanceof Error?e.message:`Failed to inspect URL`)}finally{je(!1)}}}return(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Search Console`}),(0,$.jsx)(`h2`,{children:`Google Search Console`})]})}),tn&&(0,$.jsx)(`p`,{role:`status`,className:`mb-3 text-copy-14 text-caution`,children:tn}),Jt&&(0,$.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,$.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-caution-100`,children:Jt.title}),(0,$.jsx)(`p`,{className:`mt-0.5 text-caution-200/90`,children:Jt.message}),(rs(Jt.enableUrl)||rs(Jt.indexingApiUrl))&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3`,children:[rs(Jt.enableUrl)&&(0,$.jsx)(`a`,{href:rs(Jt.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 ↗`}),rs(Jt.indexingApiUrl)&&(0,$.jsx)(`a`,{href:rs(Jt.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,$.jsx)(`button`,{type:`button`,className:`text-caution-400 hover:text-caution-200`,onClick:()=>Yt(null),children:`×`})]})}),Kt&&(0,$.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:[Kt,(0,$.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>qt(null),children:`×`})]}),Xt&&(0,$.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:[Xt,(0,$.jsx)(`button`,{type:`button`,className:`ml-2 text-positive-400 hover:text-positive-200`,onClick:()=>$t(null),children:`×`})]}),ve?(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading…`}):(0,$.jsxs)(`div`,{className:`space-y-3`,children:[an?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-label-12 text-muted`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`h-1.5 w-1.5 rounded-full bg-positive-500`}),(0,$.jsx)(`span`,{className:`text-neutral`,children:`Authorized`})]}),(0,$.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,$.jsx)(`code`,{className:`text-secondary`,children:an.domain}),(0,$.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Coverage measured`,` `,W?.lastInspectedAt?Mn(W.lastInspectedAt):`never`]}),!i&&(0,$.jsx)(`button`,{type:`button`,className:`ml-auto text-muted transition-colors hover:text-negative-400`,onClick:Jn(Fn),children:`Disconnect`})]}):r?(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Connection`}),(0,$.jsx)(`h3`,{children:`Domain authorization`})]}),(0,$.jsx)(J,{tone:a?`caution`:`negative`,children:a?`Ready to connect`:`App credentials missing`})]}),(0,$.jsxs)(`div`,{className:`mt-3 material-base px-4 py-5`,children:[(0,$.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,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[a?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:be,onClick:Jn(Pn),children:be?`Opening…`:`Connect Google Search Console`}):(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,asChild:!0,children:(0,$.jsx)(A,{to:`/settings`,children:`Open Settings`})}),!a&&(0,$.jsx)(`p`,{className:`text-copy-13 text-muted`,children:`The same Google OAuth app credentials are shared across all projects.`})]})]})]}):(0,$.jsx)(Z,{className:`surface-card`,children:(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Al})}),(an||un)&&(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Performance`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Search performance`}),(0,$.jsx)(X,{text:`${Rl(m?.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 ${Ml.toLocaleString()} matching rows while the table shows 25 per page.`})]}),m?.window?.startDate&&m.window.endDate&&(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[m.window.startDate,` to `,m.window.endDate,(m.window.daysSinceLatestData??0)>0&&` · latest data ${m.window.daysSinceLatestData} day${m.window.daysSinceLatestData===1?``:`s`} ago`]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(tl,{windows:jl,value:P,onChange:e=>{F(e),ue(0),wt.setPage(1)},label:`Search Console time period`,formatOption:e=>e===`all`?`All`:e}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Ee,onClick:()=>{ue(0),wt.setPage(1),mn(0),hn()},children:Ee?`Loading…`:`Apply filters`})]})]}),m&&m.daily.length>0&&(()=>{let{totals:e,daily:t,trends:n,periodComparison:r}=m,i=t=>e[t]??null,a=Ll.flatMap(e=>{let t=R.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=>z.includes(e.key)).map(e=>e.figure.series.at(-1)?.date).filter(e=>!!e).sort().at(-1),u=l&&l>c?l:c,d=Zt(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=[...Nl.filter(e=>z.includes(e.key)).map(e=>({dataKey:e.key,label:e.label,color:e.color,axisId:e.key,inverted:e.inverted,formatValue:e.format,trend:te?n?.[e.key]??null:null})),...a.filter(e=>z.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}))],p={key:`performance`,label:`Google search`,basis:r?.comparable?`vs prior ${r.days} ${r.days===1?`day`:`days`}`:void 0,figures:Nl.map(e=>{let t=i(e.key);return{key:e.key,label:e.label,color:e.color,value:t===null?`—`:e.format(t),change:Il(r,e.key,e.inverted),interactive:!0,disabled:t===null}})},h=a.length===0?null:{key:`indexed`,label:`Indexed pages`,basis:Cs(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:_s(e.figure.change,e.figure.unit),interactive:!0,disabled:e.figure.value===null}))};return(0,$.jsxs)(`div`,{className:`mt-3`,children:[(0,$.jsx)(Ts,{name:`Search performance figures`,frame:`none`,mode:`compare`,groups:h?[p,h]:[p],selected:z,onSelect:e=>ee(t=>t.includes(e)?t.length===1?t:t.filter(t=>t!==e):[...t,e]),chart:(0,$.jsx)(da,{data:d,xKey:`date`,series:f,xTickFormatter:fa,labelFormatter:_a,onSelectX:jn,selectedX:re}),legendExtra:(0,$.jsxs)(`label`,{className:`flex min-h-9 cursor-pointer items-center gap-2 pointer-coarse:min-h-11`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`size-4 accent-mono-200 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,checked:te,onChange:e=>ne(e.target.checked)}),`Trend line`]})}),(0,$.jsx)(`div`,{role:`group`,"aria-label":`Filter the table to a single day`,children:t.map(e=>(0,$.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":re===e.date,onClick:()=>jn(e.date),children:[_a(e.date),`: `,e.clicks,` clicks, `,e.impressions,` impressions`]},e.date))}),re&&(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-label-12`,children:[(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`Table showing `,_a(re)]}),(0,$.jsxs)(`button`,{type:`button`,className:`text-link hover:underline`,onClick:()=>jn(re),children:[`Show all `,e.days,` days`]})]}),e.position!==null&&(e.positionDays??e.days)<e.days&&(0,$.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,$.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Average position needs a property-level sync. Run `,(0,$.jsx)(`code`,{children:`canonry google sync`}),` to record it.`]})]})})(),(0,$.jsxs)(`div`,{className:`mt-3 grid gap-2 lg:grid-cols-4`,children:[(0,$.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`Start date`,title:`Start date (inclusive). Leave blank to use the window above.`,value:V.startDate,onChange:e=>H(t=>({...t,startDate:e.target.value}))}),(0,$.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-label-14 text-strong placeholder-mono-400 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`End date`,title:`End date (inclusive).`,value:V.endDate,onChange:e=>H(t=>({...t,endDate:e.target.value}))}),(0,$.jsx)(Os,{value:V.query,onChange:e=>H(t=>({...t,query:e})),label:`Filter search queries`,placeholder:`Contains query…`}),(0,$.jsx)(Os,{value:V.page,onChange:e=>H(t=>({...t,page:e})),label:`Filter page URLs`,placeholder:`Contains page URL…`})]}),f.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Date`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Query`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Page`}),Object.values(Rn).map(e=>(0,$.jsx)(`th`,{className:`text-right`,"aria-sort":vt?.key===e?vt.dir===`asc`?`ascending`:`descending`:`none`,children:(0,$.jsxs)(`button`,{type:`button`,className:`w-full cursor-pointer select-none text-right hover:text-strong focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded px-1 -mx-1`,onClick:()=>{wt.setPage(1),yt(t=>t?.key===e?t.dir===`desc`?{key:e,dir:`asc`}:null:{key:e,dir:`desc`})},children:[Hn[e],vt?.key===e?vt.dir===`desc`?` ↓`:` ↑`:``]})},e))]})}),(0,$.jsx)(`tbody`,{children:Tt.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-secondary`,children:e.date}),(0,$.jsx)(`td`,{className:`max-w-xs truncate text-strong`,children:e.query}),(0,$.jsx)(`td`,{className:`max-w-xs text-secondary`,children:(0,$.jsx)(ys,{value:e.page})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:e.clicks.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.impressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:St(e.ctr)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.position.toFixed(1)})]},`${e.date}:${e.query}:${e.page}:${t}`))})]})}),(0,$.jsx)(Ss,{page:he?wt.page:Math.floor(le/25)+1,pageSize:25,visibleRows:Tt.length,totalRows:he?pe:void 0,hasNextPage:he?void 0:de,disabled:Ee,itemLabel:he?`matches`:`rows`,onPageChange:e=>{if(he){wt.setPage(e);return}let t=(e-1)*25;ue(t),mn(t)}}),he&&pe>=Ml?(0,$.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Results are capped at `,Ml.toLocaleString(),`; narrow the filters to search beyond this set.`]}):null]}):(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No performance rows match the current filters yet.`})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Coverage`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Index coverage`}),(0,$.jsx)(X,{text:`Google's Indexing API is intended for eligible JobPosting and BroadcastEvent pages. Sitemap resubmission is the general-site bulk path.`})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[W&&W.notIndexed.length>0&&(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Wt,onClick:()=>void yn(),children:Wt?`Requesting…`:`Request indexing (${W.notIndexed.length})`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Ne,onClick:()=>void _n(!0),children:Ne?`Loading…`:`Reload saved coverage`})]})]}),W&&W.summary.total>0?(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`relative h-48 w-48`,children:[(0,$.jsxs)(`svg`,{viewBox:`0 0 128 128`,className:`h-full w-full`,"aria-hidden":`true`,children:[(0,$.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:ga.trackSubtle,strokeWidth:`14`}),(0,$.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:ya.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,$.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:ga.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,$.jsxs)(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center`,children:[(0,$.jsx)(`span`,{className:`text-heading-32 tabular-nums text-primary`,children:St(W.summary.indexedShare)}),(0,$.jsx)(`span`,{className:`text-label-12 normal-case text-muted mt-0.5`,children:`Indexed`})]})]}),(0,$.jsxs)(`div`,{className:`mt-4 flex items-center justify-center gap-8`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full bg-positive-500`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-24-strong tabular-nums text-primary`,children:W.summary.indexed.toLocaleString()}),(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Indexed`})]})]}),(0,$.jsx)(`div`,{className:`h-8 w-px bg-mono-800`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full bg-mono-500`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-24-strong tabular-nums text-primary`,children:W.summary.notIndexed.toLocaleString()}),(0,$.jsxs)(`p`,{className:`text-label-12 normal-case text-muted`,children:[`Not indexed`,(W.reasonGroups??[]).length>0&&(0,$.jsxs)(`span`,{className:`ml-1 text-faint`,children:[`· `,(W.reasonGroups??[]).length,` `,(W.reasonGroups??[]).length===1?`reason`:`reasons`]})]})]})]}),W.summary.deindexed>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`h-8 w-px bg-mono-800`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`inline-block h-2.5 w-2.5 rounded-full bg-negative-500`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-24-strong tabular-nums text-primary`,children:W.summary.deindexed.toLocaleString()}),(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Deindexed`})]})]})]})]})]})})()}),(0,$.jsx)(`div`,{className:`mt-3 flex border-b border-default`,role:`tablist`,"aria-label":`Coverage status`,children:[`indexed`,`notIndexed`,`deindexed`].map(e=>{let t=e===`indexed`?W.indexed.length:e===`notIndexed`?W.notIndexed.length:W.deindexed.length;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":gt===e,className:`border-b-2 px-3 py-2 text-button-14 transition-colors ${gt===e?`border-accent text-heading`:`border-transparent text-secondary hover:border-mono-600 hover:text-strong`}`,onClick:()=>{_t(e),jt(null)},children:[e===`indexed`?`Indexed`:e===`notIndexed`?`Not Indexed`:`Deindexed`,` (`,t,`)`]},e)})}),(0,$.jsxs)(`div`,{className:`mt-3 overflow-x-auto`,children:[gt===`indexed`&&W.indexed.length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Verdict`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Last Crawl`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Mobile`})]})}),(0,$.jsx)(`tbody`,{children:Bt.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.verdict??`Unknown`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.crawlTime?e.crawlTime.split(`T`)[0]:`—`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.isMobileFriendly===!0?`Yes`:e.isMobileFriendly===!1?`No`:`—`})]},e.id))})]}),gt===`notIndexed`&&!At&&(W.reasonGroups??[]).length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Reason`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Pages`})]})}),(0,$.jsx)(`tbody`,{children:(W.reasonGroups??[]).map(e=>(0,$.jsxs)(`tr`,{className:`cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,onClick:()=>jt(e.reason),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),jt(e.reason))},tabIndex:0,role:`button`,"aria-label":`View ${e.reason} pages`,children:[(0,$.jsx)(`td`,{className:`text-strong`,children:e.reason}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.count})]},e.reason))})]}),gt===`notIndexed`&&!At&&(W.reasonGroups??[]).length===0&&W.notIndexed.length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Indexing State`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Coverage`})]})}),(0,$.jsx)(`tbody`,{children:Vt.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.indexingState??`Unknown`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`})]},e.id))})]}),gt===`notIndexed`&&At&&(()=>{let e=(W.reasonGroups??[]).find(e=>e.reason===At);return e?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`flex items-center gap-2 mb-3`,children:(0,$.jsxs)(`button`,{type:`button`,className:`text-button-14 text-secondary hover:text-strong transition-colors`,onClick:()=>jt(null),children:[`←`,` Back to reasons`]})}),(0,$.jsxs)(`div`,{className:`mb-3 flex items-center justify-between material-base p-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:e.reason}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[e.count,` affected page`,e.count===1?``:`s`]})]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Wt,onClick:()=>void vn(e.urls.map(e=>e.url)),children:Wt?`Requesting…`:`Request indexing (${e.count})`})]}),(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Last Crawl`}),(0,$.jsx)(`th`,{className:`w-8`})]})}),(0,$.jsx)(`tbody`,{children:Ut.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.crawlTime?e.crawlTime.split(`T`)[0]:`—`}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`button`,{type:`button`,className:`text-button-14 text-muted hover:text-strong transition-colors`,disabled:Wt,onClick:()=>void vn([e.url]),title:`Request indexing`,children:`Index`})})]},e.id))})]})]}):null})(),gt===`deindexed`&&W.deindexed.length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Previous`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Current`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Detected`})]})}),(0,$.jsx)(`tbody`,{children:Ht.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.previousState}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.currentState}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.transitionDate.split(`T`)[0]})]},`${e.url}-${t}`))})]}),(gt===`indexed`&&W.indexed.length===0||gt===`notIndexed`&&!At&&W.notIndexed.length===0||gt===`deindexed`&&W.deindexed.length===0)&&(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No URLs in this category.`}),(0,$.jsx)(Ss,{page:Rt,pageSize:Pl,visibleRows:Math.min(Pl,It.length-zt),totalRows:It.length,onPageChange:Nt,itemLabel:`URLs`})]}),(0,$.jsxs)(`div`,{className:`mt-4 border-t border-default pt-3`,children:[(0,$.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":pt,onClick:()=>ht(e=>!e),children:[(0,$.jsx)(`span`,{children:`Coverage history`}),(0,$.jsx)(`span`,{children:pt?`Hide snapshots`:Ot.length>0?`View ${Ot.length} snapshots`:`View history`})]}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[`Current: `,W.summary.indexed.toLocaleString(),` indexed, `,W.summary.notIndexed.toLocaleString(),` not indexed.`,Pt&&(0,$.jsxs)($.Fragment,{children:[` Since the last snapshot: `,Pt.indexed>=0?`+`:``,Pt.indexed.toLocaleString(),` indexed, `,Pt.notIndexed>=0?`+`:``,Pt.notIndexed.toLocaleString(),` not indexed.`]})]}),pt&&(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:Ot.length>0?(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Date`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Indexed`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Not indexed`})]})}),(0,$.jsx)(`tbody`,{children:Ot.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-secondary`,children:e.date}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:e.indexed.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.notIndexed.toLocaleString()})]},e.date))})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No saved coverage snapshots yet.`})})]})]}):(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:Ne?`Loading coverage data…`:`No coverage data yet. Inspect your sitemap to populate this view.`})]}),!i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Sitemaps`}),(0,$.jsx)(X,{text:`Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[Le!==null&&(0,$.jsxs)(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:Fe||!an?.propertyId,onClick:()=>void bn(),children:[(0,$.jsx)(d,{className:`h-3.5 w-3.5 ${Fe?`animate-spin`:``}`,"aria-hidden":`true`}),Fe?`Loading…`:`Reload from Google`]}),on?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:at||lt,onClick:()=>ot(!0),children:`Submit sitemap`}):an&&(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:Jn(Pn),children:`Reconnect`})]})]})]}),at&&on&&(0,$.jsxs)(`form`,{className:`mb-3 flex flex-col gap-2 sm:flex-row`,onSubmit:e=>{e.preventDefault(),rt.trim()&&Sn([rt.trim()])},children:[(0,$.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:rt,onChange:e=>it(e.target.value)}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(q,{type:`submit`,size:`sm`,disabled:lt||!rt.trim(),children:lt?`Submitting…`:`Submit to Google`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{ot(!1),it(``)},children:`Cancel`})]})]}),Le===null?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Google's sitemap list loads on request.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Fe||!an?.propertyId,onClick:()=>void bn(),children:Fe?`Loading…`:`Load from Google`})]}):(0,$.jsxs)($.Fragment,{children:[Le.length>0&&(0,$.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-center justify-between gap-2`,children:[(0,$.jsx)(Os,{className:`w-full sm:w-64`,value:Qe,onChange:e=>{$e(e),Et.setPage(1)},label:`Filter sitemaps`,placeholder:`Filter sitemaps…`}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[Be&&(0,$.jsxs)(`span`,{className:`text-label-13 text-secondary`,children:[`Top level: `,Be.indexes,` index`,Be.indexes===1?``:`es`,`, `,Be.files,` file`,Be.files===1?``:`s`]}),(0,$.jsx)(Ol,{label:tt?`Submitting ${tt.completed} of ${tt.total}`:`Resubmit all`,menuLabel:`Resubmit sitemaps to Google`,disabled:!on||lt,items:[{key:`primary`,label:ln,description:cn>0?`Google rereads every sitemap the index lists.`:`Each sitemap in the list, once.`,disabled:sn.length===0,onSelect:()=>void Sn(sn)},{key:`files`,label:`Resubmit all files`,description:`Every file inside each index, one by one.`,onSelect:()=>void wn()}]})]})]}),(0,$.jsx)(Dl,{rows:Et.rows.map(e=>Wl(e,an?.propertyId??null,an?.sitemapUrl??null,Ke[e.path])),expanded:We,loading:Je,onToggle:e=>void xn(e),lastReadLabel:`Last read`,empty:`Google has no sitemaps for this property. Submit one to start.`,actions:e=>(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(El,{disabled:!on||lt,title:on?void 0:`Reconnect to allow submitting.`,onClick:()=>void Sn([e.url]),children:e.submittedAt?`Resubmit`:`Submit`}),(0,$.jsx)(El,{disabled:fn.isPending,onClick:()=>void Y(e.url),children:`Inspect URLs`}),!e.isDefault&&(0,$.jsx)(El,{disabled:st,title:`Canonry uses this sitemap when a command names none.`,onClick:()=>void Tn(e.url),children:`Set as default`})]})}),Le.length>0&&(0,$.jsx)(Ss,{page:Et.page,pageSize:25,visibleRows:Et.rows.length,totalRows:Et.totalRows,onPageChange:Et.setPage,itemLabel:`sitemaps`})]})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Inspection`}),(0,$.jsx)(`h3`,{children:`Inspect a URL`})]})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,$.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:E,onChange:e=>D(e.target.value),onKeyDown:e=>e.key===`Enter`&&void zn()}),(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:Ae||!an?.propertyId||!E.trim(),onClick:Jn(zn),children:Ae?`Inspecting…`:`Inspect URL`})]}),b&&(0,$.jsxs)(`div`,{className:`mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4`,children:[(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Indexing state`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:b.indexingState??`Unknown`})]}),(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Verdict`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:b.verdict??`Unknown`})]}),(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Mobile friendly`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:An(b.isMobileFriendly??null)})]}),(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Last crawl`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:Mn(b.crawlTime)})]})]})]})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`History`}),(0,$.jsx)(`h3`,{children:`Inspection log`})]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:Oe,onClick:()=>void gn(!0),children:Oe?`Loading…`:`Refresh history`})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,$.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:`text`,placeholder:`Filter exact URL`,value:_e,onChange:e=>U(e.target.value)}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:Oe,onClick:()=>void gn(!0),children:`Apply filter`})]}),g.length>0?(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Indexing`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Verdict`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Coverage`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Mobile`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Inspected`})]})}),(0,$.jsx)(`tbody`,{children:g.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,$.jsx)(`td`,{className:`text-neutral`,children:e.indexingState??`Unknown`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.verdict??`Unknown`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.coverageState??`Unknown`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:An(e.isMobileFriendly??null)}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Mn(e.inspectedAt)})]},e.id))})]})}):(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No inspection history yet.`})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Deindexed`}),(0,$.jsx)(`h3`,{children:`Recent indexing losses`})]})}),v.length>0?(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Previous`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Current`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Changed at`})]})}),(0,$.jsx)(`tbody`,{children:v.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-sm truncate text-strong`,children:e.url}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.previousState??`Unknown`}),(0,$.jsx)(`td`,{className:`text-neutral`,children:e.currentState??`Unknown`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Mn(e.transitionDate)})]},`${e.url}:${e.transitionDate}`))})]})}):(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-muted`,children:`No deindexed transitions recorded.`})]})]}),an&&!i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`border-t border-default pt-3`,children:(0,$.jsxs)(`button`,{type:`button`,className:`flex w-full items-center gap-2 text-left`,onClick:()=>{dt||pn(an),ft(e=>!e)},children:[(0,$.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 ${dt?`rotate-90`:``}`,"aria-hidden":`true`,children:(0,$.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,$.jsx)(`span`,{className:`text-label-12 normal-case text-muted`,children:`Setup & Configuration`})]})}),dt&&(0,$.jsx)(`div`,{className:`space-y-3`,children:(0,$.jsxs)(`div`,{className:`grid gap-3 xl:grid-cols-2`,children:[(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Property`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Pick the Search Console property`}),(0,$.jsx)(X,{text:`The selected property is used for future syncs and URL inspections for this project.`})]})]})}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-2`,children:[(0,$.jsx)(`label`,{className:`text-label-12 text-muted`,htmlFor:`gsc-property-${e}`,children:`Property URL`}),(0,$.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:C,disabled:Se||l.length===0,onChange:e=>T(e.target.value),children:l.length===0?(0,$.jsx)(`option`,{value:``,children:Se?`Loading properties…`:`No properties available`}):l.map(e=>(0,$.jsxs)(`option`,{value:e.siteUrl,children:[e.siteUrl,` · `,e.permissionLevel]},e.siteUrl))}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:Se,onClick:()=>void pn(an,!0),children:Se?`Refreshing…`:`Refresh properties`}),(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:!C||we,onClick:Jn(In),children:we?`Saving…`:`Save property`})]})]})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Sync`}),(0,$.jsx)(`h3`,{children:`Import GSC performance data`})]})}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-[160px_1fr]`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`text-label-12 text-muted`,htmlFor:`gsc-sync-days-${e}`,children:`Days`}),(0,$.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:O,onChange:e=>k(e.target.value)})]}),(0,$.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,$.jsx)(`input`,{type:`checkbox`,checked:M,onChange:e=>N(e.target.checked)}),`Replace existing imported rows for the requested range`]})]}),(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:dn.isPending||!an.propertyId,onClick:Jn(Ln),children:dn.isPending?`Queueing…`:`Queue sync`}),!an.propertyId&&(0,$.jsx)(`p`,{className:`text-copy-13 text-caution-400`,children:`Select a Search Console property before queueing a sync.`})]})]})]})})]})]})]})}var Kl=[`7d`,`30d`,`90d`,`all`],ql=10,Jl=[{key:`clicks`,label:`Clicks`,color:ua[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:ua[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:ya.caution,format:e=>St(e)},{key:`position`,label:`Avg position`,color:ua[2],inverted:!0,format:e=>e.toFixed(1)}],Yl=`bing-indexed`,Xl=`Impression-weighted across the queries Bing names. Bing reports these per week, so the line moves weekly.`,Zl=`Asks Bing directly. Counts against the shared Bing request limit for this key.`;function Ql(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:Sn(t),direction:t>0?`up`:`down`,tone:t>0?`worse`:`better`,basis:n}}function $l(e){return e==null?`—`:e.toFixed(1)}function eu(e){return e==null?`—`:Math.round(e).toLocaleString()}function tu(e){return e.replace(/^https?:\/\//,``).replace(/\/+$/,``)}function nu(e,t){let n=t.replace(/\/+$/,``);return e.startsWith(n)?e.slice(n.length)||`/`:e}function ru(e,t){return e?.find(e=>e.kind===t)}function iu(e){let t=e?.payload;return t&&typeof t.dailyQuota==`number`&&typeof t.monthlyQuota==`number`?{dailyQuota:t.dailyQuota,monthlyQuota:t.monthlyQuota}:null}function au(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 ou(e){return Array.isArray(e?.payload)?e.payload.filter(e=>typeof e==`object`&&!!e):null}var su=new Set([`entityType`,`requestType`,`type`,`role`]);function cu(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)?_a(e.slice(0,10)):su.has(t)&&/^[a-z]+(?:-[a-z]+)*$/.test(e)?e.charAt(0).toUpperCase()+e.slice(1).replaceAll(`-`,` `):e:JSON.stringify(e)}function lu({status:e,right:t,children:n}){return(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{children:`Bing Webmaster Tools`}),e]}),t]}),n]})}function uu({projectName:e,refreshNonce:t}){let n=S(),r=w({...Zi({client:K,path:{name:e}}),staleTime:Qn}),i=r.data??null,a=w({...si({client:K,path:{name:e}}),staleTime:Qn,enabled:!(!i?.connected||i.siteUrl)}),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{t>0&&r.refetch()},[t]);async function f(){if(o.trim()){d(null);try{await kt(e,o.trim()),s(``),await Zn(n,`bing`)}catch(e){d(Te(e))}}}async function p(){d(null);try{await sn(e),l(``),await Zn(n,`bing`)}catch(e){d(Te(e))}}async function m(){if(c){d(null);try{await Nt(e,c),await Zn(n,`bing`)}catch(e){d(Te(e))}}}if(r.isPending)return(0,$.jsx)(lu,{children:(0,$.jsx)(Z,{className:`surface-card`,children:(0,$.jsx)(`div`,{className:`text-label-14 text-secondary`,children:`Loading Bing data…`})})});if(r.isError)return(0,$.jsx)(lu,{children:(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load the Bing connection: `,Te(r.error)]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void r.refetch(),children:`Retry`})]})});if(!i?.connected)return(0,$.jsx)(lu,{children:(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Connection`}),(0,$.jsx)(`h3`,{children:`Domain authorization`})]}),(0,$.jsx)(J,{tone:`caution`,children:`Not connected`})]}),Y()?(0,$.jsx)(`p`,{className:`text-copy-14 text-neutral`,children:`Bing Webmaster Tools is not connected for this project.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.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,$.jsxs)(`div`,{className:`mt-3`,children:[(0,$.jsx)(`label`,{className:`text-label-12 text-muted`,htmlFor:`bing-api-key`,children:`API Key`}),(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-2`,children:[(0,$.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,$.jsx)(hs,{size:`sm`,disabled:!o.trim(),onClick:Jn(f),children:`Connect`})]}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[`Get your API key from`,` `,(0,$.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,$.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:u})]})});if(!i.siteUrl){let e=a.data?.sites??[];return(0,$.jsx)(lu,{children:(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Connection`}),(0,$.jsx)(`h3`,{children:`Domain authorization`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(J,{tone:`positive`,children:`Connected`}),!Y()&&(0,$.jsx)(hs,{size:`sm`,variant:`ghost`,onClick:Jn(p),children:`Disconnect`})]})]}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`material-base px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`h-2 w-2 rounded-full bg-positive-500`}),(0,$.jsx)(`span`,{className:`text-label-14 text-strong`,children:`Authorized for this project domain`}),(0,$.jsx)(`span`,{className:`text-label-12 text-muted`,children:i.domain})]}),(0,$.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,$.jsxs)(`div`,{className:`grid gap-3 lg:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Registered domain`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:i.domain})]}),(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Last auth update`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:i.updatedAt?Mn(i.updatedAt):`—`})]})]}),(0,$.jsxs)(`div`,{className:`material-base p-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Select site`}),e.length>0?(0,$.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,$.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,$.jsx)(`option`,{value:``,children:`Select a site...`}),e.map(e=>(0,$.jsxs)(`option`,{value:e.url,children:[e.url,e.verified?` (verified)`:``]},e.url))]}),!Y()&&(0,$.jsx)(hs,{size:`sm`,disabled:!c,onClick:Jn(m),children:`Set Site`})]}):(0,$.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,$.jsx)(`p`,{className:`mt-3 text-copy-13 text-negative`,children:u})]})})}return(0,$.jsx)(du,{projectName:e,connection:i,siteUrl:i.siteUrl,onDisconnect:p,error:u})}function du({projectName:e,connection:t,siteUrl:n,onDisconnect:r,error:i}){let[a,o]=(0,Q.useState)(`30d`),s={name:e},l=w({...aa({client:K,path:s,query:{window:a}}),staleTime:Qn,placeholderData:j}),u=w({...Ci({client:K,path:s}),staleTime:Qn}),d=w({...bi({client:K,path:s}),staleTime:Qn}),f=!!(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=ou(ru(u.data?.snapshots,`blocked-urls`))?.length??0;return(0,$.jsx)(lu,{status:(0,$.jsxs)(`p`,{className:`mt-1 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-label-13 text-secondary`,children:[(0,$.jsx)(`span`,{className:`h-2 w-2 rounded-full bg-positive-500`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:`Connected`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsx)(`span`,{className:`font-mono`,title:n,children:tu(n)}),l.data?.latestAvailableDate&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Data through `,_a(l.data.latestAvailableDate)]})]}),u.data?.syncedAt&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Synced `,Mn(u.data.syncedAt)]})]}),h>0&&(0,$.jsx)(`span`,{className:`ml-1.5`,children:(0,$.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,$.jsxs)(`details`,{className:`group`,children:[(0,$.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,$.jsx)(c,{className:`h-3.5 w-3.5 transition-transform group-open:rotate-180`,"aria-hidden":`true`})]}),(0,$.jsxs)(`div`,{className:`material-base mt-2 space-y-2 p-3 text-copy-13`,children:[(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`span`,{className:`text-secondary`,children:`Domain`}),` `,(0,$.jsx)(`span`,{className:`text-strong`,children:t.domain})]}),(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`span`,{className:`text-secondary`,children:`Site`}),` `,(0,$.jsx)(`span`,{className:`font-mono text-strong`,children:n})]}),(0,$.jsxs)(`p`,{children:[(0,$.jsx)(`span`,{className:`text-secondary`,children:`Last auth update`}),` `,(0,$.jsx)(`span`,{className:`text-strong`,children:t.updatedAt?Mn(t.updatedAt):`—`})]}),!Y()&&(0,$.jsx)(hs,{size:`sm`,variant:`ghost`,onClick:Jn(r),children:`Disconnect`})]})]}),children:(0,$.jsxs)(`div`,{className:`space-y-3`,children:[i&&(0,$.jsx)(`p`,{className:`text-copy-13 text-negative`,children:i}),p&&!f&&m?(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load Bing data: `,Te(m)]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{l.refetch(),u.refetch(),d.refetch()},children:`Retry`})]}):p&&!f?(0,$.jsx)(fu,{projectName:e}):(0,$.jsx)(pu,{projectName:e,siteUrl:n,range:a,onRangeChange:o}),(0,$.jsx)(vu,{projectName:e,siteUrl:n,snapshots:u.data?.snapshots}),f&&(0,$.jsx)(bu,{projectName:e,siteUrl:n}),f&&(0,$.jsx)(gu,{projectName:e}),f&&(0,$.jsx)(Su,{siteUrl:n,snapshots:u.data?.snapshots??[]})]})})}function fu({projectName:e}){let[t,n]=(0,Q.useState)(!1);async function r(){try{await rn(e),n(!0),Xn({title:`Bing sync started`,detail:`Search data appears here when it finishes.`,tone:`neutral`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}catch(t){Xn({title:`Bing sync could not start`,detail:Te(t),tone:`negative`,dedupeKey:`bing:sync:${e}`,dedupeMode:`replace`})}}return(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-strong`,children:`No Bing search data yet`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`It arrives with the daily refresh.`}),!Y()&&(0,$.jsx)(hs,{className:`mt-3`,size:`sm`,disabled:t,onClick:Jn(r),children:t?`Sync running…`:`Sync Bing data now`})]})}function pu({projectName:e,siteUrl:t,range:n,onRangeChange:r}){let i={name:e},a=w({...aa({client:K,path:i,query:{window:n}}),staleTime:Qn,placeholderData:j}),o=w({...zi({client:K,path:i,query:{window:n,groupBy:`week`}}),staleTime:Qn,placeholderData:j}),s=w({...Yi({client:K,path:i,query:{surface:`index-coverage`,window:n}}),staleTime:Qn,placeholderData:j}),[c,l]=(0,Q.useState)([`clicks`,`impressions`]),[u,d]=(0,Q.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,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`Loading Bing search data…`});else if(a.isError||!f)h=(0,$.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing search data: `,Te(a.error)]});else{let r=o.data?.totals?.avgImpressionPosition??null,i=Ql(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:Jl.map(e=>{if(e.key===`position`)return{key:e.key,label:e.label,help:Xl,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:Il(m,e.key,!1),interactive:!0,disabled:f.rows.length===0}})},_=p?{key:`indexed`,label:`Indexed pages`,basis:Cs([p]),figures:[{key:Yl,label:`Bing`,color:ua[6],value:p.value===null?`—`:p.value.toLocaleString(),change:_s(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?Zt(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,[Yl]:T.get(e)??null}}):[],D=[...Jl.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(Yl)&&p?[{dataKey:Yl,label:`Bing indexed pages`,color:ua[6],axisId:Yl,formatValue:e=>e.toLocaleString(),connectNulls:!0}]:[]];h=(0,$.jsxs)(`div`,{className:`mt-3`,children:[(0,$.jsx)(Ts,{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,$.jsx)(da,{data:E,xKey:`date`,series:D,xTickFormatter:fa,labelFormatter:_a,ariaLabel:`Daily Bing search figures`}):void 0,emptyChartMessage:`Bing reported no search traffic in this window.`,legendExtra:(0,$.jsxs)(`label`,{className:`flex min-h-9 cursor-pointer items-center gap-2 pointer-coarse:min-h-11`,children:[(0,$.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,$.jsx)(mu,{projectName:e,siteUrl:t,range:n})]})}return(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Search performance`}),(0,$.jsx)(X,{text:`${Rl(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,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[_a(f.window.startDate),` to `,_a(f.window.endDate)]})]}),(0,$.jsx)(tl,{windows:Kl,value:n,onChange:r,label:`Bing time period`,formatOption:e=>e===`all`?`All`:e})]}),h]})}function mu({projectName:e,siteUrl:t,range:n}){let[r,i]=(0,Q.useState)(`queries`),[a,s]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(void 0),[d,f]=(0,Q.useState)(1),[p,m]=(0,Q.useState)(null),h={name:e},g=(d-1)*ql;(0,Q.useEffect)(()=>{let e=a.trim()||void 0;if(e===void 0){u(void 0);return}let t=setTimeout(()=>u(e),300);return()=>clearTimeout(t)},[a]);let _=w({...zi({client:K,path:h,query:{window:n,query:l,limit:ql,offset:g}}),staleTime:Qn,placeholderData:j,enabled:r===`queries`}),v=w({...vi({client:K,path:h,query:{window:n,page:l,limit:ql,offset:g}}),staleTime:Qn,placeholderData:j,enabled:r===`pages`}),y=r===`queries`?_:v,b=r===`queries`?(_.data?.rows??[]).map(e=>({key:e.query,...e})):(v.data?.rows??[]).map(e=>({key:e.page,...e})),x=y.data?.totalMatching??0,S=r===`queries`?`Query`:`Page`;return(0,Q.useEffect)(()=>{f(1),m(null)},[r,n,l]),(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3 border-b border-base`,children:[(0,$.jsx)(`div`,{className:`flex gap-1`,role:`tablist`,"aria-label":`Bing search rows`,children:[`queries`,`pages`].map(e=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":r===e,className:`border-b-2 px-3 py-1.5 text-button-14 transition-colors ${r===e?`border-mono-200 text-strong`:`border-transparent text-muted hover:text-neutral`}`,onClick:()=>i(e),children:e===`queries`?`Queries`:`Pages`},e))}),(0,$.jsx)(Os,{className:`mb-1.5 w-full sm:w-64`,value:a,onChange:s,label:r===`queries`?`Filter Bing queries`:`Filter Bing pages`,placeholder:r===`queries`?`Contains query…`:`Contains page URL…`})]}),y.isError?(0,$.jsxs)(`p`,{className:`mt-3 text-copy-14 text-negative`,children:[`Could not load Bing `,r,`: `,Te(y.error)]}):(0,$.jsx)(`div`,{className:`mt-2 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`w-7`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,$.jsx)(`th`,{className:`text-left`,children:S}),(0,$.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,$.jsx)(`th`,{className:`text-right`,children:`CTR`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Position`})]})}),(0,$.jsxs)(`tbody`,{children:[b.length===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:6,className:`py-6 text-center text-secondary`,children:y.isPending?`Loading…`:l?`No ${r} match "${l}" in this window.`:`Bing named no ${r} in this window.`})}),b.map(i=>{let a=p===i.key;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.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,$.jsx)(c,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,$.jsx)(`td`,{className:`max-w-md text-strong`,children:r===`pages`?(0,$.jsx)(ys,{value:nu(i.key,t),title:i.key,className:`font-mono text-label-13`}):(0,$.jsx)(`span`,{className:`block truncate`,title:i.key,children:i.key})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:i.clicks.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:i.impressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:St(i.ctr)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:$l(i.avgImpressionPosition)})]}),a&&(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{}),(0,$.jsx)(`td`,{colSpan:5,className:`pb-4`,children:(0,$.jsx)(hu,{projectName:e,siteUrl:t,range:n,tab:r,rowKey:i.key})})]})]},i.key)})]})]})}),(0,$.jsx)(`div`,{className:`mt-2 flex justify-end`,children:(0,$.jsx)(Ss,{page:d,pageSize:ql,visibleRows:b.length,totalRows:x,disabled:y.isFetching,itemLabel:r,onPageChange:f})})]})}function hu({projectName:e,siteUrl:t,range:n,tab:r,rowKey:i}){let a={name:e},[o,s]=(0,Q.useState)(!1),c=w({...zi({client:K,path:a,query:{window:n,query:i,match:`exact`,groupBy:`week`}}),staleTime:Qn,enabled:r===`queries`}),l=w({...vi({client:K,path:a,query:{window:n,page:i,match:`exact`,groupBy:`week`}}),staleTime:Qn,enabled:r===`pages`}),u=w({...Ni({client:K,path:a,query:{query:i}}),staleTime:Qn,retry:!1,enabled:o&&r===`queries`}),f=w({...hi({client:K,path:a,query:{page:i}}),staleTime:Qn,retry:!1,enabled:o&&r===`pages`}),p=(r===`queries`?c.data?.weekly:l.data?.weekly)??[],m=r===`queries`?u:f,h=m.data?.rows??[],g=r===`queries`?`Pages`:`Queries`;return(0,$.jsxs)(`div`,{className:`grid gap-6 lg:grid-cols-[minmax(260px,1fr)_minmax(280px,1.4fr)]`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-1.5 text-label-13-strong text-strong`,children:`By week`}),(0,$.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Week`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Impr.`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Pos.`})]})}),(0,$.jsxs)(`tbody`,{children:[p.length===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:4,className:`py-3 text-secondary`,children:(r===`queries`?c:l).isPending?`Loading…`:`No weeks in this window.`})}),p.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums`,children:_a(e.date)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums`,children:e.clicks.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.impressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:$l(e.avgImpressionPosition)})]},e.date))]})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{className:`mb-1.5 flex items-baseline gap-2 text-label-13-strong text-strong`,children:[g,` for this `,r===`queries`?`query`:`page`,m.isSuccess&&(0,$.jsx)(`span`,{className:`text-label-12 text-secondary`,children:`from Bing, by week`})]}),!o&&(Y()?(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Not available here.`}):(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>s(!0),children:[(0,$.jsx)(v,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Load `,g.toLowerCase(),` from Bing`]}),(0,$.jsx)(X,{label:`Live`,text:Zl})]})),o&&m.isPending&&(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Asking Bing…`}),o&&m.isError&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(X,{tone:`caution`,label:`Bing refused this read`,text:`${Te(m.error)} Nothing was stored.`}),(0,$.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>void m.refetch(),children:[(0,$.jsx)(d,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Retry`]})]}),o&&m.isSuccess&&(h.length===0?(0,$.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[`Bing named no `,g.toLowerCase(),` for this `,r===`queries`?`query`:`page`,`.`]}):(0,$.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Week`}),(0,$.jsx)(`th`,{className:`text-left`,children:r===`queries`?`Page`:`Query`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Impr.`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Pos.`})]})}),(0,$.jsx)(`tbody`,{children:h.map((e,n)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.date?_a(e.date):`—`}),(0,$.jsx)(`td`,{className:`max-w-xs`,children:r===`queries`?(0,$.jsx)(ys,{value:nu(e.key,t),title:e.key,className:`font-mono`}):(0,$.jsx)(`span`,{className:`block truncate`,title:e.key,children:e.key})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums`,children:e.clicks.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.impressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:$l(e.avgImpressionPosition)})]},`${e.date}:${e.key}:${n}`))})]}))]})]})}function gu({projectName:e}){let t=w({...Ji({client:K,path:{name:e}}),staleTime:Qn}),[n,r]=(0,Q.useState)(null),i=t.data?.market,a=t.data?.rows??[];return(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsx)(`h3`,{children:`Search demand`}),i&&(0,$.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,$.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load search demand: `,Te(t.error)]}):(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`w-7`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Expand`})}),(0,$.jsx)(`th`,{className:`text-left`,children:`Tracked query`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Searches / week`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Latest week`})]})}),(0,$.jsxs)(`tbody`,{children:[a.length===0&&(0,$.jsx)(`tr`,{children:(0,$.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,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.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,$.jsx)(c,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})})}),(0,$.jsx)(`td`,{className:`text-strong`,children:t.query}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:eu(t.avgWeeklyImpressions)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:eu(t.latestImpressions)})]}),i&&(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{}),(0,$.jsx)(`td`,{colSpan:3,className:`pb-4`,children:(0,$.jsx)(_u,{projectName:e,query:t.query})})]})]},t.query)})]})]})})]})}function _u({projectName:e,query:t}){let n=w({...Ji({client:K,path:{name:e},query:{query:t}}),staleTime:Qn}),r=n.data?.history??[];return n.isPending?(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`Loading…`}):r.length===0?(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No weeks stored.`}):(0,$.jsxs)(`table`,{className:`data-table w-full max-w-md text-label-13`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Week`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Exact`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Broad`})]})}),(0,$.jsx)(`tbody`,{children:r.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums`,children:_a(e.date)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums`,children:e.impressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.broadImpressions.toLocaleString()})]},e.date))})]})}function vu({projectName:e,siteUrl:t,snapshots:n}){let r=S(),i={name:e},a=w({...Ui({client:K,path:i}),staleTime:Qn}),o=w({...Mi({client:K,path:i}),staleTime:Qn}),s=w({...mi({client:K,path:i,query:{days:`30`}}),staleTime:Qn}),[c,l]=(0,Q.useState)(`not-indexed`),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),v=iu(ru(n,`url-submission-quota`)),y=a.data?.summary,b=s.data?.rows[0],x=a.data?.notIndexed??[],C=a.data?.unknown??[],T=a.data?.indexed??[],E=o.data??[];async function D(t,n){d(!0),_(null);try{let{succeeded:i,failed:a,total:o}=(await Yt(e,t)).summary;Xn({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 Zn(r,`bing`)}catch(t){let r=Te(t);_(r),Xn({title:`Bing submission failed`,detail:r,tone:`negative`,dedupeKey:`bing:indexing:${e}:${n}`,dedupeMode:`replace`})}finally{d(!1)}}async function O(){if(f.trim()){_(null);try{let t=await Mt(e,f.trim());h(t),await Zn(r,`bing`)}catch(e){_(Te(e))}}}let k=y?[{label:`Indexed`,value:y.indexed.toLocaleString()},{label:`Not in index`,value:(y.notIndexed+(y.unknown??0)).toLocaleString(),tooltip:`Pages Bing has not confirmed in its index, including those with an unknown status.`},{label:`Status unknown`,value:(y.unknown??0).toLocaleString()},{label:`Coverage`,value:St(y.percentage,ye.percent)}]:[],A=ws({rows:c===`not-indexed`?x:c===`unknown`?C:c===`indexed`?T:[],pageSize:ql}),j=ws({rows:E,pageSize:ql}),M=ws({rows:s.data?.rows??[],pageSize:ql}),N=[{key:`not-indexed`,label:`Not indexed (${x.length})`},{key:`unknown`,label:`Status unknown (${C.length})`},{key:`indexed`,label:`Indexed (${T.length})`},{key:`inspections`,label:`Inspections (${E.length})`},{key:`crawl`,label:`Crawl by day`}],P=!Y()&&(c===`not-indexed`||c===`unknown`)&&(c===`not-indexed`?x.length:C.length)>0;return(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,$.jsx)(`h3`,{children:`Index and crawl`}),b&&b.crawlErrors>0&&(0,$.jsx)(X,{tone:`caution`,label:`${b.crawlErrors.toLocaleString()} crawl error${b.crawlErrors===1?``:`s`}`,text:`Bingbot got errors from ${b.crawlErrors===1?`one URL`:`${b.crawlErrors.toLocaleString()} URLs`} on ${_a(b.date)}. Crawl by day has the codes.`})]}),(0,$.jsx)(`p`,{className:`text-copy-13 text-muted`,children:a.data?.lastInspectedAt?`Last inspected ${Mn(a.data.lastInspectedAt)}`:`No inspection history yet`})]}),(0,$.jsx)(`div`,{className:`space-y-4`,children:k.length>0?(0,$.jsx)(ll,{label:`Bing index coverage`,items:k}):(0,$.jsx)(`p`,{className:`text-copy-13 text-muted`,children:`No coverage data yet. Inspect URLs to build coverage data.`})}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-end justify-between gap-3 border-b border-base`,children:[(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1`,role:`tablist`,"aria-label":`Bing index and crawl lists`,children:N.map(e=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":c===e.key,className:`border-b-2 px-3 py-1.5 text-button-14 transition-colors ${c===e.key?`border-mono-200 text-strong`:`border-transparent text-muted hover:text-neutral`}`,onClick:()=>{l(e.key),A.setPage(1)},children:e.label},e.key))}),P&&(0,$.jsxs)(`div`,{className:`mb-1.5 flex flex-wrap items-center gap-2`,children:[v&&(0,$.jsxs)(`span`,{className:`text-label-13 text-secondary`,children:[v.dailyQuota.toLocaleString(),` submissions left today`]}),(0,$.jsx)(hs,{size:`sm`,variant:`outline`,disabled:u,onClick:Jn(()=>D({allUnindexed:!0},`all`)),children:u?`Submitting…`:`Submit all to Bing`})]})]}),g&&(0,$.jsx)(`p`,{className:`mt-2 text-copy-13 text-negative`,children:g}),(0,$.jsxs)(`div`,{className:`mt-2 overflow-x-auto`,children:[(c===`not-indexed`||c===`unknown`||c===`indexed`)&&(()=>{let e=c!==`indexed`&&!Y();return(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-right`,children:c===`not-indexed`?`HTTP`:`Last crawled`}),e&&(0,$.jsx)(`th`,{className:`text-right`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Action`})})]})}),(0,$.jsxs)(`tbody`,{children:[A.totalRows===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:e?3:2,className:`py-6 text-center text-secondary`,children:a.isPending?`Loading…`:`None.`})}),A.rows.map(n=>(0,$.jsxs)(`tr`,{className:`group`,children:[(0,$.jsx)(`td`,{className:`max-w-lg`,children:(0,$.jsx)(ys,{value:nu(n.url,t),title:n.url,className:`font-mono text-label-13 text-neutral`})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:c===`not-indexed`?n.httpCode??`—`:n.lastCrawledDate?Mn(n.lastCrawledDate):`—`}),e&&(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(`div`,{className:`opacity-0 transition-opacity group-hover:opacity-100 group-focus-within:opacity-100 pointer-coarse:opacity-100`,children:(0,$.jsx)(hs,{size:`sm`,variant:`ghost`,disabled:u,onClick:Jn(()=>D({urls:[n.url]},n.url)),children:`Submit`})})})]},n.id))]})]})})(),(c===`not-indexed`||c===`unknown`||c===`indexed`)&&(0,$.jsx)(Ss,{page:A.page,pageSize:ql,visibleRows:A.rows.length,totalRows:A.totalRows,onPageChange:A.setPage,itemLabel:`URLs`}),c===`inspections`&&(0,$.jsxs)(`div`,{className:`space-y-3 pt-2`,children:[!Y()&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row`,children:[(0,$.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:f,onChange:e=>p(e.target.value),onKeyDown:e=>{e.key===`Enter`&&O()}}),(0,$.jsx)(hs,{size:`sm`,disabled:!f.trim(),onClick:Jn(O),children:`Inspect`})]}),m&&(0,$.jsxs)(`div`,{className:`material-base space-y-1 p-3 text-label-13`,children:[(0,$.jsx)(`div`,{className:`text-label-13-strong text-strong`,children:m.url}),(0,$.jsxs)(`div`,{className:`text-secondary`,children:[`In index: `,(0,$.jsx)(`span`,{className:m.inIndex?`text-positive`:`text-negative`,children:m.inIndex?`Yes`:`No`}),` · `,`HTTP: `,m.httpCode??`—`,` · `,`Crawled: `,m.lastCrawledDate??`—`]})]}),(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Index`}),(0,$.jsx)(`th`,{className:`text-right`,children:`HTTP`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Inspected`})]})}),(0,$.jsxs)(`tbody`,{children:[E.length===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:4,className:`py-6 text-center text-secondary`,children:o.isPending?`Loading…`:`No inspections yet.`})}),j.rows.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-lg`,children:(0,$.jsx)(ys,{value:nu(e.url,t),title:e.url,className:`font-mono text-label-13 text-neutral`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:e.inIndex?`positive`:`negative`,children:e.inIndex?`Yes`:`No`})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.httpCode??`—`}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Mn(e.inspectedAt)})]},e.id))]})]}),(0,$.jsx)(Ss,{page:j.page,pageSize:ql,visibleRows:j.rows.length,totalRows:j.totalRows,onPageChange:j.setPage,itemLabel:`inspections`})]}),c===`crawl`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Day`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Crawled`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Errors`}),(0,$.jsx)(`th`,{className:`text-right`,children:`In index`}),(0,$.jsx)(`th`,{className:`text-right`,children:`2xx`}),(0,$.jsx)(`th`,{className:`text-right`,children:`301`}),(0,$.jsx)(`th`,{className:`text-right`,children:`302`}),(0,$.jsx)(`th`,{className:`text-right`,children:`4xx`}),(0,$.jsx)(`th`,{className:`text-right`,children:`5xx`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Other`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Robots.txt`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Timeouts`}),(0,$.jsx)(`th`,{className:`text-right`,children:`DNS`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Malware`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Inbound links`})]})}),(0,$.jsxs)(`tbody`,{children:[(s.data?.rows??[]).length===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:15,className:`py-6 text-center text-secondary`,children:s.isPending?`Loading…`:`No crawl stats stored yet.`})}),M.rows.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums`,children:_a(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,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:e.toLocaleString()},t))]},e.date))]})]}),(0,$.jsx)(Ss,{page:M.page,pageSize:ql,visibleRows:M.rows.length,totalRows:M.totalRows,onPageChange:M.setPage,itemLabel:`days`})]})]})]})}function yu(e){let t=e.toLowerCase();return t===`success`?`positive`:t.includes(`error`)||t.includes(`fail`)?`negative`:t.includes(`warn`)?`caution`:`neutral`}function bu({projectName:e,siteUrl:t}){let{canWrite:n}=qn(),r=w({...bi({client:K,path:{name:e}}),staleTime:Qn}),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(new Set),c=r.data?.sitemaps??[],l=e=>{let n=e.type.toLowerCase().includes(`index`);return{url:e.url,label:nu(e.url,t),isIndex:n,kind:!n&&e.type.toLowerCase()!==`sitemap`?e.type:void 0,status:{label:e.status,tone:yu(e.status)},urls:e.urlCount,submittedAt:e.submittedAt,lastReadAt:e.lastCrawledAt}},u=c.filter(e=>e.parentUrl===null||!c.some(t=>t.parentUrl===null&&t.url===e.parentUrl)).map(e=>{let t=l(e);return t.isIndex?{...t,files:c.filter(t=>t.parentUrl===e.url).map(l)}:t});async function d(t){a(t);try{await Ft(e,{sitemapUrl:t}),Xn({title:`Checking sitemap URLs in Bing`,detail:`Coverage updates when the check finishes.`,tone:`neutral`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}catch(t){Xn({title:`Sitemap check could not start`,detail:Te(t),tone:`negative`,dedupeKey:`bing:inspect-sitemap:${e}`,dedupeMode:`replace`})}finally{a(null)}}return(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Sitemaps`}),(0,$.jsx)(X,{text:`What Bing reported for each submitted sitemap at the last sync. Inspect URLs checks every page in a sitemap against Bing's index.`})]}),r.data?.syncedAt&&(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`As of `,Mn(r.data.syncedAt)]})]}),r.isError?(0,$.jsxs)(`p`,{className:`text-copy-14 text-negative`,children:[`Could not load sitemaps: `,Te(r.error)]}):(0,$.jsx)(Dl,{rows:u,expanded:o,onToggle:e=>s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),lastReadLabel:`Last crawled`,empty:r.isPending?`Loading…`:`Bing lists no sitemaps for this site.`,actions:Y()?void 0:e=>(0,$.jsx)(El,{disabled:!n||i!==null,title:n?void 0:Kn,onClick:()=>void d(e.url),children:i===e.url?`Starting…`:`Inspect URLs`})})]})}var xu=`Bing shows this only to the site owner key. Not a failure.`;function Su({siteUrl:e,snapshots:t}){let n=iu(ru(t,`url-submission-quota`)),r=iu(ru(t,`content-submission-quota`)),i=au(ru(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:xu};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=ru(t,n),s=ou(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,$.jsx)(Cu,{label:r,value:c,help:l,note:u?`from an earlier sync`:void 0,children:s&&s.length>0?(0,$.jsxs)(`div`,{className:`overflow-x-auto`,children:[u&&(0,$.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,$.jsxs)(`table`,{className:`data-table w-full text-label-13`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsx)(`tr`,{children:d.map(e=>(0,$.jsx)(`th`,{className:`text-left`,children:e.label},e.key))})}),(0,$.jsx)(`tbody`,{children:s.map((t,n)=>(0,$.jsx)(`tr`,{children:d.map(n=>{let r=t[n.key]??t[n.key.charAt(0).toUpperCase()+n.key.slice(1)];return(0,$.jsx)(`td`,{className:n.key.toLowerCase()===`url`?`max-w-md`:`text-secondary`,children:n.key.toLowerCase()===`url`&&typeof r==`string`?(0,$.jsx)(ys,{value:nu(r,e),title:r,className:`font-mono text-neutral`}):cu(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,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsx)(`h3`,{children:`Site settings`})}),(0,$.jsxs)(`div`,{role:`list`,"aria-label":`Bing site settings`,children:[c(`blocked-urls`),c(`crawl-issues`),(0,$.jsx)(Cu,{label:`URL submissions left`,value:l(n),help:`URL submissions Bing will still accept, as of the last sync.`}),(0,$.jsx)(Cu,{label:`Content submissions left`,value:l(r)}),(0,$.jsx)(Cu,{label:`Crawl boost`,value:i?i.crawlBoostEnabled?`On`:i.crawlBoostAvailable?`Off`:`Not offered`:`—`}),i&&i.crawlRate.length===24&&(0,$.jsx)(Cu,{label:`Crawl rate by hour`,value:`24 hours`,children:(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table text-label-13`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsx)(`tr`,{children:i.crawlRate.map((e,t)=>(0,$.jsx)(`th`,{className:`text-right`,children:t},t))})}),(0,$.jsx)(`tbody`,{children:(0,$.jsx)(`tr`,{children:i.crawlRate.map((e,t)=>(0,$.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 Cu({label:e,value:t,help:n,note:r,children:i}){let[a,s]=(0,Q.useState)(!1),c=(0,$.jsx)(`span`,{className:`flex-1 text-label-14 text-strong`,children:e}),l=(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-14 tabular-nums text-secondary`,children:[r&&(0,$.jsx)(`span`,{className:`text-label-12 text-caution`,children:r}),t]});return i?(0,$.jsx)(`div`,{role:`listitem`,className:`border-t border-default first:border-t-0`,children:(0,$.jsxs)(`details`,{className:`group`,onToggle:e=>s(e.currentTarget.open),children:[(0,$.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,$.jsx)(o,{className:`h-3.5 w-3.5 shrink-0 text-secondary transition-transform group-open:rotate-90`,"aria-hidden":`true`}),c,l]}),a&&(0,$.jsx)(`div`,{className:`pb-4 pl-5.5`,children:i})]})}):(0,$.jsxs)(`div`,{role:`listitem`,className:`flex items-center gap-2 border-t border-default py-2.5 first:border-t-0`,children:[(0,$.jsx)(`span`,{className:`w-3.5 shrink-0`,"aria-hidden":`true`}),c,l,n&&(0,$.jsx)(X,{text:n})]})}var wu=ua[0],Tu=ua[1],Eu=ua[2],Du=ua[3],Ou=[`both`,`server`,`ga4`],ku={fontSize:12,paddingTop:6},Au=e=>typeof e==`number`?hn(Math.round(e)):String(e),ju=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function Mu(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 Nu(e,t){return n=>{let{cx:r,cy:i,index:a,key:o}=n,s=a??-1;return e[s]==null||e[s-1]!=null||e[s+1]!=null||r===void 0||i===void 0?(0,$.jsx)(`g`,{},o):(0,$.jsx)(`circle`,{cx:r,cy:i,r:2.6,fill:t,stroke:`none`},o)}}function Pu({projectName:e,sinceMinutes:t}){let[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(`both`),c=Rs(e,{sinceMinutes:t,granularity:`day`,limit:1}),l=Vs(e),u=w({...ir({client:K,path:{name:e}}),enabled:!!e,staleTime:er}).data?.connected===!0,d=w({...hr({client:K,path:{name:e},query:{window:t>=129600?`90d`:t>=43200?`30d`:`7d`}}),enabled:!!e&&u,staleTime:er}),f=(0,Q.useMemo)(()=>c.data?.series?.points??[],[c.data]),p=(0,Q.useMemo)(()=>{let e=d.data;return new Map((e?.days??[]).map(e=>[e.date,e.sessions]))},[d.data]),m=(0,Q.useMemo)(()=>{let e=e=>e.measured!==!1;if(f.length===0||e(f[0]))return null;let t=f.findIndex(e)-1;return t<0?{from:f[0].bucket,to:f[f.length-1].bucket}:{from:f[0].bucket,to:f[t].bucket}},[f]),h=c.data?.series?.coverageStart??null,g=c.data?.series?.trends,_=(0,Q.useMemo)(()=>{let e=Mu(g?.crawlerContentHits,f.length),t=Mu(g?.aiUserFetchHits,f.length),n=Mu(g?.aiReferralLandedHits,f.length);return f.map((r,i)=>({...r,crawlerContentHits:r.measured===!1?null:ju(r.crawlerContentHits),aiUserFetchHits:r.measured===!1?null:ju(r.aiUserFetchHits),aiReferralLandedHits:r.measured===!1?null:ju(r.aiReferralLandedHits),ga4Visits:p.get(r.bucket)??null,crawlTrend:e[i],fetchTrend:t[i],visitTrend:n[i]}))},[f,p,g]),v=c.data?.totals,y=v&&{crawlers:ju(v.crawlerContentHits),fetches:ju(v.aiUserFetchHits),visits:ju(v.aiReferralLandedHits)},b=(0,Q.useMemo)(()=>f.reduce((e,t)=>({crawlers:e.crawlers+ju(t.crawlerContentHits),fetches:e.fetches+ju(t.aiUserFetchHits),visits:e.visits+ju(t.aiReferralLandedHits)}),{crawlers:0,fetches:0,visits:0}),[f]),x=y??b,S=x.crawlers>0||x.fetches>0||x.visits>0;if(c.isLoading)return(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading AI traffic history…`});if(c.isError)return(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load AI traffic history.`}),(0,$.jsx)(X,{text:`The request failed, so this is not a reading of zero activity. Retry, or check the traffic source.`})]});if(!S){let e=l.data?.sources,t=e!==void 0&&e.length===0,n=!t&&h===null;return(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.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,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`mb-5`,children:(0,$.jsx)(ll,{label:`AI traffic totals`,items:[{label:`AI crawlers`,value:hn(x.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:hn(x.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:hn(x.visits),detail:`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.`}]})}),f.length>0&&(0,$.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,$.jsx)(`span`,{className:`text-secondary text-label-12-strong`,children:`Latest day (UTC)`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:ju(f[f.length-1].crawlerContentHits).toLocaleString()}),`pages crawled`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:ju(f[f.length-1].aiUserFetchHits).toLocaleString()}),`page fetches`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:ju(f[f.length-1].aiReferralLandedHits).toLocaleString()}),`visits, server`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading text-label-12-strong tabular-nums mr-1`,children:p.get(f[f.length-1].bucket)?.toLocaleString()??`—`}),`visits, GA4`]}),(0,$.jsx)(`span`,{className:`text-faint`,children:`still filling`})]}),(0,$.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:`Machines reading your site`}),(0,$.jsx)(X,{text:`Crawlers index pages for later. Page fetches happen while an engine is answering someone. Both are machines, not people.`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-label-12 text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>r(e.target.checked),className:`accent-current`}),`Page fetches`]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 text-label-12 text-secondary cursor-pointer`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked),className:`accent-current`}),`Trend line`]})]})]}),(0,$.jsx)(I,{width:`100%`,height:206,children:(0,$.jsxs)(te,{data:_,margin:{top:4,right:8,left:-18,bottom:0},children:[(0,$.jsx)(M,{stroke:xa,vertical:!1}),(0,$.jsx)(P,{dataKey:`bucket`,tick:va,stroke:Ca,tickFormatter:fa,minTickGap:28}),(0,$.jsx)(z,{tick:va,stroke:Ca,width:48,allowDecimals:!1}),(0,$.jsx)(N,{contentStyle:Sa.contentStyle,labelStyle:Sa.labelStyle,itemStyle:Sa.itemStyle,labelFormatter:_a,formatter:Au}),m&&(0,$.jsx)(F,{x1:m.from,x2:m.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,$.jsx)(R,{wrapperStyle:ku,iconType:`plainline`,iconSize:14}),(0,$.jsx)(L,{type:`monotone`,dataKey:`crawlerContentHits`,name:`Pages crawled`,stroke:wu,fill:wu,fillOpacity:.22,strokeWidth:1.8}),n&&(0,$.jsx)(L,{type:`monotone`,dataKey:`aiUserFetchHits`,name:`Page fetches`,stroke:Tu,fill:Tu,fillOpacity:.18,strokeWidth:1.6}),i&&(0,$.jsx)(ee,{type:`linear`,dataKey:`crawlTrend`,legendType:`none`,name:`Pages crawled trend`,dot:!1,tooltipType:`none`,stroke:wu,strokeWidth:1.4,strokeDasharray:`5 4`,connectNulls:!0}),i&&n&&(0,$.jsx)(ee,{type:`linear`,dataKey:`fetchTrend`,legendType:`none`,name:`Page fetches trend`,dot:!1,tooltipType:`none`,stroke:Tu,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0})]})}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3 mt-5 mb-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:`People arriving from AI`}),(0,$.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,$.jsx)(tl,{windows:Ou,value:o,onChange:s,label:`Visit measurement source`,formatOption:e=>e===`ga4`?`GA4`:e===`both`?`Both`:`Server`})]}),(0,$.jsx)(I,{width:`100%`,height:176,children:(0,$.jsxs)(te,{data:_,margin:{top:4,right:8,left:-18,bottom:0},children:[(0,$.jsx)(M,{stroke:xa,vertical:!1}),(0,$.jsx)(P,{dataKey:`bucket`,tick:va,stroke:Ca,tickFormatter:fa,minTickGap:28}),(0,$.jsx)(z,{tick:va,stroke:Ca,width:48,allowDecimals:!1}),(0,$.jsx)(N,{contentStyle:Sa.contentStyle,labelStyle:Sa.labelStyle,itemStyle:Sa.itemStyle,labelFormatter:_a,formatter:Au}),m&&(0,$.jsx)(F,{x1:m.from,x2:m.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,$.jsx)(R,{wrapperStyle:ku,iconType:`plainline`,iconSize:14}),o!==`ga4`&&(0,$.jsx)(ee,{type:`monotone`,dataKey:`aiReferralLandedHits`,name:`Visits, server`,stroke:Eu,strokeWidth:2,dot:!1}),o!==`server`&&(0,$.jsx)(ee,{type:`monotone`,dataKey:`ga4Visits`,name:`Visits, GA4`,connectNulls:!1,stroke:Du,strokeWidth:1.8,strokeDasharray:`5 3`,dot:Nu(_.map(e=>e.ga4Visits),Du)}),i&&o!==`ga4`&&(0,$.jsx)(ee,{type:`linear`,dataKey:`visitTrend`,legendType:`none`,name:`Visits trend`,dot:!1,tooltipType:`none`,stroke:Eu,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0})]})})]})}function Fu(e){return e.replace(/\+/g,` `)}var Iu=[`7d`,`30d`,`90d`],Lu={"7d":10080,"30d":43200,"90d":129600,all:129600};function Ru(e){return bs(e.landingPage)}var zu=25,Bu=10,Vu={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0,byEngine:{series:[],otherCount:0,days:[]}},Hu={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 Uu(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 Wu(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Gu(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 Ku({projectName:e}){let{data:t,isLoading:n,isError:r}=zs(e),i=t?.sources??[];return(0,$.jsxs)(`section`,{"aria-labelledby":`server-activity-heading`,children:[(0,$.jsx)(al,{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:!Y()&&i.length>0?(0,$.jsx)(A,{to:`/traffic`,className:`text-label-14 text-link hover:underline`,children:`Manage sources`}):void 0}),n?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading server activity…`}):r?(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load server activity.`}):i.length===0?(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`No traffic source connected.`,` `,!Y()&&(0,$.jsx)(A,{to:`/traffic`,className:`text-link hover:underline`,children:`Connect a source`})]}):(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(dl,{label:`Source`,align:`left`}),(0,$.jsx)(dl,{label:`Status`,align:`left`}),(0,$.jsx)(dl,{label:`Crawler hits`,align:`right`}),(0,$.jsx)(dl,{label:`AI hits`,align:`right`}),(0,$.jsx)(dl,{label:`AI sessions`,align:`right`}),(0,$.jsx)(dl,{label:`Last sync`,align:`right`}),(0,$.jsx)(`th`,{className:`py-2`,"aria-label":`Detail`})]})}),(0,$.jsx)(`tbody`,{children:i.map(t=>(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-2 pr-3 text-strong`,children:t.displayName}),(0,$.jsx)(`td`,{className:`py-2 pr-3`,children:(0,$.jsx)(J,{tone:Hs(t.status),children:t.status})}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums text-primary`,children:t.totals24h.crawlerHits.toLocaleString(`en-US`)}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums text-primary`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center justify-end gap-1`,children:[t.totals24h.aiUserFetchHits.toLocaleString(`en-US`),t.totals24h.aiUserFetchLikelyFakeHits>0&&(0,$.jsx)(X,{text:Ks(t.totals24h.aiUserFetchLikelyFakeHits)})]})}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right tabular-nums text-primary`,children:t.totals24h.aiReferralLandedHits.toLocaleString(`en-US`)}),(0,$.jsx)(`td`,{className:`py-2 pl-4 text-right text-secondary`,children:t.lastSyncedAt?Uu(t.lastSyncedAt):`never`}),(0,$.jsx)(`td`,{className:`py-2 pl-3 text-right`,children:!Y()&&(0,$.jsx)(A,{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 qu({projectName:e}){let[t,n]=(0,Q.useState)(`30d`);return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(Ku,{projectName:e}),(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsx)(nd,{projectName:e,window:t,periodControl:(0,$.jsx)(tl,{windows:Iu,value:t,onChange:n,label:`Traffic time period`}),between:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsxs)(`section`,{"aria-labelledby":`ai-traffic-history-heading`,children:[(0,$.jsx)(al,{id:`ai-traffic-history-heading`,title:`AI traffic history`,tooltip:Hu.aiHistoryTooltip}),(0,$.jsx)(Pu,{projectName:e,sinceMinutes:Lu[t]})]})]})})]})}var Ju={session:`Session`,first_user:`First visit`,manual_utm:`UTM`},Yu={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)`},Xu=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Attribution`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}],Zu=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}];function Qu(e){return e.engine===null}function $u({row:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`td`,{className:`max-w-[220px] truncate py-1.5 pr-3 text-strong`,title:e.source,children:e.source}),(0,$.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:e.medium}),(0,$.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,$.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:Yu[e.sourceDimension]??``,children:Ju[e.sourceDimension]??e.sourceDimension}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:St(e.share)})]})}function ed({row:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`td`,{className:`max-w-[240px] truncate py-1.5 pr-3 text-strong`,title:e.source,children:Fu(e.source)}),(0,$.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:Fu(e.medium)}),(0,$.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,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:St(e.share)})]})}function td(e,t){let n=S(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!0),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(Vu),[y,b]=(0,Q.useState)([]),[x,C]=(0,Q.useState)(null);async function w(r){c(!0),m(null);try{let a=await n.fetchQuery({...ir({client:K,path:{name:e}}),staleTime:er});if(r.current)return;if(i(a),!a.connected){o(null),v(Vu),b([]),C(null),c(!1);return}let s=t===`all`?void 0:t,[l,u,d,f]=await Promise.all([n.fetchQuery({...Ei({client:K,path:{name:e},query:s?{window:s}:void 0}),staleTime:er}),n.fetchQuery({...hr({client:K,path:{name:e},query:s?{window:s}:void 0}),staleTime:er}).catch(()=>Vu),n.fetchQuery({...ki({client:K,path:{name:e},query:s?{window:s}:void 0}),staleTime:er}).catch(()=>[]),n.fetchQuery({...fr({client:K,path:{name:e},query:{window:Je(t)?t:`30d`}}),staleTime:er}).catch(()=>null)]);if(r.current)return;o(l),v(u),b(d),C(f),c(!1)}catch(e){if(r.current)return;m(e instanceof Error?e.message:`Failed to load GA4 data`),c(!1)}}(0,Q.useEffect)(()=>{let e={current:!1};return w(e),()=>{e.current=!0}},[e,t,n]);async function T(){u(!0),m(null),g(null);try{let t=await Ct(e);g(`Synced ${t.rowCount.toLocaleString()} page rows, ${t.aiReferralCount.toLocaleString()} AI and ${t.socialReferralCount.toLocaleString()} social referral rows (${t.days} days)`),await Zn(n,`ga`),await w({current:!1})}catch(e){m(e instanceof Error?e.message:`Sync failed`)}finally{u(!1)}}async function E(){f(!0),m(null),g(null);try{await ae(e),await Zn(n,`ga`),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),o(null),C(null),g(`GA4 disconnected`)}catch(e){m(e instanceof Error?e.message:`Disconnect failed`)}finally{f(!1)}}async function D(){await Zn(n,`ga`),await w({current:!1})}return{status:r,traffic:a,loading:s,syncing:l,disconnecting:d,error:p,notice:h,aiDaily:_,sessionHistory:y,overview:x,handleSync:T,handleDisconnect:E,handleConnected:D}}function nd({projectName:e,window:t,periodControl:n,between:r}){let i=td(e,t??`30d`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(rd,{ga:i,projectName:e,periodControl:n}),r,(0,$.jsx)(id,{ga:i,projectName:e})]})}function rd({ga:e,projectName:t,periodControl:n}){let{status:r,traffic:i,syncing:a,disconnecting:o,handleSync:s,handleDisconnect:c}=e,l=r?.connected===!0,f=l&&!Y()&&!Ze(),p=i?Gu(i.windowStart,i.windowEnd):null,m;return m=e.loading&&!r?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Loading traffic data…`}):l?i&&e.overview?(0,$.jsx)(Cl,{overview:e.overview,refreshing:e.loading}):i?(0,$.jsx)($.Fragment,{children:(0,$.jsx)(ll,{label:`Site traffic`,items:[{label:`Total sessions`,value:Wu(i.totalSessions),detail:i.totalSessions.toLocaleString()},{label:`Organic sessions`,value:Wu(i.totalOrganicSessions),detail:`${i.organicSharePctDisplay} of total`},{label:`Total users`,value:i.totalUsers===null?`n/a`:Wu(i.totalUsers),detail:i.totalUsers===null?`Unavailable for this range`:i.totalUsers.toLocaleString()}]})}):(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-y border-default py-4`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No traffic data yet.`}),!Y()&&!Ze()&&(0,$.jsxs)(q,{variant:`outline`,size:`sm`,disabled:a,onClick:Jn(s),children:[(0,$.jsx)(d,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),`Sync from GA4`]})]}):Y()||Ze()?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Google Analytics 4 property connected.`}):(0,$.jsx)(pd,{projectName:t,onConnected:()=>{e.handleConnected()}}),(0,$.jsxs)(`section`,{"aria-labelledby":`site-traffic-heading`,children:[(0,$.jsx)(al,{id:`site-traffic-heading`,title:`Site traffic`,tooltip:e.overview?Hu.siteTrafficTooltip:p?`${Hu.siteTrafficFallbackTooltip} Data covers ${p}.`:Hu.siteTrafficFallbackTooltip,meta:l?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`inline-block size-2 rounded-full bg-positive-500`}),`GA4 property `,(0,$.jsx)(`span`,{className:`text-strong`,children:r.propertyId}),r.clientEmail&&(0,$.jsxs)(`span`,{className:`text-muted`,children:[`· `,r.clientEmail]})]}):void 0,actions:n||f?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n,f&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(q,{variant:`outline`,size:`sm`,disabled:a,onClick:Jn(s),children:[(0,$.jsx)(d,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),a?`Syncing…`:`Sync`]}),(0,$.jsxs)(q,{variant:`ghost`,size:`sm`,className:`text-negative-400 hover:text-negative`,disabled:o,onClick:Jn(c),children:[(0,$.jsx)(u,{className:`mr-1.5 size-3.5`}),`Disconnect`]})]})]}):void 0}),e.error&&(0,$.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,$.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}),m]})}function id({ga:e,projectName:t}){let{traffic:n,aiDaily:r,sessionHistory:i}=e,[a,o]=(0,Q.useState)({key:`sessions`,dir:`desc`}),[s,c]=(0,Q.useState)({key:`sessions`,dir:`desc`}),l=(0,Q.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]),u=ws({rows:l,getSearchText:e=>bs(e.landingPage),pageSize:Bu}),d=(0,Q.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]),f=ws({rows:d,getSearchText:Ru,pageSize:zu}),p=(0,Q.useMemo)(()=>i.map(e=>({date:e.date,value:e.sessions})),[i]);function m(e){u.setPage(1),o(t=>t.key===e?{key:e,dir:t.dir===`desc`?`asc`:`desc`}:{key:e,dir:`desc`})}function h(e){f.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 g=n?Gu(n.windowStart,n.windowEnd):null,_=n?.channelBreakdown,v=n?.paidAiSessionsBySession??0,y=n?.aiEngines??[],b=n?.socialPlatforms??[],x=b[0]??null,S=f.totalRows>0?`${f.totalRows.toLocaleString()} ${f.hasQuery?f.totalRows===1?`match`:`matches`:f.totalRows===1?`row`:`rows`}`:f.hasQuery&&(n?.aiReferralLandingPages.length??0)>0?`0 matches`:null;return(0,$.jsxs)($.Fragment,{children:[n&&_&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsxs)(`section`,{"aria-labelledby":`traffic-by-channel-heading`,children:[(0,$.jsx)(al,{id:`traffic-by-channel-heading`,title:`Traffic by channel`,tooltip:Hu.channelTooltip,meta:g}),(0,$.jsx)(ll,{label:`Sessions by channel`,items:[{label:`Organic search`,value:_.organic.sharePctDisplay,detail:`${_.organic.sessions.toLocaleString()} sessions`,tooltip:Hu.organicTooltip},{label:`Social`,value:_.social.sharePctDisplay,detail:`${_.social.sessions.toLocaleString()} sessions`,tooltip:Hu.socialTooltip},{label:`Direct`,value:_.direct.sharePctDisplay,detail:`${_.direct.sessions.toLocaleString()} sessions`,tooltip:Hu.directTooltip},{label:`AI (at least)`,value:_.ai.sharePctDisplay,detail:v>0?`${_.ai.sessions.toLocaleString()} sessions · ${v.toLocaleString()} paid`:`${_.ai.sessions.toLocaleString()} sessions`,tooltip:Hu.aiTooltip},{label:`Other channels`,value:_.other.sharePctDisplay,detail:`${_.other.sessions.toLocaleString()} sessions`,tooltip:Hu.otherTooltip}]}),(0,$.jsxs)(ol,{children:[(0,$.jsx)(sl,{label:Hu.aiChartLabel,meta:r.days.length>0?ad(r.totalSessions,`session`):Hu.noneInPeriod,children:r.days.length>0?(0,$.jsx)(gl,{input:r.byEngine,baseline:p,baselineLabel:`Total sessions`,label:Hu.aiChartLabel}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Hu.noAiReferrals})}),(0,$.jsx)(sl,{label:`Where AI visitors came from`,meta:y.length>0?`${ad(y.filter(e=>e.engine!==null).length,`engine`)} · ${ad(n.aiReferrals.length,`source`)}`:Hu.noneInPeriod,children:y.length>0?(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,$.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,$.jsx)(ml,{groups:y,groupLabel:`Engine`,caption:`AI referral sessions by engine`,childColumns:Xu,childRowKey:e=>`${e.source}:${e.medium}:${e.sourceDimension}:${e.trafficClass}`,renderChildCells:e=>(0,$.jsx)($u,{row:e}),pinLast:Qu})}),(0,$.jsx)(X,{text:Hu.aiEnginesTooltip})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Hu.noAiReferrals})}),(0,$.jsx)(sl,{label:`Pages AI visitors landed on`,meta:S??Hu.noneInPeriod,children:n.aiReferralLandingPages.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Os,{value:f.query,onChange:f.setQuery,label:`Filter landing page URLs or query parameters`,placeholder:`Filter URL or query parameters`,className:`mb-4 max-w-md`}),f.totalRows>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(ul,{label:`Landing page`,sortKey:`landingPage`,current:s.key,dir:s.dir,onSort:h,align:`left`}),(0,$.jsx)(ul,{label:`Source`,sortKey:`source`,current:s.key,dir:s.dir,onSort:h,align:`left`}),(0,$.jsx)(dl,{label:`Attribution`,align:`left`}),(0,$.jsx)(ul,{label:`Sessions`,sortKey:`sessions`,current:s.key,dir:s.dir,onSort:h,align:`right`})]})}),(0,$.jsx)(`tbody`,{children:f.rows.map(e=>(0,$.jsx)(hd,{row:e},`${e.landingPage}:${e.source}:${e.medium}:${e.sourceDimension}`))})]})}),(0,$.jsx)(Ss,{page:f.page,pageSize:f.pageSize,visibleRows:f.rows.length,totalRows:f.totalRows,onPageChange:f.setPage,itemLabel:f.hasQuery?`matches`:`rows`})]}):(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 py-4`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No landing pages match this filter`}),(0,$.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>f.setQuery(``),children:`Clear filter`})]})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Hu.noAiLandingPages})})]})]}),(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsxs)(`section`,{"aria-labelledby":`social-heading`,children:[(0,$.jsx)(al,{id:`social-heading`,title:`Social`,tooltip:Hu.socialTooltip2,meta:g}),(0,$.jsx)(ll,{label:`Social sessions`,items:[{label:`Social sessions`,value:n.socialSessions.toLocaleString(),detail:`${n.socialSharePctDisplay} of all sessions`},{label:`Platforms`,value:String(b.length),detail:`${n.socialReferrals.length} sources`,tooltip:Hu.platformsTooltip},{label:`Paid social`,value:(n.paidSocialSessions??0).toLocaleString(),detail:`${St(n.paidSocialShare??0)} of social`,tooltip:Hu.paidSocialTooltip},{label:`Top platform`,value:x?.label??`None`,detail:x?`${x.sessions.toLocaleString()} sessions`:void 0}]}),(0,$.jsxs)(ol,{children:[(0,$.jsx)(sl,{label:Hu.socialChartLabel,meta:b.length>0?ad(n.socialSessions,`session`):Hu.noneInPeriod,children:b.length>0?(0,$.jsx)(gl,{input:n.socialPlatformDaily,label:Hu.socialChartLabel}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Hu.noSocial})}),(0,$.jsx)(sl,{label:`Social platforms`,meta:b.length>0?`${ad(b.length,`platform`)} · ${ad(n.socialReferrals.length,`source`)}`:Hu.noneInPeriod,children:b.length>0?(0,$.jsx)(ml,{groups:b,groupLabel:`Platform`,caption:`Social sessions by platform`,childColumns:Zu,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,$.jsx)(ed,{row:e})}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Hu.noSocial})})]})]})]}),n&&n.topPages.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsxs)(`section`,{"aria-labelledby":`top-landing-pages-heading`,children:[(0,$.jsx)(al,{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,$.jsx)(Os,{value:u.query,onChange:u.setQuery,label:`Filter landing page URLs`,placeholder:`Filter landing pages`,className:`mb-4 max-w-md`}),(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[36rem] text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(ul,{label:`Landing page`,sortKey:`landingPage`,current:a.key,dir:a.dir,onSort:m,align:`left`}),(0,$.jsx)(ul,{label:`Sessions`,sortKey:`sessions`,current:a.key,dir:a.dir,onSort:m,align:`right`}),(0,$.jsx)(ul,{label:`Organic`,sortKey:`organicSessions`,current:a.key,dir:a.dir,onSort:m,align:`right`}),(0,$.jsx)(dl,{label:`Organic share`,align:`right`})]})}),(0,$.jsx)(`tbody`,{children:u.rows.map(e=>(0,$.jsx)(md,{page:e},e.landingPage))})]})}),u.totalRows===0&&u.hasQuery&&(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`No landing pages match this filter`}),(0,$.jsx)(Ss,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?`matches`:`pages`})]})]}),(0,$.jsx)(fd,{projectName:t}),(0,$.jsx)(`p`,{className:`mt-6 text-copy-13 text-secondary`,children:n?.lastSyncedAt?`Last synced ${Uu(n.lastSyncedAt)}`:`Never synced`})]})}function ad(e,t){return`${e.toLocaleString()} ${e===1?t:`${t}s`}`}var od=25,sd=`n/a`,cd={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 ld(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 ud(e){return e===null?sd:e.toFixed(1)}function dd(e){return e===null?sd:St(e)}function fd({projectName:e}){let[t,n]=(0,Q.useState)(`28d`),[r,i]=(0,Q.useState)(`clicks`),[a,o]=(0,Q.useState)(`desc`),s=w({...Rr({client:K,path:{name:e},query:{window:t,limit:V}}),staleTime:er}),c=s.data,l=(0,Q.useMemo)(()=>[...c?.rows??[]].sort((e,t)=>{let n=ld(e,r),i=ld(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]),u=ws({rows:l,getSearchText:e=>bs(W(e.landingPage)),pageSize:od});function d(e){u.setPage(1),r===e?o(e=>e===`desc`?`asc`:`desc`):(i(e),o(e===`landingPage`?`asc`:`desc`))}let f=c?.total??null,p=c?.searchConsoleLink?.state===`not-linked`,m=!Y()&&!Ze();return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsxs)(`section`,{"aria-labelledby":`ga-search-landing-heading`,children:[(0,$.jsxs)(`div`,{className:`mb-4 flex flex-wrap items-start justify-between gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h2`,{id:`ga-search-landing-heading`,className:`text-heading-16 text-primary`,children:cd.heading}),(0,$.jsx)(X,{text:cd.tooltip})]}),c?.windowStart&&c.windowEnd&&(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[It(c.windowStart),` to `,It(c.windowEnd),c.timeZone?` (${c.timeZone})`:``]})]}),(0,$.jsx)(tl,{windows:Vt,value:t,onChange:e=>{u.setPage(1),n(e)},label:cd.windowLabel})]}),s.isPending?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary py-6 text-center`,children:cd.loading}):s.isError||!c?(0,$.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,$.jsx)(`span`,{children:cd.loadError}),(0,$.jsx)(q,{variant:`outline`,size:`sm`,onClick:()=>{s.refetch()},children:cd.retry})]}):(0,$.jsxs)($.Fragment,{children:[(c.status===`error`||c.status===`unavailable`||c.subjectToThresholding||p)&&(0,$.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center gap-2`,"data-testid":`ga-search-landing-status`,children:[p&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,"data-testid":`ga-search-landing-not-linked`,children:[(0,$.jsx)(J,{tone:`caution`,children:cd.notLinkedBadge}),(0,$.jsx)(X,{text:cd.notLinked(c.searchConsoleLink?.searchConsoleImpressions??0)})]}),c.status===`error`&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsx)(J,{tone:`negative`,children:cd.refreshFailedBadge}),c.error&&(0,$.jsx)(X,{text:c.error})]}),c.status===`unavailable`&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsx)(J,{tone:`caution`,children:cd.unavailableBadge}),c.error&&(0,$.jsx)(X,{text:c.error})]}),c.subjectToThresholding&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsx)(J,{tone:`caution`,children:cd.thresholdedBadge}),(0,$.jsx)(X,{text:cd.thresholded})]}),c.status!==`ready`&&f&&c.syncedAt&&(0,$.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[cd.previousSnapshot,` `,Uu(c.syncedAt),`.`]}),c.status===`unavailable`&&f&&(0,$.jsx)(`p`,{className:`w-full text-copy-14 text-secondary`,children:cd.unavailableAction})]}),f?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Os,{value:u.query,onChange:u.setQuery,label:`Filter Google organic search landing pages`,placeholder:`Filter landing pages`,className:`mb-4 max-w-md`}),(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[40rem] text-label-14`,"aria-labelledby":`ga-search-landing-heading`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(ul,{label:`Landing page`,sortKey:`landingPage`,current:r,dir:a,onSort:d,align:`left`}),(0,$.jsx)(ul,{label:`Clicks`,sortKey:`clicks`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(ul,{label:`Impressions`,sortKey:`impressions`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(ul,{label:`CTR`,sortKey:`ctr`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(ul,{label:`Avg. position`,sortKey:`position`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(ul,{label:`Active users`,sortKey:`activeUsers`,current:r,dir:a,onSort:d,align:`right`})]})}),(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{className:`border-t border-subtle text-label-14-strong`,"data-testid":`ga-search-landing-total`,children:[(0,$.jsxs)(`td`,{className:`py-1.5 text-primary`,children:[cd.totalLabel,` `,(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:cd.totalScope})]}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:f.organicGoogleSearchClicks.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:f.organicGoogleSearchImpressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:dd(f.organicGoogleSearchClickThroughRate)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:ud(f.organicGoogleSearchAveragePosition)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:f.activeUsers.toLocaleString()})]}),u.rows.map(e=>(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-1.5 text-neutral max-w-[400px] truncate`,title:W(e.landingPage),children:W(e.landingPage)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-strong tabular-nums`,children:e.organicGoogleSearchClicks.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.organicGoogleSearchImpressions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:dd(e.organicGoogleSearchClickThroughRate)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:ud(e.organicGoogleSearchAveragePosition)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.activeUsers.toLocaleString()})]},e.landingPage))]})]})}),!Se(f)&&!p&&(0,$.jsxs)(`div`,{className:`text-label-14 text-secondary mt-3 space-y-1`,children:[(0,$.jsx)(`p`,{children:cd.noSearchTraffic}),(0,$.jsx)(`p`,{children:c.searchConsoleLink?.state===`no-search-data`?cd.noSearchTrafficConfirmed:cd.noSearchTrafficAction})]}),u.totalRows===0&&u.hasQuery&&(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary mt-3`,children:c.totalRows>c.rows.length?cd.noFilterMatchInLoaded(c.rows.length):cd.noFilterMatch}),(0,$.jsx)(Ss,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?`matches`:`pages`}),(c.totalRows>c.rows.length||c.rowsCapped)&&(0,$.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,$.jsxs)(`p`,{className:`mt-2 text-copy-13 text-muted`,children:[`Synced `,Uu(c.syncedAt)]})]}):(0,$.jsx)(Z,{className:`p-5`,children:c.status===`unavailable`?(0,$.jsxs)(`div`,{className:`text-label-14 text-secondary space-y-1`,children:[(0,$.jsx)(`p`,{className:`text-neutral`,children:cd.unavailable}),(0,$.jsx)(`p`,{children:cd.unavailableAction})]}):c.status===`error`?(0,$.jsxs)(`div`,{className:`text-label-14 text-secondary space-y-1`,children:[(0,$.jsx)(`p`,{className:`text-neutral`,children:cd.refreshFailed}),c.error&&(0,$.jsx)(`p`,{children:c.error})]}):(0,$.jsxs)(`div`,{className:`text-label-14 text-secondary space-y-1`,children:[(0,$.jsx)(`p`,{className:`text-neutral`,children:cd.neverSynced}),m&&(0,$.jsx)(`p`,{children:cd.neverSyncedAction})]})})]})]})]})}function pd({projectName:e,onConnected:t}){let[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(null),f=(0,Q.useRef)(null),p=(0,Q.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 h(){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 yt(e,{propertyId:n.trim(),keyJson:o});try{await Ct(e)}catch{}t()}catch(e){d(e instanceof Error?e.message:`Failed to connect GA4`)}finally{l(!1)}}}return(0,$.jsxs)(Z,{className:`surface-card p-6`,children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-primary mb-1`,children:`Connect Google Analytics 4`}),(0,$.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,$.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,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`label`,{htmlFor:`ga4-property-id`,className:`block text-label-12-strong text-secondary mb-1.5`,children:`GA4 Property ID`}),(0,$.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,$.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,$.jsxs)(`div`,{className:`mb-5`,children:[(0,$.jsx)(`label`,{className:`block text-label-12-strong text-secondary mb-1.5`,children:`Service Account Key File`}),(0,$.jsx)(`input`,{ref:f,type:`file`,accept:`.json,application/json`,onChange:p,className:`hidden`}),(0,$.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,$.jsx)(m,{className:`w-4 h-4 shrink-0`}),i?(0,$.jsx)(`span`,{className:`text-strong truncate`,children:i}):(0,$.jsx)(`span`,{children:`Upload .json key file`})]}),(0,$.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,$.jsx)(`span`,{className:`text-secondary`,children:`Viewer`}),` access on the GA4 property.`]})]}),(0,$.jsx)(q,{variant:`default`,size:`sm`,disabled:c||!n.trim()||!o,onClick:Jn(h),children:c?`Connecting & syncing…`:`Connect GA4`})]})}function md({page:e}){return(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`max-w-[400px] truncate py-1.5 pr-3 text-strong`,title:e.landingPage,children:e.landingPage}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.organicSessions.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:St(e.organicShare)})]})}function hd({row:e}){return(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`max-w-[400px] py-1.5 pr-3 text-strong`,children:(0,$.jsx)(ys,{value:e.landingPage,className:`whitespace-nowrap`})}),(0,$.jsx)(`td`,{className:`max-w-[220px] truncate py-1.5 pr-3 text-secondary`,title:e.source,children:e.source}),(0,$.jsx)(`td`,{className:`py-1.5 pr-3 text-secondary`,title:Yu[e.sourceDimension]??``,children:Ju[e.sourceDimension]??e.sourceDimension}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()})]})}var gd=new Set([`gbp-listing-discrepancy`,`gbp-lodging-gap`,`gbp-cta-gap`,`gbp-metric-drop`,`gbp-keyword-drop`]);function _d({projectName:e,projectId:t}){let n=S(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),l=w(Sr({client:K,path:{name:e}})),u=l.data?.find(e=>e.connectionType===`gbp`),d=!!u,f=r?{locationName:r}:void 0,p=w({...Fr({client:K,path:{name:e}}),enabled:d}),m=w({...kr({client:K,path:{name:e},query:f}),enabled:d}),h=w({...Mr({client:K,path:{name:e},query:f}),enabled:d}),g=w({...Vr({client:K,path:{name:e},query:f}),enabled:d}),_=w({...vr({client:K,path:{name:e},query:f}),enabled:d}),v=w({...wr({client:K,path:{name:e},query:f}),enabled:d}),y=w({queryKey:[`gbp-section-insights`,e],queryFn:()=>tt(e),enabled:d});function b(){Zn(n,`gbp`)}let x=C({...ra(),onSuccess:n=>{$o({id:n.runId,projectId:t,kind:ce[`gbp-sync`],projectLabel:e,sourceAction:`gbp-sync`}),Xn({title:`Business Profile sync started`,detail:`${e} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`gbp-sync:${e}`,dedupeMode:`replace`})}}),T=(0,Q.useSyncExternalStore)(Go,jo,jo),E=Object.values(T.runs).some(e=>e.kind===ce[`gbp-sync`]&&e.projectId===t),D=x.isPending||E,O=C({...Ir(),onSuccess:()=>b()});if((0,Q.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,Q.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,$.jsxs)($.Fragment,{children:[`Then adopt the ones to sync: `,(0,$.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,$.jsxs)($.Fragment,{children:[`Schedule it: `,(0,$.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,$.jsx)(`section`,{className:`page-section-divider`,children:(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Local presence`}),(0,$.jsx)(`h2`,{children:`Connect Google Business Profile`}),(0,$.jsx)(`p`,{className:`mt-2 max-w-2xl text-copy-14 text-muted`,children:`Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:`}),(0,$.jsx)(`ol`,{className:`mt-5 space-y-4`,children:t.map((e,t)=>(0,$.jsxs)(`li`,{className:`grid grid-cols-[1.5rem_1fr] gap-x-3`,children:[(0,$.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,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:e.title}),(0,$.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,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:e.note})]})]},e.title))})]})})}let k=m.data,A=p.data?.locations??[],j=A.filter(e=>e.selected),M=h.data?.keywords??[],N=g.data?.lodging??[],P=_.data?.placeActions??[],F=v.data?.places??[],I=A.length>0?A[0].accountName:u.domain,L=r?A.find(e=>e.locationName===r)?.displayName??null:null,R=r?A.filter(e=>e.locationName===r):j,z=new Set(R.map(e=>e.locationName)),ee=N.filter(e=>z.has(e.locationName)),te=P.filter(e=>z.has(e.locationName)),ne=F.filter(e=>z.has(e.locationName)),re=new Set(j.map(e=>e.locationName)),B=r?M:M.filter(e=>re.has(e.locationName)),ie=!r&&j.length>1,ae=(y.data??[]).filter(e=>!e.dismissed&&gd.has(e.type)&&(!L||e.query===L||e.query===r||e.title.startsWith(L)));return(0,$.jsx)(`section`,{className:`page-section-divider`,children:(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Local presence`}),(0,$.jsxs)(`h2`,{className:`flex items-center gap-2`,children:[`Google Business Profile`,(0,$.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,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(J,{tone:`positive`,children:`Connected`}),!Y()&&(0,$.jsx)(hs,{type:`button`,variant:`outline`,size:`sm`,disabled:D,onClick:()=>x.mutate({client:K,path:{name:e},body:{}}),children:D?`Syncing…`:`Sync`})]})]}),(0,$.jsxs)(`p`,{className:`mb-4 text-copy-13 text-muted`,children:[I?(0,$.jsxs)($.Fragment,{children:[`Account `,(0,$.jsx)(`span`,{className:`font-mono text-secondary`,children:I}),` · `]}):null,p.data?`${p.data.totalSelected} of ${p.data.totalDiscovered} locations tracked`:`Loading locations…`]}),j.length>1&&(0,$.jsxs)(`div`,{className:`mb-5 max-w-xs`,children:[(0,$.jsx)(`label`,{htmlFor:`local-presence-location`,className:`mb-1 block text-label-14-strong text-secondary`,children:`Location`}),(0,$.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,$.jsx)(`option`,{value:``,children:`All locations`}),j.map(e=>(0,$.jsx)(`option`,{value:e.locationName,children:e.displayName},e.id))]})]}),j.length===0?(0,$.jsxs)(`p`,{className:`text-copy-14 text-muted`,children:[`No locations are tracked yet. Open `,(0,$.jsx)(`span`,{className:`text-copy-14-strong text-neutral`,children:`Manage locations`}),` below to track the one(s) for this business.`]}):(0,$.jsxs)($.Fragment,{children:[ae.length>0&&(0,$.jsxs)(`div`,{className:`mb-6 grid gap-2`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Needs attention`}),ae.map(e=>(0,$.jsx)(`div`,{className:[`surface-card insight-card`,Pd(e.severity),`p-3`].filter(Boolean).join(` `),children:(0,$.jsxs)(`p`,{className:`flex items-center gap-2 text-copy-14-strong text-strong`,children:[e.title,e.recommendation?.reason&&(0,$.jsx)(X,{text:e.recommendation.reason})]})},e.id))]}),k&&(0,$.jsx)(Hd,{performance:k.performance,freshness:k.freshness,timeseries:k.timeseries}),k?.profileCompleteness&&(0,$.jsx)(vd,{summary:k.profileCompleteness}),R.length>0&&(0,$.jsx)(yd,{locations:R,lodging:ee,places:ne,placeActions:te,expandedLocation:a,onToggleExpanded:e=>{o(t=>t===e?null:e)}}),(0,$.jsxs)(`div`,{className:`mb-2`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline mb-2`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Search terms`}),h.data&&h.data.total>0&&(0,$.jsxs)(`span`,{className:`text-label-12 text-faint`,children:[St(h.data.thresholdedPct,ye.percent),` privacy-thresholded`]})]}),B.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No keyword impressions stored yet.`}):(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Search term`}),ie&&(0,$.jsx)(`th`,{className:`text-left`,children:`Location`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Window`})]})}),(0,$.jsx)(`tbody`,{children:B.slice(0,25).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-neutral`,children:e.keyword}),ie&&(0,$.jsx)(`td`,{className:`text-muted`,children:A.find(t=>t.locationName===e.locationName)?.displayName??e.locationName}),(0,$.jsx)(`td`,{className:`text-right font-mono text-strong`,children:e.valueCount===null?(0,$.jsxs)(`span`,{className:`text-muted`,title:`Privacy floor — Google withheld the exact count`,children:[`<`,e.valueThreshold]}):e.valueCount.toLocaleString()}),(0,$.jsxs)(`td`,{className:`text-right text-label-12-mono text-faint`,children:[e.periodStart,`–`,e.periodEnd]})]},`${e.locationName}:${e.keyword}`))})]})]})]}),(0,$.jsxs)(`div`,{className:`mt-6 border-t border-default pt-4`,children:[(0,$.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,$.jsx)(`span`,{"aria-hidden":`true`,children:s?`▾`:`▸`}),` Manage locations (`,A.length,`)`]}),s&&(0,$.jsx)(`div`,{className:`mt-3`,children:A.length===0?(0,$.jsxs)(`p`,{className:`text-copy-14 text-muted`,children:[`No locations discovered. Run `,(0,$.jsx)(`span`,{className:`font-mono`,children:`canonry gbp locations discover`}),`.`]}):(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Location`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Address`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Status`}),!Y()&&(0,$.jsx)(`th`,{className:`text-right`,children:`Action`})]})}),(0,$.jsx)(`tbody`,{children:A.map(t=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-strong`,children:t.displayName}),(0,$.jsx)(`td`,{className:`text-muted`,children:t.storefrontAddress??`—`}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:t.selected?`positive`:`neutral`,children:t.selected?`Tracked`:`Not tracked`})}),!Y()&&(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(hs,{type:`button`,variant:`outline`,size:`sm`,disabled:O.isPending,onClick:()=>O.mutate({client:K,path:{name:e,locationName:t.locationName},body:{selected:!t.selected}}),children:t.selected?`Untrack`:`Track`})})]},t.id))})]})})]})]})})}function vd({summary:e}){if(e.locationCount===0)return null;let t=e.locationCount,n=[{label:`Description`,value:`${e.withDescription}/${t}`,tone:Md(e.withDescription,t,`caution`)},{label:`Hours`,value:`${e.withHours}/${t}`,tone:Md(e.withHours,t,`caution`)},{label:`Phone`,value:`${e.withPrimaryPhone}/${t}`,tone:Md(e.withPrimaryPhone,t,`caution`)},{label:`Service area`,value:`${e.withServiceArea}/${t}`,tone:Md(e.withServiceArea,t,`neutral`)},{label:`Secondary categories`,value:`${e.withSecondaryCategories}/${t}`,detail:`${e.secondaryCategoryTotal} total`,tone:Md(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,$.jsxs)(`div`,{className:`mb-6 border-y border-default py-3`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Owner profile · Business Information`}),(0,$.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,$.jsx)(`div`,{className:`grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3`,children:n.map(e=>(0,$.jsxs)(`div`,{className:`grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3`,children:[(0,$.jsx)(`span`,{className:`text-label-12 text-muted`,children:e.label}),(0,$.jsx)(`span`,{className:`text-label-14-mono tabular-nums ${Nd(e.tone)}`,children:e.value}),e.detail&&(0,$.jsx)(`span`,{className:`col-span-2 text-label-12 text-faint`,children:e.detail})]},e.label))})]})}function yd({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,$.jsxs)(`div`,{className:`mb-6`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline mb-2`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Source evidence`}),(0,$.jsx)(X,{text:Y()?`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,$.jsxs)(`span`,{className:`text-label-12 text-faint`,children:[e.length,` location`,e.length===1?``:`s`]})]}),(0,$.jsx)(`div`,{className:`data-table-wrapper`,children:(0,$.jsxs)(`table`,{className:`data-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`min-w-[14rem]`,children:`Location`}),(0,$.jsx)(`th`,{className:`min-w-[15rem]`,children:`Owner profile`}),(0,$.jsx)(`th`,{className:`min-w-[11rem]`,children:`Hotel data`}),(0,$.jsx)(`th`,{className:`min-w-[11rem]`,children:`Public Maps`}),(0,$.jsx)(`th`,{className:`min-w-[10rem]`,children:`CTAs`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Detail`})]})}),(0,$.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,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:e.displayName}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-faint`,children:e.primaryCategoryDisplayName??`Primary category not returned`}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[(0,$.jsx)(J,{tone:e.selected?`positive`:`neutral`,children:e.selected?`Tracked`:`Not tracked`}),e.openStatus&&e.openStatus!==`OPEN`&&(0,$.jsx)(J,{tone:e.openStatus===`CLOSED_PERMANENTLY`?`negative`:`caution`,children:Id(e.openStatus)})]})]})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(xd,{location:e})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Sd,{lodging:t})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(wd,{place:n,mapsUri:e.mapsUri})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ed,{actions:r})}),(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>a(e.locationName),children:l?`Hide`:`Details`})})]}),l&&(0,$.jsx)(`tr`,{className:`bg-mono-950/35 hover:bg-mono-950/35`,children:(0,$.jsx)(`td`,{colSpan:6,className:`px-4 py-4`,children:(0,$.jsx)(kd,{location:e,lodging:t,place:n,placeActions:r})})})]},e.id)})})]})})]})}function bd(e){return[{label:`Description`,tone:Fd(e.description)?`positive`:`neutral`,value:Fd(e.description)?`set`:`not returned`},{label:`Hours`,tone:e.regularHours?`positive`:`neutral`,value:e.regularHours?`set`:`not returned`},{label:`Phone`,tone:Fd(e.primaryPhone)?`positive`:`neutral`,value:Fd(e.primaryPhone)?`set`:`not returned`},{label:`Website`,tone:Fd(e.websiteUri)?`positive`:`neutral`,value:Fd(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 xd({location:e}){let t=bd(e);return(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>(0,$.jsxs)(J,{tone:e.tone,children:[e.label,` `,e.value]},e.label))})}function Sd({lodging:e}){return(0,$.jsx)(Od,{...Cd(e)})}function Cd(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 wd({place:e,mapsUri:t}){return(0,$.jsx)(Od,{...Td(e,t)})}function Td(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 Ed({actions:e}){return(0,$.jsx)(Od,{...Dd(e)})}function Dd(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 Od({tone:e,label:t,detail:n}){return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(J,{tone:e,children:t}),(0,$.jsx)(`p`,{className:`mt-1.5 text-copy-13 text-faint`,children:n})]})}function kd({location:e,lodging:t,place:n,placeActions:r}){let i=t?Bd(t.attributes):[];return(0,$.jsxs)(`div`,{className:`grid gap-5 text-label-12 lg:grid-cols-3`,children:[(0,$.jsxs)(Ad,{title:`Owner profile · Business Information`,children:[(0,$.jsx)(jd,{label:`Primary category`,value:e.primaryCategoryDisplayName??`Not returned`}),(0,$.jsx)(jd,{label:`Secondary categories`,value:e.additionalCategories.length>0?e.additionalCategories.join(`, `):`Not returned`}),(0,$.jsx)(jd,{label:`Description`,value:Fd(e.description)?e.description:`Not returned`}),(0,$.jsx)(jd,{label:`Hours`,value:e.regularHours?`Returned by Google`:`Not returned`}),(0,$.jsx)(jd,{label:`Service area`,value:e.serviceArea?`Returned by Google`:`Not returned`}),(0,$.jsx)(jd,{label:`Phone`,value:e.primaryPhone??`Not returned`}),(0,$.jsx)(jd,{label:`Website`,value:e.websiteUri??`Not returned`}),(0,$.jsx)(jd,{label:`Open status`,value:Id(e.openStatus)}),(0,$.jsx)(jd,{label:`Opening date`,value:e.openingDate??`Not returned`})]}),(0,$.jsx)(Ad,{title:`Hotel data · Lodging API`,children:t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(jd,{label:`Last checked`,value:zd(t.syncedAt)}),(0,$.jsx)(jd,{label:`Groups returned`,value:String(t.populatedGroupCount)}),(0,$.jsx)(jd,{label:`Populated groups`,value:i.length>0?i.join(`, `):`None returned`})]}):(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No Lodging API snapshot was stored for this location.`})}),(0,$.jsxs)(Ad,{title:`Public listing + CTAs`,children:[n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(jd,{label:`Places tier`,value:n.tier}),(0,$.jsx)(jd,{label:`Last checked`,value:zd(n.syncedAt)}),(0,$.jsx)(jd,{label:`Public signals`,value:n.amenities.length>0?n.amenities.join(`, `):`No supported signals detected`})]}):(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No Places Details snapshot was stored for this location.`}),e.mapsUri&&(0,$.jsx)(`a`,{href:e.mapsUri,target:`_blank`,rel:`noopener noreferrer`,className:`inline-block text-muted hover:text-neutral`,children:`View on Google Maps →`}),(0,$.jsx)(`div`,{className:`mt-3 border-t border-default pt-3`,children:r.length===0?(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:`No placeActionLinks returned.`}):(0,$.jsx)(`div`,{className:`grid gap-2`,children:r.map(e=>(0,$.jsxs)(`div`,{className:`grid gap-0.5`,children:[(0,$.jsxs)(`span`,{className:`text-label-12-strong text-neutral`,children:[Ld(e.placeActionType),e.isPreferred?` · preferred`:``]}),(0,$.jsxs)(`span`,{className:`text-faint`,children:[Ld(e.providerType),e.uri?` · ${Rd(e.uri)}`:``]})]},e.placeActionLinkName))})})]})]})}function Ad({title:e,children:t}){return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-label-12-strong normal-case text-muted`,children:e}),(0,$.jsx)(`div`,{className:`grid gap-2`,children:t})]})}function jd({label:e,value:t}){return(0,$.jsxs)(`div`,{className:`grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3`,children:[(0,$.jsx)(`span`,{className:`text-faint`,children:e}),(0,$.jsx)(`span`,{className:`min-w-0 break-words text-secondary`,children:t})]})}function Md(e,t,n){return e===t?`positive`:e===0?n:`caution`}function Nd(e){switch(e){case`positive`:return`text-positive`;case`caution`:return`text-caution`;case`negative`:return`text-negative`;case`neutral`:return`text-neutral`}}function Pd(e){return e===`critical`||e===`high`?`insight-card-negative`:e===`medium`?`insight-card-caution`:``}function Fd(e){return typeof e==`string`&&e.trim().length>0}function Id(e){return e?Ld(e):`Not returned`}function Ld(e){return e?e.toLowerCase().split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `):`Unknown`}function Rd(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function zd(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}function Bd(e){return Object.entries(e).filter(([e,t])=>e!==`name`&&e!==`metadata`&&Vd(t)).map(([e])=>Ld(e.replace(/([a-z])([A-Z])/g,`$1_$2`)))}function Vd(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e!=`object`||Object.keys(e).length>0}function Hd({performance:e,freshness:t,timeseries:n}){let r=e.totals,i=xe.filter(e=>(r[e]??0)>0),a=je.filter(e=>(r[e]??0)>0),o=Object.keys(r).filter(e=>(r[e]??0)>0&&qe(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 ${_a(t.dataThroughDate)}${t.pendingDays>0?` · ${t.pendingDays}d pending`:``}`:null,p=[...i,...o];return(0,$.jsxs)(`div`,{className:`mb-6 grid gap-6`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Profile actions · daily`}),f&&(0,$.jsx)(`span`,{className:`text-label-12 text-muted`,children:f})]}),!d||i.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`No profile action activity yet — run a sync.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ud,{data:c,metrics:i,kind:`line`,firstPending:l,lastDate:u}),(0,$.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-x-5 gap-y-1`,children:p.map(e=>(0,$.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[On(e),` `,(0,$.jsx)(`span`,{className:`font-mono text-heading`,children:(r[e]??0).toLocaleString()})]},e))})]})]}),d&&a.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft mb-2`,children:`Reach · impressions, daily`}),(0,$.jsx)(Ud,{data:c,metrics:a,kind:`area`,firstPending:l,lastDate:u})]}),s.length>0&&(0,$.jsxs)(`p`,{className:`text-copy-13 text-faint`,children:[`Not active: `,s.map(e=>On(e)).join(`, `)]})]})}function Ud({data:e,metrics:t,kind:n,firstPending:r,lastDate:i}){return(0,$.jsx)(`div`,{className:`h-48 w-full`,children:(0,$.jsx)(I,{width:`100%`,height:`100%`,children:(0,$.jsxs)(te,{data:e,margin:{top:8,right:8,bottom:0,left:0},children:[(0,$.jsx)(M,{stroke:xa,vertical:!1}),(0,$.jsx)(P,{dataKey:`date`,tick:va,tickLine:!1,axisLine:{stroke:Ca},tickFormatter:fa,minTickGap:24}),(0,$.jsx)(z,{tick:va,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,$.jsx)(N,{...Sa,labelFormatter:_a,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),On(String(t??``))]}),(0,$.jsx)(R,{wrapperStyle:{fontSize:12,color:ga.text},formatter:e=>On(e)}),r&&i&&(0,$.jsx)(F,{x1:r,x2:i,fill:ga.surface,fillOpacity:.55,stroke:`none`,label:{value:`pending`,position:`insideTopRight`,fill:ga.textDim,fontSize:12}}),t.map((e,t)=>n===`line`?(0,$.jsx)(ee,{type:`monotone`,dataKey:e,stroke:ua[t%ua.length],strokeWidth:2,dot:!1,isAnimationActive:!1},e):(0,$.jsx)(L,{type:`monotone`,dataKey:e,stackId:`reach`,stroke:ua[t%ua.length],fill:ua[t%ua.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},e))]})})})}var Wd=25;function Gd(e){return typeof window>`u`?e:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,``)??``}${e}`}function Kd(e){return e.toLocaleString()}function qd(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 Jd(e){let t=e.filter(e=>e.kind===ce[`backlink-extract`]&&!is(e.status));return t.length===0?null:t.reduce((e,t)=>e.createdAt>t.createdAt?e:t)}function Yd(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 Xd({projectName:e}){let t=Ze(),[n,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,_]=(0,Q.useState)(null),[v,b]=(0,Q.useState)(Date.now()),[x,S]=(0,Q.useState)(0),[C,w]=(0,Q.useState)(!0),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(null),k=(0,Q.useCallback)(async()=>{w(!0),O(null);try{let[t,n,r,i,a]=await Promise.all([Qe().catch(()=>null),fe(e,{excludeCrawlers:!0}).catch(()=>null),He(e,{limit:Wd,offset:x,excludeCrawlers:!0}).catch(e=>{if(e instanceof ht&&e.code===`NOT_FOUND`)return null;throw e}),Rt(e,{surface:wt.backlinks}).catch(()=>null),ge(e).catch(()=>[])]);f(t),o(n),c(r),u(i);let s=Jd(a);m(s)}catch(e){O(e instanceof Error?e.message:`Failed to load backlinks`)}finally{w(!1)}},[e,x]);(0,Q.useEffect)(()=>{k()},[k]),(0,Q.useEffect)(()=>{if(!p)return;let e=p.id,t=!1,n=async()=>{try{let n=await we(e);if(t)return;is(n.status)?(m(null),_(n),await k()):m(e=>e?.id===n.id?{...e,...n}:e)}catch{}},r=window.setInterval(()=>{n()},3e3);return()=>{t=!0,window.clearInterval(r)}},[p,k]),(0,Q.useEffect)(()=>{if(!p)return;let e=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(e)},[p]),(0,Q.useEffect)(()=>{if(!h||h.status===`failed`)return;let e=window.setTimeout(()=>_(null),1e4);return()=>window.clearTimeout(e)},[h]);async function A(){E(!0),O(null);try{let t=await _t(e);m(t)}catch(e){e instanceof ht&&e.code===`MISSING_DEPENDENCY`?O(`DuckDB is not installed. Visit the Backlinks admin page to install it.`):O(e instanceof Error?e.message:`Failed to trigger extract`)}finally{E(!1)}}let j=s?.rows??[],M=s?.total??0,N=n?.excludedLinkingDomains??0,P=Math.floor(x/Wd)+1;return(0,Q.useEffect)(()=>{x>0&&x>=M&&S(0)},[x,M]),(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Backlinks`}),(0,$.jsx)(`h2`,{children:`Referring domains`})]})}),D&&(0,$.jsx)(Z,{className:`surface-card p-4 mb-4 bg-negative-soft`,children:(0,$.jsx)(`p`,{className:`text-copy-14 text-negative`,children:D})}),p&&(0,$.jsx)(Z,{className:`surface-card p-4 mb-4 bg-info-soft`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,$.jsx)(r,{className:`h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5`,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex-1 min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`Extract running`}),(0,$.jsx)(J,{tone:`neutral`,children:p.status}),(0,$.jsxs)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:[Yd(p.startedAt??null,p.createdAt),` elapsed · refreshing every 3s`]}),(0,$.jsxs)(`span`,{className:`sr-only`,children:[`now=`,v]})]}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`Refreshing this project from the current Common Crawl release.`})]})]})}),h&&!p&&(0,$.jsx)(Z,{className:`surface-card p-4 mb-4 ${h.status===`failed`?`bg-negative-soft`:`bg-positive-soft`}`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[h.status===`failed`?(0,$.jsx)(`span`,{className:`h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-label-18`,"aria-hidden":!0,children:`!`}):(0,$.jsx)(g,{className:`h-5 w-5 text-positive-400 shrink-0 mt-0.5`,"aria-hidden":!0}),(0,$.jsxs)(`div`,{className:`flex-1`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong ${h.status===`failed`?`text-negative`:`text-positive`}`,children:h.status===`failed`?`Extract failed`:`Extract complete`}),h.error?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:kn(h.error)}):h.status===`failed`?null:(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`Backlinks refreshed from the cached release.`})]})]})}),F()]});function F(){return C?(0,$.jsx)(Z,{className:`surface-card p-6`,children:(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading backlinks…`})}):I()}function I(){let e=n!==null&&n.totalLinkingDomains>0,r=h?.status===`failed`,o=n!==null&&n.totalLinkingDomains===0&&!r,s=d?.status===`ready`,c=d?.status===`failed`,l=d&&(d.status===`downloading`||d.status===`querying`||d.status===`queued`);return e?L((0,$.jsxs)($.Fragment,{children:[!Y()&&!t&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:T||p!==null,onClick:Jn(A),children:[(0,$.jsx)(i,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:T?`Queuing…`:`Re-run extract`]}),(0,$.jsx)(ks,{label:`About re-running`,children:`Re-queries the current release for this project without downloading it again.`})]}),!Y()&&!t&&(0,$.jsx)(q,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,$.jsx)(`a`,{href:Gd(`/backlinks`),children:`Open admin`})})]})):(0,$.jsx)(Z,{className:`surface-card p-6`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-4`,children:[(0,$.jsx)(`div`,{className:`flex h-10 w-10 shrink-0 items-center justify-center rounded-md bg-bg-elevated text-secondary`,children:(0,$.jsx)(a,{className:`h-5 w-5`,"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`flex-1`,children:[!d&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No release sync yet`}),(0,$.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.`}),!Y()&&!t&&(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:Gd(`/backlinks`),children:`Set up backlinks`})})})]}),l&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Sync in progress`}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-muted mt-1`,children:[`A workspace release sync is running (`,d.status,d.phaseDetail?` — ${d.phaseDetail}`:``,`). Backlinks will appear here once it finishes.`]}),!Y()&&!t&&(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(q,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,$.jsx)(`a`,{href:Gd(`/backlinks`),children:`View sync status`})})})]}),c&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Last sync failed`}),(0,$.jsx)(`p`,{className:`text-copy-14 text-muted mt-1`,children:d.error??`The workspace release sync failed. Retry from the Backlinks admin page.`}),!Y()&&!t&&(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:Gd(`/backlinks`),children:`Go to Backlinks admin`})})})]}),s&&!l&&!o&&!r&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No backlinks yet for this project`}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:[`Release `,(0,$.jsx)(`code`,{className:`text-neutral`,children:d.release}),` is ready. Run an extract for this project.`]}),!Y()&&!t&&(0,$.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,$.jsxs)(q,{type:`button`,size:`sm`,disabled:T||p!==null,onClick:Jn(A),children:[(0,$.jsx)(y,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:T?`Queuing…`:`Run extract`]}),(0,$.jsx)(ks,{label:`About extraction`,children:`Queries the current release for this project without downloading it again.`})]})]}),r&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Last extract failed`}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary mt-1`,children:`See the error above, then check the workspace source before retrying.`}),!Y()&&!t&&(0,$.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:(0,$.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:Gd(`/backlinks`),children:`Go to Backlinks admin`})})})]}),o&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`No referring domains found`}),(0,$.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.`]}),!Y()&&!t&&(0,$.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,$.jsx)(q,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:Gd(`/backlinks`),children:`Go to Backlinks admin`})}),(0,$.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:T||p!==null,onClick:Jn(A),children:[(0,$.jsx)(y,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),p?`Extract running…`:T?`Queuing…`:`Re-run extract`]}),(0,$.jsxs)(ks,{label:`What does Re-run extract do?`,children:[(0,$.jsxs)(`span`,{className:`block`,children:[`Re-queries the cached release for `,(0,$.jsx)(`span`,{className:`text-strong`,children:n.targetDomain}),`. Only useful if the cache files were incomplete last time.`]}),(0,$.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,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Zd,{summary:n,trend:l}),(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted mt-2`,children:[(0,$.jsx)(`span`,{className:`text-secondary`,children:`Common Crawl`}),` · `,t,` `,(0,$.jsx)(`code`,{className:`text-secondary`,children:n.release}),` · queried `,qd(n.queriedAt),N>0&&(0,$.jsxs)($.Fragment,{children:[` · `,N,` excluded domain`,N===1?``:`s`]})]}),(0,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft mb-2`,children:`Top referring domains`}),(0,$.jsx)(Z,{className:`surface-card overflow-hidden`,children:(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base text-left text-label-12 normal-case text-faint`,children:[(0,$.jsx)(`th`,{className:`px-4 py-2 text-label-12-strong`,children:`Domain`}),(0,$.jsx)(`th`,{className:`px-4 py-2 text-right text-label-12-strong`,children:`Linking hosts`})]})}),(0,$.jsxs)(`tbody`,{children:[j.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-mono-900 last:border-0`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2 text-strong`,children:e.linkingDomain}),(0,$.jsx)(`td`,{className:`px-4 py-2 text-right text-secondary tabular-nums`,children:Kd(e.numHosts)})]},e.linkingDomain)),j.length===0&&(0,$.jsx)(`tr`,{children:(0,$.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,$.jsx)(Ss,{page:P,pageSize:Wd,visibleRows:j.length,totalRows:M,onPageChange:e=>S((e-1)*Wd)})]}),(0,$.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:e})]})}}function Zd({summary:e,trend:t}){let[n,r]=(0,Q.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?_s(o.change,o.unit):void 0,series:o?Es(o):void 0,formatValue:i,allowDecimals:o?.unit===`fraction`}},s=[o(`referring-domains`,`Referring domains`,`Unique domains linking to ${e.targetDomain}.`,e.totalLinkingDomains,Kd),o(`hosts`,`Total linking hosts`,`Aggregate linking hosts across referring domains.`,e.totalHosts,Kd),o(`top-10-concentration`,`Top-10 concentration`,`Share of linking hosts from the 10 largest linking domains.`,Number(e.top10HostsShare),e=>St(e))],c=s.some(xs),l=a.get(`referring-domains`)?.series??[],u=l[0],d=l.at(-1);return(0,$.jsx)(Ts,{name:`Backlinks figures`,groups:[{key:`backlinks`,label:`Every release`,basis:i?Cs(i.figures):void 0,figures:s}],selected:c?[n]:[],onSelect:r,cadence:`release`,span:c&&u&&d?vs(u,d):void 0,emptyChartMessage:t?`One release so far. The trend starts with the next one.`:`Release history could not be loaded.`})}var Qd={[U[`keyword-metrics`]]:`Search demand`,[U[`domain-intelligence`]]:`Domain comparison`,[U[`ranked-keywords`]]:`Searches you rank for`,[U[`market-rankings`]]:`Market rankings`,[U[`competitor-discovery`]]:`Organic competitors`,[U[`keyword-gaps`]]:`Search gaps`},$d={[un.shared]:`Shared`,[un.missing]:`Missing`,[un.outranked]:`Competitor ahead`},ef=`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.`,tf={[Ot.queued]:`Queued`,[Ot.running]:`Refreshing`,[Ot.completed]:`Completed`,[Ot.partial]:`Partial results`,[Ot.failed]:`Failed`,[Ot.cancelled]:`Cancelled`,[Ot[`reconciliation-required`]]:`Needs review`},nf=25,rf=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:1}),af=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}),of=Intl.DateTimeFormat().resolvedOptions().timeZone,sf=`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`,cf=`px-4 py-3 text-right align-top tabular-nums whitespace-nowrap`,lf=`min-w-56 px-4 py-3 text-left align-top text-label-14`,uf=`Position on the page, counting maps and other blocks`;function df(e){return e?.status===Ot.queued||e?.status===Ot.running}function ff({value:e,currency:t=!1}){return e===null?(0,$.jsx)(`span`,{className:`text-muted`,"aria-label":`Not supplied`,children:`—`}):(0,$.jsx)($.Fragment,{children:t?af.format(e):rf.format(e)})}function pf({status:e}){let t=e===Ot.completed?`positive`:e===Ot.failed?`negative`:e===Ot.partial||e===Ot[`reconciliation-required`]?`caution`:`neutral`;return(0,$.jsx)(J,{tone:t,children:tf[e]})}function mf(e){let t=Lt(e).split(`/`).at(-1)??e,n=fn.safeParse(t.replaceAll(`_`,`-`));return n.success?Qd[n.data]:t.replaceAll(/[-_]/g,` `)}function hf(e){return e===`mobile`?`phone results`:e===`desktop`?`computer results`:`device not specified by source`}function gf(e){return e.capabilities.includes(U[`market-rankings`])?`Market locations`:`Location ${e.locationCode}`}function _f(e){return e.capabilities.includes(U[`market-rankings`])?`searches`:`tasks`}function vf(e){return e.capability!==U[`market-rankings`]||![Ot.queued,Ot.running,Ot.completed].includes(e.status)}function yf(e,t){let n=e.capabilities.includes(U[`market-rankings`]);return`${t} ${t===1?n?`search`:`task`:_f(e)}`}function bf(e,t){return Number.isFinite(Date.parse(e))?dn(nn(e,t)):null}var xf={[Ot.failed]:`Latest refresh failed`,[Ot.cancelled]:`Latest refresh cancelled`,[Ot[`reconciliation-required`]]:`Latest refresh needs review`};function Sf(e,t){let n=e&&e.id!==t?.id?xf[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=`${yf(t,t.failedTasks)} failed`,n=t.capabilities.includes(U[`market-rankings`])?`Their queries show as Failed.`:`Open Activity for details.`;return{label:e,text:`${e}: ${t.failedTasks} of ${yf(t,t.taskCount)} in this refresh returned no results. ${n}`}}return t.status===Ot.partial?{label:`Partial results`,text:`Partial results: ${t.error??`some ${_f(t)} returned only part of their results or did not run. Open Activity for details.`}`}:null}function Cf({source:e}){return(0,$.jsxs)(`dl`,{className:`grid gap-x-8 gap-y-2 text-label-13 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Dataset`}),(0,$.jsx)(`dd`,{children:mf(e.dataset)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Search engine`}),(0,$.jsxs)(`dd`,{children:[`Google · `,hf(e.device)]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Provider geography`}),(0,$.jsxs)(`dd`,{children:[`Location `,e.locationCode,` · `,e.languageCode]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Collected`}),(0,$.jsx)(`dd`,{children:Tt(e.collectedAt,of)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Source updated`}),(0,$.jsx)(`dd`,{children:e.sourceUpdatedAt?It(e.sourceUpdatedAt):`Not supplied`})]})]})}function wf({label:e,source:t,children:n}){return(0,$.jsxs)(`details`,{className:`text-left`,children:[(0,$.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-13 text-secondary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[`Details`,(0,$.jsxs)(`span`,{className:`sr-only`,children:[` for `,e]})]}),(0,$.jsxs)(`div`,{className:`min-w-56 space-y-4 pb-3 text-label-13 text-secondary`,children:[n,t&&(0,$.jsx)(Cf,{source:t})]})]})}function Tf({error:e,retry:t}){return(0,$.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,$.jsx)(`p`,{children:Bs(e)}),(0,$.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:t,children:`Retry`})]})}function Ef({title:e,children:t}){return(0,$.jsxs)(`div`,{className:`py-12 text-center`,children:[(0,$.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:e}),(0,$.jsx)(`p`,{className:`mx-auto mt-2 max-w-lg text-copy-14 text-secondary`,children:t})]})}function Df({projectName:e}){let t=E({strict:!1}),r=T(),i=w(Pr({client:K,path:{name:e}})),a=w(ca({client:K,path:{name:e}})),o=w({...ni({client:K,path:{name:e,id:t.seoRunId??``}}),enabled:!!t.seoRunId}),[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=t.seoProfileId??o.data?.profileId,f=d?a.data?.profiles.find(e=>e.id===d):t.seoRunId?void 0:a.data?.profiles[0],p=t=>{c(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})})},m=i.data?.access.canWrite===!0&&!Y()&&!Ze(),h=()=>{c(null),l.current?.focus()};if((0,Q.useEffect)(()=>{!t.seoProfileId&&f&&r({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoProfileId:f.id}),replace:!0})},[r,e,t.seoProfileId,f]),i.error)return(0,$.jsx)(Tf,{error:i.error,retry:()=>{i.refetch()}});if(a.error)return(0,$.jsx)(Tf,{error:a.error,retry:()=>{a.refetch()}});if(!i.data||!a.data)return(0,$.jsx)(`p`,{role:`status`,className:`py-10 text-copy-14 text-secondary`,children:`Loading SEO data…`});let g=i.data.available&&i.data.connections.some(e=>e.capabilities.length>0),_=g&&i.data.connections.some(e=>e.capabilities.some(e=>i.data.scopes.some(t=>t.capabilities?.includes(e)??!0))),v=f&&i.data.scopes.find(e=>e.kind===f.scope.kind&&e.key===(f.scope.key??null));return(0,$.jsxs)(`section`,{"aria-label":`SEO`,className:`min-w-0 space-y-5`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:`SEO`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Search demand and organic rankings.`})]}),m&&_&&(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[f&&(0,$.jsx)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:e=>{l.current=e.currentTarget,c({profile:f,id:f.id})},children:`Edit profile`}),(0,$.jsxs)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:e=>{l.current=e.currentTarget,c({id:crypto.randomUUID()})},children:[(0,$.jsx)(n,{"aria-hidden":`true`,className:`size-4`}),`New profile`]})]})]}),a.data.profiles.length>0&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-5 gap-y-3 border-y border-subtle py-3`,children:[(0,$.jsxs)(`label`,{className:`flex min-w-0 flex-1 items-center gap-3 sm:flex-none`,children:[(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`Profile`}),(0,$.jsxs)(`select`,{ref:u,"aria-label":`SEO profile`,value:f?.id??``,onChange:e=>p(e.target.value),className:`${sf} min-w-0 sm:w-64`,children:[!f&&(0,$.jsx)(`option`,{value:``,disabled:!0,children:`Profile unavailable`}),a.data.profiles.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),f&&(0,$.jsxs)(`div`,{className:`min-w-0 text-label-13 text-secondary`,children:[(0,$.jsx)(`p`,{className:`break-words text-copy-13-strong text-primary`,children:v?.label??`${f.scope.kind}${f.scope.key?`: ${f.scope.key}`:``}`}),(0,$.jsxs)(`p`,{children:[f.rankings?`${f.rankings.locations.length} search location${f.rankings.locations.length===1?``:`s`}`:`Location ${f.locationCode}`,` · `,f.languageCode]})]})]}),s&&(0,$.jsx)(up,{projectName:e,context:i.data,profile:s.profile,id:s.id,onClose:h,onSaved:e=>{p(e),requestAnimationFrame(()=>u.current?.focus())}},s.id),!Ze()&&!i.data.available&&a.data.profiles.length>0&&(0,$.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.`}),t.seoRunId&&o.error?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(Tf,{error:o.error,retry:()=>{o.refetch()}}),f?(0,$.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:()=>p(f.id),children:`View latest data`}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Select a profile to view its latest data.`})]}):t.seoRunId&&o.isPending?(0,$.jsx)(`p`,{role:`status`,className:`py-10 text-copy-14 text-secondary`,children:`Loading refresh…`}):f&&o.data&&o.data.profileId!==f.id?(0,$.jsxs)(Ef,{title:`Refresh belongs to another profile`,children:[`Choose the refresh’s profile, or return to the selected profile’s latest data.`,(0,$.jsx)(q,{variant:`secondary`,className:`mt-4 pointer-coarse:min-h-11`,onClick:()=>p(f.id),children:`View latest data`})]}):f?(0,$.jsx)(Of,{projectName:e,profile:f,context:i.data,selectedRunId:t.seoRunId,onLatest:()=>p(f.id)},`${f.id}:${f.revision}:${t.seoRunId??``}`):!_&&a.data.profiles.length===0?(0,$.jsx)(Ef,{title:g?`SEO scope unavailable`:`Configure an SEO data provider`,children:g?i.data.scopes.find(e=>e.reason)?.reason??`No datasets are available for this project’s measurement scopes.`:`Connect a provider before creating an SEO profile.`}):d?(0,$.jsx)(Ef,{title:`Profile unavailable`,children:`This saved profile is no longer available. Select another profile to view its data.`}):!s&&(0,$.jsx)(Ef,{title:`No SEO data yet`,children:m?`Create a profile to choose the scope, source, and searches to measure.`:`An SEO profile is needed before data can be collected.`})]})}function Of({projectName:e,profile:t,context:n,selectedRunId:i,onLatest:a}){let o=S(),[s,c]=(0,Q.useState)(i?`activity`:t.capabilities.includes(U[`ranked-keywords`])?U[`ranked-keywords`]:t.capabilities.at(0)??`activity`),[l,u]=(0,Q.useState)(null),f=(0,Q.useRef)(null),p=(0,Q.useRef)(null),m={name:e},h=w({...Kr({client:K,path:m,query:{profileId:t.id,runId:i}}),refetchInterval:e=>df(e.state.data?.latestRun)?2e3:!1}),g=C({...ar({client:K}),meta:{skipGlobalErrorToast:!0}}),_=C({...Nr({client:K}),meta:{skipGlobalErrorToast:!0}}),v=h.data?.latestRun,y=h.data?.evidenceRun,b=h.data?.evidenceRun?.capabilities??t.capabilities,x=s===`activity`||b.includes(s)?s:b.at(0)??`activity`,T=df(v),E=g.isPending||_.isPending,D=n.access.canRun&&!Y()&&!Ze(),O=n.connections.find(e=>e.id===t.connectionId),k=n.scopes.find(e=>e.kind===t.scope.kind&&e.key===(t.scope.key??null)),A=w({...Br({client:K,path:m,query:{kind:st[`seo-sync`]}}),retry:!1}),j=!A.isError&&A.data?.enabled&&A.data.nextRunAt?A.data.nextRunAt:null,M=j?bf(j,A.data?.timezone??`UTC`):null,N=y?.finishedAt&&(y.status===Ot.completed||y.status===Ot.partial)?bf(y.finishedAt,of):null,P=T?null:Sf(v,y);return(0,Q.useEffect)(()=>{v&&(df(v)?p.current=v.id:p.current===v.id&&(p.current=null,Zn(o,`seo`,{projectName:e,profileId:t.id})))},[v,t.id,e,o]),(0,$.jsxs)(`div`,{className:`space-y-5`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 text-label-14 text-secondary`,children:[(0,$.jsx)(`div`,{"aria-live":`polite`,children:T&&v?(0,$.jsxs)(`p`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(r,{className:`size-4 animate-spin`,"aria-hidden":`true`}),v.cancelRequested?`Cancellation requested`:tf[v.status],` · `,v.completedTasks,` of `,v.taskCount,` `,_f(v),` completed`]}):(0,$.jsxs)(`p`,{children:[N&&y?.finishedAt?(0,$.jsxs)($.Fragment,{children:[`Updated `,(0,$.jsx)(`time`,{dateTime:y.finishedAt,title:Tt(y.finishedAt,of)??void 0,children:N})]}):`No completed refresh`,M&&j&&(0,$.jsxs)($.Fragment,{children:[` · Next refresh `,(0,$.jsx)(`time`,{dateTime:j,children:M})]})]})}),P&&(0,$.jsx)(X,{tone:`caution`,placement:`bottom`,label:P.label,text:P.text})]}),i?(0,$.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,onClick:a,children:`View latest data`}):D&&(0,$.jsxs)(q,{className:`pointer-coarse:min-h-11`,disabled:E||T||!n.available||!O,onClick:Jn(async()=>{if(!(!D||i||T||E)){u(null);try{if(!f.current){let e=await g.mutateAsync({path:m,body:{profileId:t.id}});if(e.availability!==rt.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 _.mutateAsync({path:m,body:f.current});f.current=null,df(e)&&(p.current=e.id),await o.fetchQuery(Kr({client:K,path:m,query:{profileId:t.id}}))}catch(e){Us(e).code===`VALIDATION_ERROR`&&(f.current=null),u(Bs(e))}}}),children:[(0,$.jsx)(d,{"aria-hidden":`true`,className:`size-4 ${E?`animate-spin`:``}`}),E?`Starting refresh…`:T?`Refresh in progress`:f.current?`Retry refresh`:`Refresh data`]})]}),l&&(0,$.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.`]}),i&&(0,$.jsxs)(`p`,{className:`break-all text-copy-13 text-secondary`,children:[`Viewing saved refresh `,i,`.`]}),h.data?.evidenceRun&&h.data.evidenceRun.profileRevision!==t.revision&&(0,$.jsxs)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:[`Saved data uses profile revision `,h.data.evidenceRun.profileRevision,` · `,gf(h.data.evidenceRun),` · `,h.data.evidenceRun.languageCode,`. The current profile has changed.`]}),!Ze()&&k&&!k.supported&&(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:k.reason??`This scope is not supported for domain data.`}),h.error?(0,$.jsx)(Tf,{error:h.error,retry:()=>{h.refetch()}}):h.data?.summary&&(0,$.jsxs)(`div`,{children:[(0,$.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,$.jsxs)(`dl`,{className:`grid grid-cols-1 gap-5 border-b border-subtle pb-5 sm:grid-cols-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13 text-secondary`,children:`Searches you rank for`}),(0,$.jsx)(`dd`,{className:`mt-2 text-heading-32 tabular-nums text-heading`,children:(0,$.jsx)(ff,{value:h.data.summary.organicKeywords})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13 text-secondary`,children:`In the top 10`}),(0,$.jsx)(`dd`,{className:`mt-2 text-heading-32 tabular-nums text-heading`,children:(0,$.jsx)(ff,{value:h.data.summary.inTop10})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[`Estimated organic traffic`,(0,$.jsx)(X,{text:`Modeled search traffic for this target and provider geography. This is not measured site traffic.`})]}),(0,$.jsx)(`dd`,{className:`mt-2 text-heading-32 tabular-nums text-heading`,children:(0,$.jsx)(ff,{value:h.data.summary.estimatedOrganicTraffic})})]})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{className:`flex flex-wrap gap-x-5 border-b border-subtle`,"aria-label":`SEO views`,children:[...b,`activity`].map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":x===e,className:`min-h-11 border-b-2 text-button-14 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${x===e?`border-strong text-primary`:`border-transparent text-secondary hover:text-primary`}`,onClick:()=>c(e),children:e===`activity`?`Activity`:Qd[e]},e))}),x===`activity`?(0,$.jsx)(lp,{projectName:e,profileId:t.id,canRun:D,selectedRunId:i}):h.isPending?(0,$.jsx)(`p`,{role:`status`,className:`py-8 text-copy-14 text-secondary`,children:`Loading saved data…`}):h.data&&(0,$.jsx)(kf,{projectName:e,profileId:t.id,runId:h.data.evidenceRunId,view:x,active:T,nextRefresh:M},`${t.id}:${x}:${h.data.evidenceRunId??`empty`}`)]}),(0,$.jsxs)(`details`,{className:`border-t border-subtle text-label-14 text-secondary`,children:[(0,$.jsx)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:`Data details`}),(0,$.jsxs)(`div`,{className:`space-y-4 pb-3 text-label-13`,children:[(0,$.jsxs)(`p`,{children:[`Current profile source: `,Ze()?`Fictional demo data`:O?.label??`Source unavailable`,`. Google; `,hf(t.rankings?.device??`unspecified`),`.`]}),h.data?.evidenceRun&&(0,$.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}`,`. `,gf(h.data.evidenceRun),` · `,h.data.evidenceRun.languageCode,` · profile revision `,h.data.evidenceRun.profileRevision,`.`]}),(0,$.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,$.jsx)(`p`,{children:`Current profile targets:`}),(0,$.jsx)(`ul`,{className:`space-y-1`,children:t.targets.map((e,t)=>(0,$.jsxs)(`li`,{className:`break-words`,children:[e.value,` · `,e.includeSubdomains?`includes subdomains`:`exact host`]},t))}),t.scope.expectedPlanRevision!==void 0&&(0,$.jsxs)(`p`,{children:[`Saved measurement plan revision `,t.scope.expectedPlanRevision,`.`]}),h.data?.summary&&(0,$.jsx)(Cf,{source:h.data.summary.provenance})]})]})]})}function kf({projectName:e,profileId:t,runId:n,view:r,active:i,nextRefresh:a}){return r===U[`market-rankings`]?n?(0,$.jsx)($f,{projectName:e,profileId:t,runId:n,active:i}):(0,$.jsx)(Ef,{title:`No market rankings yet`,children:a?`First refresh ${a}`:`Refresh this profile to rank its tracked queries in each market.`}):(0,$.jsx)(Af,{projectName:e,profileId:t,runId:n,view:r,active:i})}function Af({projectName:e,profileId:t,runId:n,view:r,active:i}){let[a,o]=(0,Q.useState)(1),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(),[d,f]=(0,Q.useState)(),p={client:K,path:{name:e},query:{profileId:t,runId:n??void 0,limit:nf,offset:(a-1)*nf}},m=w({...cr(p),enabled:!!n&&r===U[`ranked-keywords`]}),h=w({...br(p),enabled:!!n&&r===U[`keyword-metrics`]}),g=w({...Lr(p),enabled:!!n&&r===U[`domain-intelligence`]}),_=w({...Oi({...p,query:{...p.query,sort:l}}),placeholderData:j,enabled:!!n&&r===U[`competitor-discovery`]}),v=w({...Ur({...p,query:{...p.query,kind:s||void 0,sort:d}}),placeholderData:j,enabled:!!n&&r===U[`keyword-gaps`]}),y=r===U[`ranked-keywords`]?m:r===U[`keyword-metrics`]?h:r===U[`competitor-discovery`]?_:r===U[`keyword-gaps`]?v:g;return n?(0,$.jsxs)(`div`,{className:`space-y-3 pt-4`,children:[r===U[`keyword-gaps`]&&(0,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-3 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Show`}),(0,$.jsxs)(`select`,{"aria-label":`Show search gaps`,className:`${sf} w-auto`,value:s,onChange:e=>{c(e.target.value),o(1)},children:[(0,$.jsx)(`option`,{value:``,children:`All comparisons`}),(0,$.jsx)(`option`,{value:un.missing,children:`Missing`}),(0,$.jsx)(`option`,{value:un.shared,children:`Shared`}),(0,$.jsx)(`option`,{value:un.outranked,children:`Competitor ahead`})]})]}),(0,$.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===U[`competitor-discovery`]&&(0,$.jsxs)(`p`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[`Domains sharing organic searches`,(0,$.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,$.jsx)(Tf,{error:y.error,retry:()=>{y.refetch()}}):y.data?y.data.items.length===0?(0,$.jsx)(Ef,{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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`relative overflow-x-auto material-base`,role:`region`,"aria-label":`${Qd[r]} table`,"aria-busy":y.isFetching,tabIndex:0,children:[r===U[`ranked-keywords`]&&m.data&&(0,$.jsx)(Ff,{rows:m.data.items}),r===U[`keyword-metrics`]&&h.data&&(0,$.jsx)(If,{rows:h.data.items}),r===U[`domain-intelligence`]&&g.data&&(0,$.jsx)(Lf,{rows:g.data.items}),r===U[`competitor-discovery`]&&_.data&&(0,$.jsx)(Nf,{rows:_.data.items,sort:l,onSort:e=>{u(e),o(1)}}),r===U[`keyword-gaps`]&&v.data&&(0,$.jsx)(Pf,{rows:v.data.items,sort:d,onSort:e=>{f(e),o(1)}})]}),(0,$.jsx)(Ss,{page:a,pageSize:nf,visibleRows:y.data.items.length,totalRows:y.data.total,onPageChange:o,disabled:y.isFetching,className:`text-label-13 [&_button]:min-h-11`})]}):(0,$.jsxs)(`p`,{role:`status`,className:`py-8 text-label-14 text-secondary`,children:[`Loading `,Qd[r].toLowerCase(),`…`]})]}):(0,$.jsxs)(Ef,{title:`No saved data yet`,children:[`Refresh this profile to collect `,Qd[r].toLowerCase(),` for its saved scope.`]})}function jf({value:e}){return e===null?(0,$.jsx)(ff,{value:null}):(0,$.jsxs)($.Fragment,{children:[e>0?`+`:``,rf.format(e)]})}function Mf({label:e,sort:t,ascending:n,descending:r,align:i=`right`,onSort:a,help:o}){return(0,$.jsx)(Qf,{label:e,align:i,sorted:t===n?`ascending`:t===r?`descending`:null,onSort:()=>a(t===n?r:n),help:o,showUnsorted:!0})}function Nf({rows:e,sort:t,onSort:n}){return(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Organic competitors, from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(Mf,{label:`Competitor`,align:`left`,sort:t,ascending:Oe.domain,descending:Oe[`-domain`],onSort:n}),(0,$.jsx)(Mf,{label:`Shared searches`,sort:t,ascending:Oe.shared,descending:Oe[`-shared`],onSort:n}),(0,$.jsx)(Mf,{label:`Avg. position`,sort:t,ascending:Oe.position,descending:Oe[`-position`],onSort:n}),(0,$.jsx)(Mf,{label:`Est. organic traffic`,sort:t,ascending:Oe.traffic,descending:Oe[`-traffic`],onSort:n}),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`th`,{scope:`row`,className:lf,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.domain}),(0,$.jsxs)(`p`,{className:`mt-1 text-label-13 text-secondary`,children:[`Compared with `,e.target.value]})]}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.sharedKeywords})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.averagePosition})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.estimatedOrganicTraffic})}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsxs)(wf,{label:e.domain,source:e.provenance,children:[(0,$.jsx)(`p`,{children:`Average position covers shared searches. Traffic covers the competitor’s whole domain.`}),(0,$.jsxs)(`p`,{children:[`Competitor’s ranked searches: `,(0,$.jsx)(ff,{value:e.organicKeywords})]}),(0,$.jsxs)(`p`,{children:[`Target: `,e.target.value,` · includes subdomains`]})]})})]},`${e.target.value}:${e.domain}:${t}`))})]})}function Pf({rows:e,sort:t,onSort:n}){return(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Search gaps, from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(Mf,{label:`Search`,align:`left`,sort:t,ascending:Ee.keyword,descending:Ee[`-keyword`],onSort:n}),(0,$.jsx)(Mf,{label:`Comparison`,align:`left`,sort:t,ascending:Ee.kind,descending:Ee[`-kind`],onSort:n}),(0,$.jsx)(Mf,{label:`Your rank`,sort:t,ascending:Ee[`target-rank`],descending:Ee[`-target-rank`],onSort:n}),(0,$.jsx)(Mf,{label:`Competitor rank`,sort:t,ascending:Ee[`competitor-rank`],descending:Ee[`-competitor-rank`],onSort:n}),(0,$.jsx)(Mf,{label:`Rank gap`,sort:t,ascending:Ee[`rank-gap`],descending:Ee[`-rank-gap`],onSort:n,help:ef}),(0,$.jsx)(Mf,{label:`Monthly searches`,sort:t,ascending:Ee.volume,descending:Ee[`-volume`],onSort:n}),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`th`,{scope:`row`,className:lf,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.keyword}),(0,$.jsxs)(`p`,{className:`mt-1 text-label-13 text-secondary`,children:[e.target.value,` · `,e.competitor.value]})]}),(0,$.jsx)(`td`,{className:`px-4 py-3 align-top`,children:(0,$.jsx)(J,{tone:e.kind===un.shared?`neutral`:`caution`,children:$d[e.kind]})}),(0,$.jsx)(`td`,{className:cf,children:e.kind===un.missing?(0,$.jsx)(`span`,{className:`text-secondary`,children:`Not found`}):(0,$.jsx)(ff,{value:e.targetRankOrganic})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.competitorRankOrganic})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(jf,{value:e.rankGap})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.searchVolume})}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsxs)(wf,{label:`${e.keyword} against ${e.competitor.value}`,source:e.provenance,children:[(0,$.jsxs)(`p`,{children:[`Your ranking page: `,e.targetUrl?(0,$.jsx)(Jo,{url:e.targetUrl}):`Not supplied`]}),(0,$.jsxs)(`p`,{children:[`Competitor’s ranking page: `,e.competitorUrl?(0,$.jsx)(Jo,{url:e.competitorUrl}):`Not supplied`]}),(0,$.jsxs)(`p`,{children:[`Difficulty /100: `,(0,$.jsx)(ff,{value:e.keywordDifficulty})]}),(0,$.jsxs)(`p`,{children:[`CPC: `,(0,$.jsx)(ff,{value:e.cpcUsd,currency:!0})]})]})})]},`${e.target.value}:${e.competitor.value}:${e.keyword}:${t}`))})]})}function Ff({rows:e}){return(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Searches you rank for, from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Search`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Position`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Monthly searches`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Est. traffic`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Difficulty /100`}),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`th`,{scope:`row`,className:lf,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.keyword}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:(0,$.jsx)(ys,{value:e.url??e.target.value})})]}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.rankOrganic})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.searchVolume})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.estimatedTraffic})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.keywordDifficulty})}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsxs)(wf,{label:e.keyword,source:e.provenance,children:[(0,$.jsx)(`p`,{className:`break-all`,children:e.url??`Ranking URL not supplied`}),(0,$.jsxs)(`p`,{children:[`Target: `,e.target.value,` · `,e.target.includeSubdomains?`includes subdomains`:`exact host`]}),(0,$.jsxs)(`p`,{children:[uf,`: `,(0,$.jsx)(ff,{value:e.rankAbsolute})]}),(0,$.jsxs)(`p`,{children:[`CPC: `,(0,$.jsx)(ff,{value:e.cpcUsd,currency:!0})]}),(0,$.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 If({rows:e}){return(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Search demand from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Search`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Monthly searches`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`CPC`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Difficulty /100`}),(0,$.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Intent`}),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`${lf} text-primary`,children:e.keyword}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.searchVolume})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.cpcUsd,currency:!0})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.keywordDifficulty})}),(0,$.jsx)(`td`,{className:`px-4 py-3 align-top`,children:e.searchIntent??`Not supplied`}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsxs)(wf,{label:e.keyword,source:e.provenance,children:[(0,$.jsxs)(`p`,{children:[`Ad competition: `,e.adCompetition===null?`Not supplied`:St(e.adCompetition,ye.fraction)]}),(0,$.jsxs)(`p`,{children:[`Core search: `,e.coreKeyword??`Not supplied`]}),e.monthlySearches.length>0&&(0,$.jsx)(`dl`,{children:e.monthlySearches.map(e=>(0,$.jsxs)(`div`,{className:`flex justify-between gap-5`,children:[(0,$.jsxs)(`dt`,{children:[e.year,`-`,String(e.month).padStart(2,`0`)]}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ff,{value:e.searchVolume})})]},`${e.year}-${e.month}`))})]})})]},`${e.keyword}:${t}`))})]})}function Lf({rows:e}){return(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Domain comparison from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong`,children:`Domain`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Searches ranked for`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Est. organic traffic`}),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:e.map((e,t)=>(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`th`,{scope:`row`,className:lf,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.target.value}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:e.target.includeSubdomains?`Includes subdomains`:`Exact host`})]}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.organicKeywords})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.estimatedOrganicTraffic})}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsx)(wf,{label:e.target.value,source:e.provenance,children:(0,$.jsxs)(`dl`,{className:`grid grid-cols-2 gap-2`,children:[(0,$.jsx)(`dt`,{children:`Position 1`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ff,{value:e.top1})}),(0,$.jsx)(`dt`,{children:`Positions 2–3`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ff,{value:e.top2To3})}),(0,$.jsx)(`dt`,{children:`Positions 4–10`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ff,{value:e.top4To10})}),(0,$.jsx)(`dt`,{children:`Positions 11–20`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ff,{value:e.top11To20})}),(0,$.jsx)(`dt`,{children:`Est. traffic value`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(ff,{value:e.estimatedOrganicTrafficValueUsd,currency:!0})})]})})})]},`${e.target.value}:${t}`))})]})}var Rf=5,zf=10,Bf=`all`;function Vf(e){return e===Bf?Bf:vt.safeParse(e).data??null}var Hf={column:`ranks11To20`,descending:!0},Uf={3:`sm:grid-cols-3`,4:`sm:grid-cols-4`,5:`sm:grid-cols-5`},Wf=`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`,Gf=`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 Kf(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 qf(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 Jf(e){let t=e.filter(e=>e.kind===at.region).length;return t===e.length?{label:`Region`,plural:`regions`}:t===0?{label:`Market`,plural:`markets`}:{label:`Region or market`,plural:`regions and markets`}}function Yf(e,t){return e.counts[t]}function Xf(e){let t=e.descending?-1:1,n=e.column;return n===`label`?(e,n)=>t*(ln(e.label,n.label)||ln(e.key,n.key)):(e,r)=>t*(Yf(e,n)-Yf(r,n))||ln(e.label,r.label)||ln(e.key,r.key)}function Zf(e,t=250){let[n,r]=(0,Q.useState)(e),i=e.trim()===``;return(0,Q.useEffect)(()=>{if(i){r(``);return}let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[i,e,t]),i?``:n}function Qf({label:e,align:t,sorted:n,onSort:r,help:i,showUnsorted:a=!1}){return(0,$.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,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsxs)(`button`,{type:`button`,onClick:r,className:`${Wf} ${n?`text-primary`:``}`,children:[e,(n||a)&&(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`ml-0.5`,children:n===`ascending`?`↑`:n===`descending`?`↓`:`↕`})]}),i&&(0,$.jsx)(X,{text:i})]})})}function $f({projectName:e,profileId:t,runId:n,active:r}){let i=E({strict:!1}),a=T(),o=i.seoRegion,s=i.seoMarket,c=Vf(i.seoShow),l=an.safeParse(i.seoSort).data??B.rank,u=t=>{a({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...t}),replace:!0})},d=(0,Q.useId)(),f=w(jr({client:K,path:{name:e},query:{profileId:t,runId:n,regionKey:o,marketKey:s}}));if(f.error)return(0,$.jsx)(`div`,{className:`py-4`,children:(0,$.jsx)(Tf,{error:f.error,retry:()=>{f.refetch()}})});if(!f.data)return(0,$.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,$.jsx)(tp,{projectName:e,regionKey:o,marketKey:s,regionLabel:f.data.regionLabel,marketLabel:f.data.marketLabel});if(p.queries===0)return(0,$.jsxs)(`div`,{className:`pt-4`,children:[v,_?(0,$.jsxs)(Ef,{title:`No rankings here`,children:[`This refresh has no rankings for this `,s===void 0?`region`:`market`,`.`]}):(0,$.jsx)(Ef,{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=$e(m,p),b=c??(p.needsWork>0?ct[`needs-work`]:Bf),x=h.length>1||h.some(e=>e.kind===at.region),S=[`${rf.format(p.queries)} ${p.queries===1?`query`:`queries`}`,...p.partlyChecked>0?[`${rf.format(p.partlyChecked)} partly checked`]:[],...p.failed>0?[`${rf.format(p.failed)} failed`]:[],...p.cancelled>0?[`${rf.format(p.cancelled)} not searched`]:[]].join(` · `);return(0,$.jsxs)(`div`,{className:`space-y-6 pt-4`,children:[v,(0,$.jsxs)(`section`,{"aria-labelledby":d,className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-baseline justify-between gap-3`,children:[(0,$.jsx)(`h3`,{id:d,className:`text-heading-16 text-heading`,children:`Google rank`}),(0,$.jsx)(`p`,{className:`text-copy-13 tabular-nums text-secondary`,children:S})]}),(0,$.jsxs)(`dl`,{className:`grid grid-cols-2 gap-5 border-b border-subtle pb-5 ${Uf[y.length+1]??`sm:grid-cols-5`}`,children:[y.map(e=>(0,$.jsx)(ep,{label:e.label,help:Kf(e,m),value:p[e.count]},e.count)),(0,$.jsx)(ep,{label:`Rival ahead`,help:qf(m),value:p.rivalAhead,className:`sm:border-l sm:border-subtle sm:pl-5`})]})]}),x&&(0,$.jsx)(np,{projectName:e,groups:h,bands:y},`groups\u0000${g}`),(0,$.jsx)(rp,{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===B.rank?void 0:e}),urlQ:i.seoQ??``,onQ:e=>u({seoQ:e||void 0}),onClear:()=>u({seoShow:Bf,seoQ:void 0})},`queries\u0000${g}`)]})}function ep({label:e,help:t,value:n,className:r}){return(0,$.jsxs)(`div`,{className:r,children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-label-13 text-secondary`,children:[e,(0,$.jsx)(X,{text:t,placement:`bottom`})]}),(0,$.jsx)(`dd`,{className:`mt-2 text-heading-32 tabular-nums text-heading`,children:rf.format(n)})]})}function tp({projectName:e,regionKey:t,marketKey:n,regionLabel:r,marketLabel:i}){let a=r??`Region not in this refresh`;return(0,$.jsxs)(`nav`,{"aria-label":`Market rankings scope`,className:`flex flex-wrap items-center gap-x-2 text-label-14`,children:[(0,$.jsx)(A,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoRegion:void 0,seoMarket:void 0}),className:Gf,children:`All markets`}),t!==void 0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,children:`/`}),n===void 0?(0,$.jsx)(`span`,{"aria-current":`page`,className:`text-label-14-strong text-primary`,children:a}):(0,$.jsx)(A,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoMarket:void 0}),className:Gf,children:a})]}),n!==void 0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`text-muted`,children:`/`}),(0,$.jsx)(`span`,{"aria-current":`page`,className:`text-label-14-strong text-primary`,children:i??`Market not in this refresh`})]})]})}function np({projectName:e,groups:t,bands:n}){let r=T(),[i,a]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(1),l=Jf(t),u=(i===null?t:[...t].sort(Xf(i))).slice((s-1)*Rf,s*Rf),d=i??(n.some(e=>e.count===Hf.column)?Hf: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??Hf;a(t.column===e?{column:e,descending:!t.descending}:{column:e,descending:e!==`label`}),c(1)},m=e=>d?.column===e?d.descending?`descending`:`ascending`:null,h=e=>e.kind===at.region?t=>({...t,seoRegion:e.key,seoMarket:void 0}):t=>({...t,seoMarket:e.key}),g=`Google rank by ${l.label.toLowerCase()}`;return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`h3`,{className:`text-heading-16 text-heading`,children:[`By `,l.label.toLowerCase()]}),(0,$.jsx)(`div`,{className:`relative overflow-x-auto rounded-md border border-default`,role:`region`,"aria-label":g,tabIndex:0,children:(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:g}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(Qf,{label:l.label,align:`left`,sorted:m(`label`),onSort:()=>p(`label`)}),f.map(e=>(0,$.jsx)(Qf,{label:e.label,align:`right`,sorted:m(e.column),onSort:()=>p(e.column)},e.column)),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Open`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:u.map(t=>(0,$.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,$.jsx)(`th`,{scope:`row`,className:`min-w-36 px-4 py-3 text-left align-top text-label-14`,children:(0,$.jsx)(A,{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,$.jsx)(`td`,{className:cf,children:rf.format(t.counts[e.column])},e.column)),(0,$.jsx)(`td`,{className:`px-4 py-3 text-right align-top`,children:(0,$.jsx)(o,{"aria-hidden":`true`,className:`ml-auto size-4 text-muted`})})]},`${t.kind}:${t.key}`))})]})}),(0,$.jsx)(Ss,{page:s,pageSize:Rf,visibleRows:u.length,totalRows:t.length,onPageChange:c,itemLabel:l.plural,className:`text-label-13 [&_button]:min-h-11`})]})}function rp({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,Q.useId)(),[g,_]=(0,Q.useState)(f),v=Zf(g).trim().slice(0,200),y=(0,Q.useRef)(f);(0,Q.useEffect)(()=>{v!==y.current&&(y.current=v,p(v))},[v]);let b=`${c}\u0000${u}\u0000${v}`,[x,S]=(0,Q.useState)({filterKey:b,page:1});x.filterKey!==b&&S({filterKey:b,page:1});let C=x.filterKey===b?x.page:1,T=w({...Er({client:K,path:{name:e},query:{profileId:t,runId:n,regionKey:r,marketKey:i,outcome:c===Bf?void 0:c,q:v||void 0,sort:u,limit:zf,offset:(C-1)*zf}}),placeholderData:j}),E=[{value:ct[`needs-work`],label:`Needs work`,count:a.needsWork},...o.map(e=>({value:e.filter,label:e.label,count:a[e.count]})),{value:ct[`rival-ahead`],label:`Rival ahead`,count:a.rivalAhead},{value:ct[`partly-checked`],label:`Partly checked`,count:a.partlyChecked},{value:ct.failed,label:`Failed`,count:a.failed},{value:ct.cancelled,label:`Not searched`,count:a.cancelled},{value:Bf,label:`All`,count:a.queries}],D=[ct[`partly-checked`],ct.failed,ct.cancelled],O=E.filter(e=>e.value===c||e.count>0||!D.includes(e.value)),k=O.find(e=>e.value===c)?.label??`All`,A=u===B.rank?`ascending`:u===B[`-rank`]?`descending`:null,M=u===B.query?`ascending`:u===B[`-query`]?`descending`:null,N=T.data?.items??[],P=s===null?`not ranked`:`not in the top ${s}`,F=!T.data||T.isPlaceholderData?null:T.data.total===0?`No queries match`:`${rf.format(T.data.total)} ${T.data.total===1?`query`:`queries`}: ${k}`;return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,id:h,children:`Queries`}),(0,$.jsx)(X,{placement:`bottom`,text:`Needs work: queries ranking 11 or deeper, ${P}, or partly checked. Rival ahead: a tracked competitor ranks above the site.`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsxs)(`label`,{className:`flex min-w-0 items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`Show`}),(0,$.jsx)(`select`,{"aria-label":`Show queries`,value:c,onChange:e=>l(e.target.value),className:`${sf} min-w-0 sm:w-56`,children:O.map(e=>(0,$.jsxs)(`option`,{value:e.value,children:[e.label,` (`,rf.format(e.count),`)`]},e.value))})]}),(0,$.jsx)(Os,{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,$.jsx)(`p`,{role:`status`,className:`sr-only`,children:F}),T.error?(0,$.jsx)(Tf,{error:T.error,retry:()=>{T.refetch()}}):T.data?T.data.total===0?(0,$.jsxs)(`div`,{className:`py-12 text-center`,children:[(0,$.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`No queries match`}),(0,$.jsx)(q,{variant:`secondary`,className:`mt-4 pointer-coarse:min-h-11`,onClick:()=>{y.current=``,_(``),m()},children:`Clear filters`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`relative overflow-x-auto rounded-md border border-default ${T.isPlaceholderData?`opacity-60`:``}`,role:`region`,"aria-label":`Queries`,"aria-busy":T.isPlaceholderData,tabIndex:0,children:(0,$.jsxs)(`table`,{className:`w-full text-label-14`,children:[(0,$.jsxs)(`caption`,{className:`sr-only`,children:[`Queries: `,k]}),(0,$.jsx)(`thead`,{className:`bg-surface text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(Qf,{label:`Query`,align:`left`,sorted:M,onSort:()=>d(u===B.query?B[`-query`]:B.query)}),(0,$.jsx)(Qf,{label:`Google rank`,align:`right`,sorted:A,onSort:()=>d(u===B.rank?B[`-rank`]:B.rank)}),(0,$.jsx)(`th`,{className:`px-4 py-3 text-left text-label-13-strong whitespace-nowrap`,children:`Top rival`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:`Rival rank`}),(0,$.jsx)(`th`,{className:`${cf} text-label-13-strong`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Rank gap`,(0,$.jsx)(X,{text:ef,placement:`bottom`})]})}),(0,$.jsx)(`th`,{className:`px-4`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-subtle`,children:N.map((e,t)=>(0,$.jsx)(ip,{row:e,requested:s},`${e.marketKey}\u0000${e.queryId??e.queryText}\u0000${t}`))})]})}),(0,$.jsx)(Ss,{page:C,pageSize:zf,visibleRows:N.length,totalRows:T.data.total,onPageChange:e=>S({filterKey:b,page:e}),disabled:T.isFetching,itemLabel:`queries`,className:`text-label-13 [&_button]:min-h-11`})]}):(0,$.jsx)(`p`,{className:`py-8 text-copy-14 text-secondary`,children:`Loading queries…`})]})}function ip({row:e,requested:t}){let[n,r]=(0,Q.useState)(!1),i=(0,Q.useId)();return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`tr`,{className:n?`border-b-0`:void 0,children:[(0,$.jsxs)(`th`,{scope:`row`,className:lf,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.queryText}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:e.marketLabel})]}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(op,{row:e,requested:t})}),(0,$.jsx)(`td`,{className:`px-4 py-3 align-top text-label-13`,children:(0,$.jsx)(sp,{row:e})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(ff,{value:e.topCompetitor?.rankOrganic??null})}),(0,$.jsx)(`td`,{className:cf,children:(0,$.jsx)(jf,{value:e.rankGap})}),(0,$.jsx)(`td`,{className:`px-4 text-right align-top`,children:(0,$.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,$.jsxs)(`span`,{className:`sr-only`,children:[` for `,e.queryText,` in `,e.marketLabel]})]})})]}),(0,$.jsx)(`tr`,{id:i,hidden:!n,children:(0,$.jsx)(`td`,{colSpan:6,className:`bg-surface-subtle px-4 pb-4 pt-3`,children:(0,$.jsx)(cp,{row:e,requested:t})})})]})}function ap(e){return e.outcome===dt.failed||e.outcome===dt.cancelled}function op({row:e,requested:t}){return e.outcome===dt.failed?(0,$.jsx)(X,{tone:`caution`,label:`Failed`,placement:`bottom`,text:`Failed: the source returned no results for this search in this refresh.`}):e.outcome===dt.cancelled?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-secondary`,children:[`Not searched`,(0,$.jsx)(X,{placement:`bottom`,text:`The refresh was cancelled, or reached a spending limit, before this search ran.`})]}):e.rankOrganic===null?e.outcome===dt[`partly-checked`]?(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-secondary`,children:[`Not in top `,e.depth,(0,$.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,$.jsxs)(`span`,{className:`text-secondary`,children:[`Not in top `,e.depth]}):(0,$.jsx)($.Fragment,{children:e.rankOrganic})}function sp({row:e}){if(ap(e))return(0,$.jsxs)(`span`,{className:`text-muted`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`—`}),(0,$.jsx)(`span`,{className:`sr-only`,children:`No result`})]});let t=e.topCompetitor;return t?(0,$.jsxs)(`span`,{className:`inline-flex flex-wrap items-center gap-x-1.5 gap-y-1`,children:[(0,$.jsx)(`span`,{className:`text-primary`,children:t.domain}),e.rivalAhead&&(0,$.jsx)(J,{tone:`caution`,children:`Ahead`})]}):(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`None in top `,e.depth]})}function cp({row:e,requested:t}){let n=`text-muted`,r=`mt-0.5 text-primary`,i=e.outcome===dt.failed?`No result: the search failed`:e.outcome===dt.cancelled?`No result: not searched`:`Not in the top ${e.depth}`;return(0,$.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,$.jsxs)(`div`,{className:`sm:col-span-2 lg:col-span-4`,children:[(0,$.jsx)(`p`,{className:n,children:`Ranking page`}),e.url?(0,$.jsx)(Jo,{url:e.url}):(0,$.jsx)(`p`,{className:r,children:i})]}),(0,$.jsxs)(`div`,{className:`lg:col-span-2`,children:[(0,$.jsx)(`p`,{className:n,children:`Searched as`}),(0,$.jsxs)(`p`,{className:r,children:[`“`,e.searchText,`” from `,e.locationLabel]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:n,children:`Target`}),(0,$.jsxs)(`p`,{className:`${r} break-words`,children:[e.target.value,` · `,e.target.includeSubdomains?`includes subdomains`:`exact host`]})]}),e.rankOrganic!==null&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:n,children:uf}),(0,$.jsx)(`p`,{className:`${r} tabular-nums`,children:(0,$.jsx)(ff,{value:e.rankAbsolute})})]}),e.searchStatus===Ke.partial&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:n,children:`Results checked`}),(0,$.jsxs)(`p`,{className:`${r} tabular-nums`,children:[`Top `,e.depth,t===null?``:` of ${t}`]})]}),!ap(e)&&(0,$.jsxs)(`div`,{className:`sm:col-span-2 lg:col-span-2`,children:[(0,$.jsx)(`p`,{className:n,children:`Tracked competitors in these results`}),e.competitors.length?(0,$.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,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(`dt`,{className:`break-all text-primary`,children:e.domain}),(0,$.jsxs)(`dd`,{className:`text-right tabular-nums text-primary`,children:[`#`,e.rankOrganic]})]},e.domain))}):(0,$.jsxs)(`p`,{className:r,children:[`None in the top `,e.depth]})]}),e.provenance&&(0,$.jsx)(`div`,{className:`sm:col-span-2 lg:col-span-4`,children:(0,$.jsx)(Cf,{source:e.provenance})})]})}function lp({projectName:e,profileId:t,canRun:n,selectedRunId:r}){let[i,a]=(0,Q.useState)(r??null),[o,s]=(0,Q.useState)(null),c=w({...Cr({client:K,path:{name:e},query:{profileId:t}}),refetchInterval:e=>e.state.data?.runs.some(df)?2e3:!1}),l=w({...ni({client:K,path:{name:e,id:i??``}}),enabled:!!i,refetchInterval:e=>df(e.state.data)?2e3:!1}),u=C({...Di({client:K}),meta:{skipGlobalErrorToast:!0}}),d=async t=>{if(n&&!u.isPending){s(null);try{await u.mutateAsync({path:{name:e,id:t}})}catch(e){s(Bs(e))}}};if(c.error)return(0,$.jsx)(`div`,{className:`py-4`,children:(0,$.jsx)(Tf,{error:c.error,retry:()=>{c.refetch()}})});if(!c.data)return(0,$.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,$.jsxs)(`div`,{className:`divide-y divide-subtle`,children:[o&&(0,$.jsx)(`p`,{role:`alert`,className:`py-3 text-copy-14`,children:o}),f.map(e=>(0,$.jsxs)(`div`,{className:`py-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(pf,{status:e.status}),(0,$.jsx)(`span`,{className:`text-label-14`,children:Tt(e.createdAt,of)})]}),(0,$.jsxs)(`p`,{className:`text-copy-13 text-secondary`,children:[e.completedTasks,` of `,e.taskCount,` `,_f(e),` completed`,e.failedTasks>0?` · ${e.failedTasks} failed`:``]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsxs)(q,{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,$.jsxs)(`span`,{className:`sr-only`,children:[` for refresh `,e.id]})]}),n&&df(e)&&(0,$.jsx)(q,{variant:`secondary`,className:`pointer-coarse:min-h-11`,disabled:u.isPending||e.cancelRequested,onClick:Jn(()=>d(e.id)),children:e.cancelRequested?`Cancellation requested`:`Cancel refresh`})]})]}),i===e.id&&(0,$.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,$.jsxs)(`p`,{className:`break-all`,children:[`Refresh `,e.id]}),(0,$.jsxs)(`p`,{children:[`Profile revision `,e.profileRevision,` · `,gf(e),` · `,e.languageCode]}),(0,$.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,$.jsx)(`p`,{children:e.error}),l.error?(0,$.jsx)(Tf,{error:l.error,retry:()=>{l.refetch()}}):l.data?l.data.tasks.some(vf)&&(0,$.jsx)(`ul`,{className:`space-y-3`,children:l.data.tasks.filter(vf).map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{children:[Qd[e.capability],e.searchText===null?e.target?` · ${e.target.value}`:``:` · “${e.searchText}” from ${e.locationLabel??`its market`}`,e.comparison?` · ${e.comparison.competitor.value} · ${$d[e.comparison.mode]} searches`:``,e.retried?` · retried once`:``]}),(0,$.jsx)(pf,{status:e.status})]}),e.error&&(0,$.jsx)(`p`,{className:`mt-1`,children:e.error})]},e.id))}):(0,$.jsx)(`p`,{role:`status`,children:`Loading refresh details…`})]})]},e.id))]}):(0,$.jsx)(Ef,{title:`No refreshes yet`,children:`Refresh this profile to collect its first saved results.`})}function up({projectName:e,context:t,profile:n,id:r,onClose:i,onSaved:a}){let o=S(),[s,c]=(0,Q.useState)(n?.name??``),[l,u]=(0,Q.useState)(n?.connectionId??t.connections.at(0)?.id??``),[d,f]=(0,Q.useState)(n?.capabilities??[U[`ranked-keywords`]]),[p,m]=(0,Q.useState)(n?.targets??[{kind:$t.domain,value:``,includeSubdomains:!0}]),[g,_]=(0,Q.useState)(n?.competitors?.map(e=>e.value).join(`
|
|
2
|
-
`)??``),[v,y]=(0,Q.useState)(n?.keywords.join(`
|
|
3
|
-
`)??``),[b,x]=(0,Q.useState)(n?.locationCode.toString()??``),[w,T]=(0,Q.useState)(n?.languageCode??`en`),[E,D]=(0,Q.useState)(n?.limit.toString()??`100`),[O,k]=(0,Q.useState)(n?`${n.scope.kind}:${n.scope.key??``}`:`${bn.project}:`),[A,j]=(0,Q.useState)(null),M=C({...Ar({client:K}),meta:{skipGlobalErrorToast:!0}}),N=t.connections.find(e=>e.id===l),P=t.scopes.find(e=>`${e.kind}:${e.key??``}`===O),F=N?.capabilities.filter(e=>P?.capabilities?.includes(e)??!0)??[],I=d.filter(e=>F.includes(e)),L=I.includes(U[`keyword-gaps`]),R=L||I.includes(U[`competitor-discovery`]),z=I.some(e=>e!==U[`keyword-metrics`]),ee=I.includes(U[`ranked-keywords`])||R,te=(0,Q.useId)(),ne=I.includes(U[`market-rankings`]),re=e=>e===U[`market-rankings`]?!n?.rankings||I.some(e=>e!==U[`market-rankings`]):ne,B=F.includes(U[`market-rankings`])?n?.rankings?`Market rankings use their own profile.`:`Set up market rankings with the CLI or API.`:null,ie=async()=>{if(!t.access.canWrite||Y()||Ze()||M.isPending)return;if(!P){j(`Choose a measurement scope.`);return}if(R&&p.some(e=>e.kind!==$t.domain||!e.includeSubdomains)){j(`Organic competitors and search gaps require whole-domain targets including subdomains.`);return}let i={name:s,connectionId:l,capabilities:I,targets:z?p:[],keywords:v.split(`
|
|
4
|
-
`).map(e=>e.trim()).filter(Boolean),locationCode:Number(b),languageCode:w,limit:ee?Number(E):n?.limit??100,scope:{kind:P.kind,...P.key?{key:P.key}:{},...P.planRevision===void 0?{}:{expectedPlanRevision:P.planRevision}},...I.includes(U[`market-rankings`])&&n?.rankings?{rankings:n.rankings}:{},...L?{competitors:g.split(`
|
|
5
|
-
`).map(e=>e.trim()).filter(Boolean).map(e=>({kind:$t.domain,value:e,includeSubdomains:!0}))}:{}},c=_n.safeParse(i);if(!c.success)j(c.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(` `));else{j(null);try{await M.mutateAsync({path:{name:e,id:r},body:c.data}),await o.fetchQuery(ca({client:K,path:{name:e}})),a(r)}catch(e){j(Bs(e))}}},ae=(e,t)=>m(n=>n.map((n,r)=>r===e?{...n,...t}:n));return(0,$.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(),ie()},children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:n?`Edit profile`:`New profile`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,className:`size-9 pointer-coarse:min-h-11 pointer-coarse:min-w-11 p-0`,"aria-label":`Close profile editor`,onClick:i,children:(0,$.jsx)(h,{className:`size-4`,"aria-hidden":`true`})})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Profile name`}),(0,$.jsx)(`input`,{className:sf,required:!0,maxLength:120,value:s,onChange:e=>c(e.target.value),autoFocus:!0})]}),(0,$.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Source`}),(0,$.jsxs)(`select`,{className:sf,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,$.jsx)(`option`,{value:``,disabled:!0,children:`Select a source`}),t.connections.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}),(0,$.jsxs)(`label`,{className:`space-y-1.5 text-label-14 sm:col-span-2`,children:[(0,$.jsx)(`span`,{children:`Measurement scope`}),(0,$.jsxs)(`select`,{className:sf,required:!0,value:P?O:``,onChange:e=>{let n=t.scopes.find(t=>`${t.kind}:${t.key??``}`===e.target.value);k(e.target.value),f(e=>e.filter(e=>n?.capabilities?.includes(e)??!0))},children:[(0,$.jsx)(`option`,{value:``,disabled:!0,children:`Select a scope`}),t.scopes.map(e=>(0,$.jsx)(`option`,{value:`${e.kind}:${e.key??``}`,children:e.label},`${e.kind}:${e.key}`))]}),P?.reason?(0,$.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:P.reason}):P&&!P.supported&&(0,$.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:`Domain data is not supported for this scope.`})]})]}),(0,$.jsxs)(`fieldset`,{children:[(0,$.jsx)(`legend`,{className:`mb-2 text-label-14`,children:`Collect`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-2`,children:Object.values(U).map(e=>{let t=re(e);return(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:I.includes(e),disabled:!F.includes(e)||t,"aria-describedby":t&&B?te:void 0,onChange:t=>f(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))}),Qd[e]]},e)})}),P?.capabilities&&(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:`Available datasets follow this scope and source. Changing scope clears unsupported selections.`}),B&&(0,$.jsx)(`p`,{id:te,className:`mt-1 text-copy-13 text-secondary`,children:B})]}),z&&(0,$.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,$.jsx)(`legend`,{className:`mb-2 text-label-14`,children:`Targets`}),(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:ne?`Market rankings report the Google rank of one target: one of this project’s own domains.`:R?`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,$.jsxs)(`div`,{className:`grid items-end gap-3 sm:grid-cols-[1fr_13rem_auto]`,children:[(0,$.jsxs)(`label`,{className:`space-y-1 text-label-14`,children:[(0,$.jsxs)(`span`,{className:`sr-only`,children:[`Target `,t+1]}),(0,$.jsx)(`input`,{className:sf,value:e.value,placeholder:`example.com`,"aria-label":`Target ${t+1}`,onChange:e=>ae(t,{value:e.target.value}),required:!0,maxLength:253})]}),(0,$.jsxs)(`label`,{className:`space-y-1 text-label-14`,children:[(0,$.jsxs)(`span`,{className:`sr-only`,children:[`Target `,t+1,` kind`]}),(0,$.jsxs)(`select`,{className:sf,"aria-label":`Target ${t+1} kind`,value:e.kind,onChange:e=>ae(t,{kind:e.target.value,includeSubdomains:e.target.value===$t.domain}),children:[(0,$.jsx)(`option`,{value:$t.domain,children:`Domain + subdomains`}),(0,$.jsx)(`option`,{value:$t.host,children:`Exact host`})]})]}),(0,$.jsx)(q,{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,$.jsx)(q,{type:`button`,variant:`secondary`,className:`pointer-coarse:min-h-11`,disabled:p.length>=(ne?1:20),onClick:()=>m(e=>[...e,{kind:$t.domain,value:``,includeSubdomains:!0}]),children:`Add target`})]}),L&&(0,$.jsxs)(`label`,{className:`block space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Comparison domains`}),(0,$.jsx)(`textarea`,{className:`${sf} min-h-24`,value:g,onChange:e=>_(e.target.value),placeholder:`competitor.com`,required:!0}),(0,$.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.`})]}),I.includes(U[`keyword-metrics`])&&(0,$.jsxs)(`label`,{className:`block space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Searches`}),(0,$.jsx)(`textarea`,{className:`${sf} min-h-28`,value:v,onChange:e=>y(e.target.value),placeholder:`One search per line`}),(0,$.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,$.jsxs)(`div`,{className:`grid gap-4 ${ee?`sm:grid-cols-3`:`sm:grid-cols-2`}`,children:[(0,$.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Provider location code`}),(0,$.jsx)(`input`,{className:sf,type:`number`,min:1,step:1,required:!0,value:b,onChange:e=>x(e.target.value)}),(0,$.jsx)(`span`,{className:`block text-label-13 text-secondary`,children:ne?`Used only when the project has no markets or locations.`:`The source’s location identifier.`})]}),(0,$.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:`Language code`}),(0,$.jsx)(`input`,{className:sf,required:!0,minLength:2,maxLength:10,value:w,onChange:e=>T(e.target.value)})]}),ee&&(0,$.jsxs)(`label`,{className:`space-y-1.5 text-label-14`,children:[(0,$.jsx)(`span`,{children:R?`Result limit`:`Ranked searches per target`}),(0,$.jsx)(`input`,{className:sf,type:`number`,min:1,max:1e3,step:1,required:!0,value:E,onChange:e=>D(e.target.value)}),R&&(0,$.jsx)(`span`,{className:`block text-copy-13 text-secondary`,children:L?`For each gap comparison, shared and missing searches each have this limit. Other datasets use it per target.`:`Maximum rows per target and dataset.`})]})]}),A&&(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-secondary`,children:A}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(q,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:M.isPending||!N||!I.length,children:M.isPending?`Saving…`:`Save profile`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:i,children:`Cancel`})]})]})}var dp=[{value:`7`,label:`7d`},{value:`30`,label:`30d`},{value:`90`,label:`90d`},{value:`180`,label:`180d`}],fp=[{value:`1`,label:`1h`},{value:`24`,label:`24h`},{value:`168`,label:`7d`},{value:`720`,label:`30d`}],pp=20,mp=12,hp=20,gp=50,_p=3,vp=`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`,yp=`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500`,bp=`inline-flex w-fit cursor-pointer list-none items-center gap-1 rounded text-label-14 text-secondary hover:text-heading ${yp} [&::-webkit-details-marker]:hidden`,xp=`inline-flex items-center gap-1.5 rounded text-left ${yp}`,Sp={ai:`AI referral`,search:`Search`,social:`Social`,paid:`Paid`,referral:`Referral`,direct:`Direct`},Cp={cloudflare:`Cloudflare`,vercel:`Vercel`,"cloud-run":`Cloud Run`,wordpress:`WordPress`},wp={[pt.matched]:`Matched`,[pt.unmatched]:`No URL match`,[pt.ambiguous]:`Ambiguous URL match`,[pt[`unknown-host`]]:`Host not recorded`,[pt.redacted]:`URL redacted`,[pt[`not-configured`]]:`No Property plan`},Tp={[bt.verified]:`text-positive`,[bt.likely_real]:`text-heading`,[bt.unknown]:`text-secondary`},Ep=`This project's traffic source logs no IP address, so one person can't be told from another. AI-referred visits are still counted.`,Dp=`Each row is everyone on one browser version, so its visits are not one person's.`,Op=(e,t)=>`${e.toLocaleString()} ${t}${e===1?``:`s`}`,kp=e=>e.entryName??Sp[e.entryClass],Ap=e=>{if(!e.entryName)return e.paid&&e.entryClass!==`paid`?`Paid`:null;let t=e.paid&&e.entryClass!==`paid`?`${Sp[e.entryClass]}, paid`:Sp[e.entryClass];return t===kp(e)?null:t},jp=e=>Un(e,e),Mp=e=>e&&e.toUpperCase()!==`GET`?e.toUpperCase():null;function Np(){let e=E({strict:!1}),t=T(),n=k({select:e=>e.location.pathname});return{search:e,update:e=>{t({to:n,search:t=>({...t,...e}),replace:!0})}}}function Pp({projectName:e}){let{account:t}=qn(),{search:n,update:r}=Np();if(Y()||t?.role===jt.viewer)return(0,$.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,$.jsxs)(`section`,{"aria-labelledby":`journeys-heading`,className:`space-y-6`,children:[(0,$.jsx)(`h2`,{id:`journeys-heading`,className:`sr-only`,children:`Journeys`}),(0,$.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,$.jsx)(`button`,{type:`button`,"aria-current":i===e.value?`page`:void 0,onClick:()=>{i!==e.value&&(Ut(`other`),r({journeyView:e.value===`visitors`?void 0:e.value}))},className:`-mb-px border-b-2 pb-2 text-label-14 transition-colors ${yp} ${i===e.value?`border-mono-100 text-heading`:`border-transparent text-secondary hover:text-heading`}`,children:e.label},e.value))}),i===`visitors`?(0,$.jsx)(Bp,{projectName:e},`visitors:${e}`):(0,$.jsx)(Yp,{projectName:e},`agents:${e}`)]})}function Fp({options:e,value:t,onChange:n,label:r}){let i=(0,Q.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,$.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,$.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 ${yp} ${e.value===t?`bg-surface-active text-heading`:`text-secondary hover:text-heading`}`,children:e.label},e.value))})}function Ip({summary:e,children:t}){let[n,r]=(0,Q.useState)(!1);return(0,$.jsxs)(`details`,{open:n,onToggle:e=>r(e.currentTarget.open),className:`text-copy-14 text-secondary`,children:[(0,$.jsxs)(`summary`,{className:bp,children:[n?(0,$.jsx)(c,{className:`size-3.5`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`size-3.5`,"aria-hidden":`true`}),e]}),(0,$.jsx)(`div`,{className:`mt-3`,children:t})]})}function Lp({what:e,error:t,retry:n}){return(0,$.jsxs)(`div`,{role:`alert`,className:`space-y-2 text-copy-14 text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`Could not load `,e,`. `,Bs(t)]}),(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:n,children:`Retry`})]})}function Rp({label:e,help:t,children:n}){return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-13 text-secondary`,children:[e,t&&(0,$.jsx)(X,{placement:`bottom`,text:t})]}),(0,$.jsx)(`dd`,{className:`mt-1 text-heading-20 tabular-nums text-heading`,children:n})]})}function zp({projectName:e,partialSources:t}){return t.length===0?null:(0,$.jsx)(`ul`,{className:`space-y-1`,children:t.map(t=>(0,$.jsxs)(`li`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-label-14`,children:[(0,$.jsx)(_,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`text-heading`,children:[`Later visits are not recorded for `,Cp[t.sourceType]??t.sourceType,`.`]}),(0,$.jsx)(X,{placement:`bottom`,text:t.reason}),(0,$.jsx)(A,{to:`/traffic/$projectName/$sourceId`,params:{projectName:e,sourceId:t.sourceId},className:`rounded text-link underline-offset-4 hover:underline ${yp}`,children:`Review source`})]},t.sourceId))})}function Bp({projectName:e}){let{search:t,update:n}=Np(),r=dp.some(e=>e.value===t.journeyDays)?t.journeyDays:`30`,i=t.journeyEngine??``,a=t.journeyReturned===`true`||t.journeyReturned===`false`?t.journeyReturned:``,o=t.journeyMatching===En.ua?En.ua:``,s=Math.max(0,Number.parseInt(t.journeyOffset??`0`,10)||0),[c,l]=(0,Q.useState)(()=>new Date().toISOString()),u={since:new Date(Date.parse(c)-Number(r)*864e5).toISOString(),until:c},d=w({...Ri({client:K,path:{name:e},query:u}),staleTime:3e4}),f={...u,engine:i||void 0,returned:a||void 0,keyBasis:o||En[`ip-ua`],limit:pp,offset:s},p=w({...di({client:K,path:{name:e},query:f}),staleTime:3e4}),m=p.data,h=t.journeyVisitor??null;return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-10 gap-y-4`,children:[d.isPending?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading visitor summary…`}):d.isError?(0,$.jsx)(Lp,{what:`the visitor summary`,error:d.error,retry:()=>{d.refetch()}}):(0,$.jsx)(Vp,{summary:d.data}),(0,$.jsx)(Fp,{label:`First AI visit within`,options:dp,value:r,onChange:e=>{Ut(`window`),l(new Date().toISOString()),n({journeyDays:e===`30`?void 0:e,journeyOffset:void 0,journeyVisitor:void 0})}})]}),m&&(0,$.jsx)(zp,{projectName:e,partialSources:m.partialSources}),p.isPending?(0,$.jsx)(`p`,{role:`status`,className:`py-6 text-copy-14 text-secondary`,children:`Loading visitors…`}):p.isError?(0,$.jsx)(Lp,{what:`visitors`,error:p.error,retry:()=>{p.refetch()}}):m&&m.visitors.length===0&&!i&&!a&&!o&&d.data?.aiVisitors===null?(0,$.jsxs)(`div`,{className:`border-y border-default py-8 text-copy-14 text-secondary`,children:[(0,$.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:`Visitors can't be measured here.`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-prose`,children:Ep}),(0,$.jsx)(q,{className:`mt-3`,size:`sm`,variant:`outline`,onClick:()=>{Ut(`other`),n({journeyMatching:En.ua,journeyOffset:void 0,journeyVisitor:void 0})},children:`Show browser groups`})]}):m&&m.visitors.length===0&&!i&&!a&&!o?(0,$.jsxs)(`div`,{className:`border-y border-default py-8 text-copy-14 text-secondary`,children:[(0,$.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:`No AI-referred visitors in this period.`}),(0,$.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,$.jsx)(A,{to:`/traffic`,className:`mt-2 inline-block text-link hover:underline`,children:`Review traffic sources`})]}):m?(0,$.jsx)(Up,{projectName:e,data:m,engines:d.data?.byEngine.map(e=>e.engine)??[],engine:i,returned:a,matching:o,openKey:h,onToggle:e=>{e&&Be(`journeys.visitor_open`),n({journeyVisitor:e??void 0})},onFilter:e=>{Ut(`other`),n({...e,journeyOffset:void 0,journeyVisitor:void 0})},onPage:e=>n({journeyOffset:e===0?void 0:String(e),journeyVisitor:void 0})}):null,(0,$.jsx)(Ip,{summary:`About this data`,children:(0,$.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[d.data&&(0,$.jsx)(qp,{summary:d.data}),m&&(0,$.jsx)(Jp,{data:m})]})})]})}function Vp({summary:e}){let t=(0,$.jsx)(Rp,{label:`AI-referred visits`,children:e.aiVisits.toLocaleString()});if(e.aiVisitors===null||e.returningVisitors===null||e.returnedVia===null)return(0,$.jsxs)(`dl`,{className:`flex flex-wrap items-start gap-x-12 gap-y-4`,children:[t,(0,$.jsx)(Rp,{label:`Visitors and returns`,help:Ep,children:(0,$.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:St(e.returnRate,ye.fraction),i=e.keyBasis.ua>0?`${Op(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,$.jsxs)(`dl`,{className:`flex flex-wrap items-start gap-x-12 gap-y-4`,children:[t,(0,$.jsx)(Rp,{label:`AI-referred visitors`,help:i,children:e.aiVisitors.toLocaleString()}),(0,$.jsxs)(Rp,{label:`Came back`,help:r?`${r} came back in a later visit.`:void 0,children:[e.returningVisitors.toLocaleString(),` `,(0,$.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[`of `,e.aiVisitors.toLocaleString()]}),r&&(0,$.jsxs)(`span`,{className:`sr-only`,children:[`, a `,r,` return rate`]})]}),(0,$.jsx)(Rp,{label:`Median time to return`,children:e.medianDaysToReturn===null?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not available`}):gt(e.medianDaysToReturn)}),(0,$.jsx)(Rp,{label:`Return visits by channel`,children:n.length===0?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`None yet`}):(0,$.jsx)(`span`,{className:`flex flex-wrap gap-x-3 gap-y-1 text-label-14 text-heading`,children:n.map(([e,t])=>(0,$.jsxs)(`span`,{children:[Sp[e],` `,(0,$.jsx)(`span`,{className:`tabular-nums text-secondary`,children:t.toLocaleString()})]},e))})})]})}function Hp({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,$.jsx)(`span`,{className:`text-secondary`,children:e.returned?`Came back`:`No return yet`});let r=[];for(let e of n){let t=`${kp(e)}${e.paid?` (paid)`:``}`,n=r.at(-1);n?.label===t?n.visits++:r.push({label:t,visits:1})}let i=r.slice(0,_p),a=e.returnChannels.length-i.reduce((e,t)=>e+t.visits,0);return(0,$.jsxs)(`span`,{className:`text-heading`,children:[i.map(e=>e.visits>1?`${e.label} ×${e.visits}`:e.label).join(`, `),a>0&&(0,$.jsxs)(`span`,{className:`text-secondary`,children:[` +`,a.toLocaleString(),` more`]})]})}function Up({projectName:e,data:t,engines:n,engine:r,returned:i,matching:a,openKey:s,onToggle:l,onFilter:u,onPage:d}){let f=!!(r||i||a),p=a===En.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,$.jsxs)(`section`,{"aria-label":`AI-referred visitors`,className:`min-w-0 space-y-2`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,$.jsxs)(`p`,{role:`status`,className:`text-label-13 text-secondary`,children:[m.toLocaleString(),` to `,h.toLocaleString(),` of `,Op(t.totalVisitors,p?`browser group`:`visitor`)]}),(0,$.jsxs)(`details`,{className:`text-label-14`,open:f||void 0,children:[(0,$.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 ${yp} [&::-webkit-details-marker]:hidden`,children:[(0,$.jsx)(b,{className:`size-3`,"aria-hidden":`true`}),`Filter`,f&&(0,$.jsx)(`span`,{className:`text-heading`,children:[r,i===`true`?`Came back`:i===`false`?`No return yet`:``,p?`Browser groups`:``].filter(Boolean).join(` · `)})]}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-end gap-3`,children:[(0,$.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`First AI engine`,(0,$.jsxs)(`select`,{className:vp,value:r,onChange:e=>u({journeyEngine:e.target.value||void 0}),children:[(0,$.jsx)(`option`,{value:``,children:`All engines`}),r&&!n.includes(r)&&(0,$.jsx)(`option`,{value:r,children:r}),n.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e))]})]}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Came back`,(0,$.jsxs)(`select`,{className:vp,value:i,onChange:e=>u({journeyReturned:e.target.value||void 0}),children:[(0,$.jsx)(`option`,{value:``,children:`All visitors`}),(0,$.jsx)(`option`,{value:`true`,children:`Came back`}),(0,$.jsx)(`option`,{value:`false`,children:`No return yet`})]})]}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Matched by`,(0,$.jsxs)(`select`,{className:vp,value:a,onChange:e=>u({journeyMatching:e.target.value||void 0}),children:[(0,$.jsx)(`option`,{value:``,children:`Network and browser`}),(0,$.jsx)(`option`,{value:En.ua,children:`Browser only (groups)`})]})]}),f&&(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>u({journeyEngine:void 0,journeyReturned:void 0,journeyMatching:void 0}),children:`Clear filters`})]})]})]}),p&&(0,$.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,$.jsx)(_,{className:`size-3.5 shrink-0 text-caution`,"aria-hidden":`true`}),Dp]}),s&&g&&(0,$.jsxs)(`div`,{className:`rounded-md border border-default bg-surface-subtle px-4 py-4 sm:px-8`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,$.jsx)(`p`,{className:`text-label-13 text-secondary`,children:`This visitor is not on this page of the list.`}),(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>l(null),children:`Close`})]}),(0,$.jsx)(Wp,{projectName:e,visitorKey:s,partialSources:t.partialSources})]}),t.visitors.length===0?(0,$.jsx)(`p`,{className:`rounded-md border border-default p-5 text-copy-14 text-secondary`,children:`No visitors match these filters.`}):(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[42rem]`,"aria-label":`AI-referred visitors`,children:[(0,$.jsx)(`thead`,{className:`bg-surface-subtle text-left text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`py-2 pl-3 pr-2 font-normal`,children:`First AI visit`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-2 py-2 font-normal`,children:`Landing page`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-2 py-2 font-normal`,children:`Came back through`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-2 py-2 text-right font-normal`,children:`Visits`}),(0,$.jsx)(`th`,{scope:`col`,className:`py-2 pl-2 pr-3 text-right font-normal`,children:`Last seen`})]})}),(0,$.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,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{className:r?`bg-surface-active`:`hover:bg-surface-hover`,children:[(0,$.jsx)(`td`,{className:`py-2.5 pl-3 pr-2 align-top`,children:(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":r?a:void 0,"aria-label":`${n.firstAiEngine} visitor, first AI visit ${Un(n.firstAiAt)}`,onClick:()=>l(r?null:n.visitorKey),className:`${xp} whitespace-nowrap`,children:[r?(0,$.jsx)(c,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:n.firstAiEngine}),(0,$.jsx)(`time`,{dateTime:n.firstAiAt,className:`text-label-14 text-secondary`,children:In(n.firstAiAt)})]})}),(0,$.jsx)(`td`,{className:`px-2 py-2.5 align-top`,children:i?(0,$.jsx)(`span`,{className:`block max-w-[18rem] truncate text-label-13-mono text-heading`,title:i.landingPath,children:qs(i.landingPath)}):(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Not kept`})}),(0,$.jsx)(`td`,{className:`px-2 py-2.5 align-top text-label-14`,children:(0,$.jsx)(Hp,{visitor:n})}),(0,$.jsx)(`td`,{className:`px-2 py-2.5 text-right align-top text-label-14 tabular-nums text-heading`,children:n.visitCount.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-2.5 pl-2 pr-3 text-right align-top text-label-14 text-secondary`,children:(0,$.jsx)(`time`,{dateTime:n.lastSeenAt,children:In(n.lastSeenAt)})})]}),r&&(0,$.jsx)(`tr`,{id:a,children:(0,$.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-8`,children:(0,$.jsx)(Wp,{projectName:e,visitorKey:n.visitorKey,partialSources:t.partialSources})})})]},n.visitorKey)})})]})}),(t.totalVisitors>t.limit||t.offset>0)&&(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:t.offset===0,onClick:()=>d(Math.max(0,t.offset-t.limit)),children:`Previous`}),(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:t.offset+t.limit>=t.totalVisitors,onClick:()=>d(t.offset+t.limit),children:`Next visitors`})]})]})}function Wp({projectName:e,visitorKey:t,partialSources:n}){let[r,i]=(0,Q.useState)(0),[a,o]=(0,Q.useState)(Tn.pages),[s,c]=(0,Q.useState)(null),l=w({...Ti({client:K,path:{name:e,visitorKey:t},query:{limit:mp,offset:r,events:a}}),staleTime:3e4,placeholderData:e=>e});if(l.isPending)return(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading visits…`});if(l.isError)return(0,$.jsx)(Lp,{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,$.jsxs)(`div`,{className:`space-y-4`,role:`region`,"aria-label":`Visits by this visitor`,children:[(0,$.jsxs)(`p`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1 text-label-13 text-secondary`,children:[(0,$.jsx)(`span`,{className:`text-heading`,children:d.device}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsx)(`span`,{children:Op(u.totalVisits,`visit`)}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[d.keyBasis===En.ua?`Matched by browser only`:`Matched by network and browser`,(0,$.jsx)(X,{placement:`bottom`,text:d.keyBasis===En.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,$.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14`,children:[(0,$.jsx)(_,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`text-heading`,children:[`Some requests are missing on `,Op(d.cappedDays,`day`),`.`]}),(0,$.jsx)(X,{placement:`bottom`,text:`At most ${300 .toLocaleString()} requests per visitor are kept each day.`})]}),(0,$.jsx)(Gp,{visits:u.visits,openId:s,events:u.events,loading:l.isFetching,onToggle:e=>{e&&Be(`journeys.visit_open`),c(e)},onToggleEvents:()=>o(a===Tn.pages?Tn.all:Tn.pages)}),m&&(0,$.jsxs)(`p`,{className:`text-label-13 text-secondary`,children:[`Later visits are not recorded by `,Cp[m.sourceType]??m.sourceType,`.`]}),(u.totalVisits>u.limit||u.offset>0)&&(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:u.offset===0||l.isFetching,onClick:()=>{i(Math.max(0,u.offset-u.limit)),c(null)},children:`Earlier visits`}),(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:f||l.isFetching,onClick:()=>{i(u.offset+u.limit),c(null)},children:`Later visits`})]}),(0,$.jsx)(Ip,{summary:`Technical details`,children:(0,$.jsxs)(`dl`,{className:`max-w-prose space-y-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13-strong text-heading`,children:`Visitor key`}),(0,$.jsx)(`dd`,{className:`break-all text-label-13-mono`,children:d.visitorKey})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13-strong text-heading`,children:`Last recorded request`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(`time`,{dateTime:d.lastSeenAt,children:Mn(d.lastSeenAt)})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-13-strong text-heading`,children:`User agent`}),(0,$.jsx)(`dd`,{className:`break-all text-label-13-mono`,children:d.userAgent??`Not recorded`})]})]})})]})}function Gp({visits:e,openId:t,events:n,loading:r,onToggle:i,onToggleEvents:a}){return(0,$.jsxs)(`table`,{className:`w-full`,"aria-label":`Visits in time order`,children:[(0,$.jsx)(`thead`,{className:`text-left text-label-12 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`When`}),(0,$.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`Came from`}),(0,$.jsx)(`th`,{scope:`col`,className:`pb-1.5 pr-4 font-normal`,children:`Landing page`}),(0,$.jsx)(`th`,{scope:`col`,className:`pb-1.5 text-right font-normal`,children:`Pages`})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-default`,children:e.map(e=>{let s=e.id===t,l=Ap(e);return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`whitespace-nowrap py-2 pr-4 align-top`,children:(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":s,onClick:()=>i(s?null:e.id),className:`${xp} text-label-14 text-heading`,children:[s?(0,$.jsx)(c,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),(0,$.jsx)(`time`,{dateTime:e.startedAt,children:Un(e.startedAt)})]})}),(0,$.jsxs)(`td`,{className:`py-2 pr-4 align-top text-label-14`,children:[(0,$.jsx)(`span`,{className:e.entryClass===`ai`?`text-label-14-strong text-heading`:`text-heading`,children:kp(e)}),l&&(0,$.jsxs)(`span`,{className:`text-secondary`,children:[` · `,l]})]}),(0,$.jsx)(`td`,{className:`py-2 pr-4 align-top`,children:(0,$.jsx)(`span`,{className:`block max-w-[22rem] truncate text-label-13-mono text-heading`,title:e.landingPath,children:qs(e.landingPath)})}),(0,$.jsx)(`td`,{className:`py-2 text-right align-top text-label-14 tabular-nums text-heading`,children:e.pageCount.toLocaleString()})]}),s&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:4,className:`pb-3 pl-6`,children:(0,$.jsx)(Kp,{visit:e,events:n,loading:r,onToggleEvents:a})})})]},e.id)})})]})}function Kp({visit:e,events:t,loading:n,onToggleEvents:r}){return(0,$.jsxs)(`div`,{className:`space-y-2`,children:[e.events.length===0?(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:t===Tn.pages?`No pages recorded for this visit.`:`No requests recorded for this visit.`}):(0,$.jsx)(`ol`,{"aria-label":`${kp(e)} visit requests`,className:`space-y-1`,children:e.events.map((e,t)=>(0,$.jsxs)(`li`,{className:`flex items-baseline gap-3`,children:[(0,$.jsx)(`time`,{dateTime:e.ts,className:`w-20 shrink-0 text-label-13 tabular-nums text-secondary`,children:jp(e.ts)}),(0,$.jsxs)(`span`,{className:`min-w-0 break-all text-label-13-mono text-heading`,children:[Mp(e.method)&&(0,$.jsxs)(`span`,{className:`text-secondary`,children:[Mp(e.method),` `]}),e.path]}),e.status!==null&&e.status>=400&&(0,$.jsx)(`span`,{className:`text-label-13 tabular-nums text-caution`,children:e.status})]},`${e.ts}:${t}`))}),(0,$.jsx)(`button`,{type:`button`,disabled:n,onClick:r,className:`rounded text-label-13 text-link hover:underline disabled:opacity-50 ${yp}`,children:t===Tn.pages?`Show all ${Op(e.requestCount,`request`)}`:`Show fewer requests`})]})}function qp({summary:e}){return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`p`,{children:[Op(e.aiVisits,`AI-referred visit`),` started in this period, including visits from earlier visitors.`]}),e.byEngine.length>0&&(0,$.jsxs)(`table`,{className:`w-full max-w-md text-label-14`,"aria-label":`Visitors by first AI engine`,children:[(0,$.jsx)(`thead`,{className:`text-left text-label-13`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 font-normal`,children:`First AI engine`}),(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 text-right font-normal`,children:`Visitors`}),(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 text-right font-normal`,children:`Came back`})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-default`,children:e.byEngine.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`py-1.5 text-heading`,children:e.engine}),(0,$.jsx)(`td`,{className:`py-1.5 text-right tabular-nums text-heading`,children:e.visitors.toLocaleString()}),(0,$.jsx)(`td`,{className:`py-1.5 text-right tabular-nums text-heading`,children:e.returningVisitors.toLocaleString()})]},e.engine))})]}),(0,$.jsxs)(`p`,{children:[`Matching: `,Op(e.keyBasis.ipUa,`visitor`),` by network and browser, `,Op(e.keyBasis.ua,`visitor`),` by browser only. Visitor figures count only the first: one browser version can be many people.`]})]})}function Jp({data:e}){return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`p`,{children:[`Visitors are picked by their first AI visit, from `,Un(e.windowStart),` to `,Un(e.windowEnd),`. Their later visits show even after that.`]}),(0,$.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,$.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,$.jsxs)(`p`,{children:[(0,$.jsxs)(`span`,{className:`text-label-14-strong text-heading`,children:[Cp[e.sourceType]??e.sourceType,`:`]}),` `,e.reason]},e.sourceId))]})}function Yp({projectName:e}){let{search:t,update:n}=Np(),r=fp.some(e=>e.value===t.agentHours)?t.agentHours:`24`,[i,a]=(0,Q.useState)(()=>new Date().toISOString()),[s,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(0),[x,S]=(0,Q.useState)(null),[C,T]=(0,Q.useState)({properties:[],sources:[]}),E=(0,Q.useRef)(null),D={since:new Date(Date.parse(i)-Number(r)*36e5).toISOString(),until:i,sourceId:s||void 0,agentId:u?.id,trust:f||void 0,targetKey:m||void 0},O=w({...ui({client:K,path:{name:e},query:{...D,limit:hp,offset:v}}),staleTime:3e4}),k=O.data;(0,Q.useEffect)(()=>{k&&T({properties:k.properties,sources:k.coverage.sources})},[k]);let A=k?.properties??C.properties,j=k?.coverage.sources??C.sources,M=A.find(e=>e.key===m),N=j.find(e=>e.sourceId===s),P=()=>{y(0),S(null)},F=!!(s||f||m||u);return(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-x-10 gap-y-4`,children:[k?(0,$.jsx)(Xp,{context:k}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Requests AI assistants made for a person`}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start gap-3`,children:[(0,$.jsxs)(`details`,{className:`text-label-14`,open:F||void 0,children:[(0,$.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 ${yp} [&::-webkit-details-marker]:hidden`,children:[(0,$.jsx)(b,{className:`size-3`,"aria-hidden":`true`}),`Filter`]}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-end gap-3`,children:[(0,$.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Source`,(0,$.jsxs)(`select`,{className:vp,value:s,onChange:e=>{Ut(`other`),l(e.target.value),P()},children:[(0,$.jsx)(`option`,{value:``,children:`All sources`}),j.map(e=>(0,$.jsx)(`option`,{value:e.sourceId,children:e.label},e.sourceId))]})]}),(0,$.jsxs)(`label`,{className:`grid gap-1 text-label-13 text-secondary`,children:[`Trust`,(0,$.jsxs)(`select`,{className:vp,value:f,onChange:e=>{Ut(`other`),p(e.target.value),P()},children:[(0,$.jsx)(`option`,{value:``,children:`All trust levels`}),Object.values(bt).filter(e=>e!==bt.likely_fake).map(e=>(0,$.jsx)(`option`,{value:e,children:Gs[e]},e))]})]}),A.length>0&&(0,$.jsxs)(`details`,{ref:E,className:`relative`,children:[(0,$.jsxs)(`summary`,{className:`${vp} inline-flex cursor-pointer list-none items-center py-1.5 [&::-webkit-details-marker]:hidden`,children:[`Property: `,M?.label??`All properties`]}),(0,$.jsxs)(`div`,{className:`mt-2 w-72 max-w-full`,children:[(0,$.jsx)(`input`,{"aria-label":`Find a property`,type:`search`,value:g,onChange:e=>_(e.target.value),placeholder:`Find a property`,className:`${vp} mb-2 w-full`}),(0,$.jsx)(`div`,{className:`max-h-64 overflow-y-auto`,role:`group`,"aria-label":`Properties`,children:[{key:``,label:`All properties`},...A.filter(e=>e.label.toLowerCase().includes(g.toLowerCase()))].map(e=>(0,$.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 ${yp}`,onClick:()=>{Ut(`other`),h(e.key),P(),E.current&&(E.current.open=!1,E.current.querySelector(`summary`)?.focus())},children:e.label},e.key))})]})]}),F&&(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>{Ut(`other`),l(``),p(``),h(``),d(null),P()},children:`Clear filters`})]})]}),(0,$.jsx)(Fp,{label:`Period`,options:fp,value:r,onChange:e=>{Ut(`window`),a(new Date().toISOString()),P(),n({agentHours:e===`24`?void 0:e})}})]})]}),F&&(0,$.jsxs)(`p`,{className:`flex flex-wrap items-center gap-x-4 gap-y-1 text-label-14 text-secondary`,children:[s&&(0,$.jsxs)(`span`,{children:[`Source: `,(0,$.jsx)(`span`,{className:`text-heading`,children:N?.label??s})]}),f&&(0,$.jsxs)(`span`,{children:[`Trust: `,(0,$.jsx)(`span`,{className:`text-heading`,children:Gs[f]})]}),m&&(0,$.jsxs)(`span`,{children:[`Property: `,(0,$.jsx)(`span`,{className:`text-heading`,children:M?.label??m})]}),u&&(0,$.jsxs)(`span`,{children:[`Agent: `,(0,$.jsx)(`span`,{className:`text-heading`,children:u.label})]})]}),O.isPending?(0,$.jsx)(`p`,{role:`status`,className:`py-6 text-copy-14 text-secondary`,children:`Loading agent requests…`}):O.isError?(0,$.jsx)(Lp,{what:`agent requests`,error:O.error,retry:()=>{O.refetch()}}):k?(0,$.jsxs)($.Fragment,{children:[k.journeys.length===0?(0,$.jsxs)(`div`,{className:`border-y border-default py-8 text-copy-14 text-secondary`,children:[(0,$.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:`No agent requests in this period.`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-prose`,children:`Try a longer period or clear filters.`})]}):(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[40rem]`,"aria-label":`Agent visits`,children:[(0,$.jsx)(`thead`,{className:`bg-surface-subtle text-left text-label-13 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`Agent`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`Trust`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`First page`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 font-normal`,children:`Started`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 text-right font-normal`,children:`Requests`})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-default`,children:k.journeys.map(t=>{let n=x===t.id;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{className:n?`bg-surface-active`:`hover:bg-surface-hover`,children:[(0,$.jsx)(`td`,{className:`px-3 py-2.5 align-top`,children:(0,$.jsxs)(`button`,{type:`button`,"aria-expanded":n,"aria-controls":n?`agent-sequence-${t.id}`:void 0,"aria-label":`${t.product} visit starting ${Un(t.startedAt)}`,onClick:()=>{n||Be(`journeys.agent_open`),S(n?null:t.id)},className:`${xp} text-label-14-strong text-heading`,children:[n?(0,$.jsx)(c,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}):(0,$.jsx)(o,{className:`size-3.5 shrink-0 text-secondary`,"aria-hidden":`true`}),t.product]})}),(0,$.jsx)(`td`,{className:`px-3 py-2.5 align-top text-label-14`,children:t.trustLevels.map(e=>(0,$.jsx)(`span`,{className:`block ${Tp[e]}`,children:Gs[e]},e))}),(0,$.jsx)(`td`,{className:`px-3 py-2.5 align-top`,children:(0,$.jsx)(`span`,{className:`block max-w-[22rem] truncate text-label-13-mono text-heading`,title:`${t.firstHost??``}${t.firstPath}`,children:t.firstPath})}),(0,$.jsx)(`td`,{className:`whitespace-nowrap px-3 py-2.5 align-top text-label-14 text-secondary`,children:(0,$.jsx)(`time`,{dateTime:t.startedAt,children:Un(t.startedAt)})}),(0,$.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,$.jsx)(`span`,{className:`block text-label-13 text-caution`,children:Op(t.errorCount,`error`)})]})]}),n&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:5,className:`bg-surface-subtle px-4 py-4 sm:px-10`,children:(0,$.jsx)(Zp,{projectName:e,journey:t,selection:{...D,since:k.windowStart,until:k.windowEnd},onSelectAgent:()=>{Ut(`other`),d({id:t.agentId,label:t.product}),P()}})})})]},t.id)})})]})}),(k.totalJourneys>k.limit||k.offset>0)&&(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:k.offset===0||O.isFetching,onClick:()=>{y(Math.max(0,k.offset-k.limit)),S(null)},children:`Previous`}),(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:k.offset+k.limit>=k.totalJourneys||O.isFetching,onClick:()=>{y(k.offset+k.limit),S(null)},children:`Next agent visits`})]}),(0,$.jsx)(Ip,{summary:`About this data`,children:(0,$.jsx)($p,{context:k})})]}):null]})}function Xp({context:e}){let t=e.coverage.likelyFakeRequests;return(0,$.jsxs)(`div`,{className:`space-y-2`,children:[(0,$.jsxs)(`dl`,{className:`flex flex-wrap items-start gap-x-12 gap-y-4`,children:[(0,$.jsx)(Rp,{label:`Agent visits`,help:`Requests an AI assistant made for a person, grouped when they come close together.`,children:e.totalJourneys.toLocaleString()}),(0,$.jsx)(Rp,{label:`Requests`,children:e.observedRequests.toLocaleString()}),t!==null&&t>0&&(0,$.jsx)(Rp,{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,$.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,$.jsx)(_,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Recording is off on this instance.`]}),e.coverage.cappedSourceDays.length>0&&(0,$.jsxs)(`p`,{className:`flex items-center gap-2 text-label-14 text-heading`,children:[(0,$.jsx)(_,{className:`size-3.5 text-caution`,"aria-hidden":`true`}),`Some requests are missing: a source reached its daily limit.`]})]})}function Zp({projectName:e,journey:t,selection:n,onSelectAgent:r}){let[i,a]=(0,Q.useState)(0),o=w({...wi({client:K,path:{name:e,journeyId:t.id},query:{...n,limit:gp,offset:i}}),staleTime:3e4});return(0,$.jsxs)(`div`,{id:`agent-sequence-${t.id}`,role:`region`,"aria-label":`${t.product} requests`,className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[o.data&&o.data.events.length>0?(0,$.jsx)(Qp,{operator:t.operator,events:o.data.events}):(0,$.jsx)(`span`,{}),(0,$.jsxs)(q,{size:`sm`,variant:`outline`,onClick:r,children:[`Only `,t.product]})]}),o.isPending?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading requests…`}):o.isError?(0,$.jsx)(Lp,{what:`these requests`,error:o.error,retry:()=>{o.refetch()}}):(0,$.jsxs)($.Fragment,{children:[o.data.events.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No recorded requests on this page.`}):(0,$.jsxs)(`table`,{className:`w-full max-w-4xl`,"aria-label":`${t.product} recorded requests`,children:[(0,$.jsx)(`thead`,{className:`text-left text-label-12 text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 font-normal`,children:`Time`}),(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 font-normal`,children:`Request`}),o.data.scope.mode===`advanced`&&(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 font-normal`,children:`Property`}),(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 pr-3 text-right font-normal`,children:`Latency`}),(0,$.jsx)(`th`,{scope:`col`,className:`py-1.5 text-right font-normal`,children:`Status`})]})}),(0,$.jsx)(`tbody`,{className:`divide-y divide-default`,children:o.data.events.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`whitespace-nowrap py-1.5 pr-3 align-top text-label-13 tabular-nums text-secondary`,children:(0,$.jsx)(`time`,{dateTime:e.ts,children:new Date(e.ts).toLocaleTimeString(`en-US`,{hour:`numeric`,minute:`2-digit`,second:`2-digit`})})}),(0,$.jsxs)(`td`,{className:`break-all py-1.5 pr-3 align-top text-label-13-mono text-heading`,children:[Mp(e.method)&&(0,$.jsxs)(`span`,{className:`text-secondary`,children:[Mp(e.method),` `]}),(0,$.jsx)(`span`,{className:`text-secondary`,children:e.host??``}),e.path]}),o.data.scope.mode===`advanced`&&(0,$.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:wp[e.attribution]}),(0,$.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,$.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,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:o.data.offset===0||o.isFetching,onClick:()=>a(Math.max(0,o.data.offset-o.data.limit)),children:`Earlier requests`}),(0,$.jsx)(q,{variant:`outline`,size:`sm`,disabled:o.data.offset+o.data.limit>=o.data.totalEvents||o.isFetching,onClick:()=>a(o.data.offset+o.data.limit),children:`Later requests`})]})]})]})}function Qp({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,$.jsx)(`ul`,{className:`space-y-1 text-label-14`,children:[...n].map(([t,n])=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:Tp[t],children:Gs[t]}),(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`: `,[...n].map(t=>Ws(t,e)).join(` · `)]})]},t))})}function $p({context:e}){return(0,$.jsxs)(`div`,{className:`max-w-prose space-y-3`,children:[(0,$.jsxs)(`p`,{children:[Un(e.windowStart),` to `,Un(e.windowEnd),`. Agent visits are limited to this period.`]}),(0,$.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,$.jsxs)(`p`,{children:[`Property attribution uses URL matches in plan revision `,e.scope.planRevision,`.`]}),(0,$.jsx)(`p`,{children:`These requests do not show the person's task, market, tracked query, query class or model.`}),(0,$.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:e.coverage.limitations.map(e=>(0,$.jsx)(`li`,{children:e},e))}),e.coverage.cappedSourceDays.map(t=>(0,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-14-strong text-heading`,children:e.label}),(0,$.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:e.limitations.map(e=>(0,$.jsx)(`li`,{children:e},e))})]},e.sourceId))]})}var em=[`non-brand`,`branded`,`unclassified`],tm={"non-brand":`Non-brand`,branded:`Branded`,unclassified:`Unclassified`};function nm(e,t){return t<=0?`neutral`:e/t*100>=70?`positive`:`caution`}function rm(e,t){let n=[...new Set(e.byQuery.flatMap(e=>e.providers.map(e=>e.provider)))].sort(),r=new Map,i=e=>{let i=t(e)??`unclassified`,a=r.get(i);return a||(a={key:i,queries:0,unanswered:0,engines:n.map(e=>({provider:e,answered:0,mentioned:0,cited:0})),answers:0,competitorCited:0,competitorGaps:[],citedAndNamed:0,citedNotNamed:0,namedNotCited:0,neither:0},r.set(i,a)),a},a=new Map;for(let t of e.byQuery){let e=i(t.query);if(t.providers.length===0){e.unanswered++;continue}e.queries++;for(let n of t.providers){a.set(`${t.queryId}::${n.provider}`,t.query);let r=e.engines.find(e=>e.provider===n.provider);r.answered++,n.mentioned&&r.mentioned++,n.cited&&r.cited++,e.answers++}let n=t.providers.some(e=>e.cited),r=t.providers.some(e=>e.mentioned);n&&r?e.citedAndNamed++:n?e.citedNotNamed++:r?e.namedNotCited++:e.neither++}for(let t of e.competitorGaps){let e=a.get(`${t.queryId}::${t.provider}`);if(e===void 0)continue;let n=i(e);n.competitorCited++,n.competitorGaps.push({query:e,provider:t.provider,competitors:t.citingCompetitors})}return em.map(e=>r.get(e)).filter(e=>e!==void 0&&e.queries>0)}function im(e){let t=new Map(e.byQuery.map(e=>[e.queryId,e]));return e.competitorGaps.flatMap(e=>{let n=t.get(e.queryId);return n?.providers.some(t=>t.provider===e.provider)?[]:[{query:e.query,provider:e.provider,competitors:e.citingCompetitors,reason:n?`engine`:`query`}]})}var am={engine:`engine no longer configured`,query:`query no longer tracked`},om={"non-brand":`non-brand queries`,branded:`branded queries`,unclassified:`unclassified queries`},sm=`Each engine's latest answer to each query, spot checks left out. Mentioned: the answer names you. Cited: its sources link to your site. Competitor cited instead of you: answers that cite a tracked competitor's site and not yours.`;function cm(e,t,n){return e===1?t:n}function lm({projectName:e,classify:t,hasCompetitors:n,providerScores:r=[]}){let i=(0,Q.useId)(),[a,o]=(0,Q.useState)(`non-brand`),s=w({...fi({client:K,path:{name:e}}),staleTime:$n}),c=s.data??null,l=c?.status===`ready`?rm(c,t):[],u=l.find(e=>e.key===a)??l.at(0),d;s.isError?d=(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Could not load engine results: `,Bs(s.error)]}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{s.refetch()},children:`Retry`})]}):c?c.status===`no-data`?d=(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:c.reason===`no-queries`?`Add queries to start tracking AI citations.`:H()?Ba:`Engine results appear after the first AI Visibility check.`}):u||(d=(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No engine answers yet.`})):d=(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading engine results…`});let f=[];if(u&&c?.status===`ready`){let e=cm(u.queries,`query`,`queries`);f.push((0,$.jsxs)($.Fragment,{children:[`Cited and named: `,(0,$.jsxs)(`strong`,{children:[u.citedAndNamed,` of `,u.queries]}),` `,e]})),f.push((0,$.jsxs)($.Fragment,{children:[`Cited but not named: `,(0,$.jsxs)(`strong`,{children:[u.citedNotNamed,` of `,u.queries]}),` `,e]})),f.push((0,$.jsxs)($.Fragment,{children:[`Named but not cited: `,(0,$.jsxs)(`strong`,{children:[u.namedNotCited,` of `,u.queries]}),` `,e]})),f.push((0,$.jsxs)($.Fragment,{children:[`Not cited or named: `,(0,$.jsxs)(`strong`,{children:[u.neither,` of `,u.queries]}),` `,e]}));for(let t of u.engines)t.answered<u.queries&&f.push((0,$.jsxs)($.Fragment,{children:[oo(t.provider),`: answered `,(0,$.jsxs)(`strong`,{children:[t.answered,` of `,u.queries]}),` `,e]}));u.unanswered>0&&f.push((0,$.jsxs)($.Fragment,{children:[`No answers yet: `,(0,$.jsx)(`strong`,{children:u.unanswered}),` `,cm(u.unanswered,`query`,`queries`)]}));let{providersCiting:t,providersMentioning:n,providersConfigured:i}=c.summary;f.push((0,$.jsxs)($.Fragment,{children:[`All queries: cited by `,(0,$.jsxs)(`strong`,{children:[t,` of `,i]}),` `,cm(i,`engine`,`engines`),`, named by `,(0,$.jsxs)(`strong`,{children:[n,` of `,i]})]}));for(let e of r)f.push((0,$.jsxs)($.Fragment,{children:[oo(e.provider),e.model?` (${e.model})`:``,` citation rate:`,` `,(0,$.jsx)(`strong`,{children:St(e.score,ye.percent)}),`, `,(0,$.jsxs)(`strong`,{children:[e.cited,` of `,e.total]}),` `,cm(e.total,`answer`,`answers`),`, all queries`]}));for(let e of u.competitorGaps)f.push(`"${e.query}" (${oo(e.provider)}): ${e.competitors.join(`, `)} cited instead of you`);for(let e of im(c))f.push(`"${e.query}" (${oo(e.provider)}): ${e.competitors.join(`, `)} cited instead of you, not counted (${am[e.reason]})`)}let p=c?.status===`ready`?c.summary.latestRunAt:null,m=(e,t)=>u?.key===`non-brand`?wo[nm(e,t)]:`text-primary`;return(0,$.jsxs)(`section`,{className:`overview-brief`,"aria-labelledby":i,children:[(0,$.jsxs)(`div`,{className:`av-card-head`,children:[(0,$.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,$.jsx)(`h2`,{id:i,className:`av-card-title`,children:`By engine`}),u&&(0,$.jsx)(X,{text:sm})]}),p||u?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[p?(0,$.jsxs)(`p`,{className:`av-card-meta`,children:[`Latest run `,Un(p)]}):null,l.length>1?(0,$.jsx)(Io,{label:`Query type`,className:`flex-wrap`,options:l.map(e=>({value:e.key,label:tm[e.key]})),value:u.key,onChange:o}):u?(0,$.jsx)(`span`,{className:`mention-share-class`,children:tm[u.key]}):null]}):null]}),(0,$.jsx)(`div`,{className:`av-card-body`,children:d??(u&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`table`,{className:`av-grid av-grid-dense`,"aria-label":`By engine, ${om[u.key]}`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`th`,{scope:`col`,children:[`Of `,u.queries,` `,cm(u.queries,`query`,`queries`)]}),u.engines.map(e=>(0,$.jsx)(`th`,{scope:`col`,children:oo(e.provider)},e.provider))]})}),(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:`Mentioned`}),u.engines.map(e=>(0,$.jsx)(`td`,{children:(0,$.jsx)(`span`,{className:`av-n-sm ${m(e.mentioned,e.answered)}`,children:e.mentioned})},e.provider))]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label`,children:`Cited`}),u.engines.map(e=>(0,$.jsx)(`td`,{children:(0,$.jsx)(`span`,{className:`av-n-sm ${m(e.cited,e.answered)}`,children:e.cited})},e.provider))]})]})]}),(0,$.jsxs)(`p`,{className:`av-card-line`,children:[(0,$.jsx)(`span`,{className:`av-card-line-label`,children:`Competitor cited instead of you`}),n?(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`av-n-sm text-primary`,children:u.competitorCited}),` `,(0,$.jsxs)(`span`,{className:`av-of`,children:[`of `,u.answers,` `,cm(u.answers,`answer`,`answers`)]}),(0,$.jsxs)(`span`,{className:`sr-only`,children:[` · `,om[u.key]]})]}):(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:`No competitors tracked`})]})]}))}),(0,$.jsx)(dc,{items:f})]})}var um={[ze.queued]:{word:`queued`,tone:`text-secondary`},[ze.running]:{word:`running`,tone:`text-info-300`},[ze.completed]:{word:`completed`,tone:`text-secondary`},[ze.partial]:{word:`partial`,tone:`text-caution-400`},[ze.failed]:{word:`failed`,tone:`text-negative-400`},[ze.cancelled]:{word:`cancelled`,tone:`text-secondary`}};function dm({runs:e,projectName:t,collapsed:n=!1}){let r=(0,Q.useId)(),i=new Set(e.map(e=>e.location??``)).size>1,a=e.some(e=>e.kind!==ce[`answer-visibility`]),o=e.map(e=>`${e.startedAt}: ${e.summary}.${e.statusDetail?` ${e.statusDetail}`:``}`);return(0,$.jsx)(`section`,{className:`overview-brief`,"aria-labelledby":r,children:(0,$.jsxs)(`details`,{className:`av-history`,open:!n||void 0,children:[(0,$.jsxs)(`summary`,{className:`av-card-head`,children:[(0,$.jsx)(`h2`,{id:r,className:`av-card-title`,children:`Past checks`}),(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2`,children:[e.length>0?(0,$.jsxs)(`span`,{className:`av-card-meta`,children:[e.length,` recent`]}):null,(0,$.jsx)(c,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,$.jsx)(`div`,{className:`av-card-body`,children:e.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No checks yet.`}):(0,$.jsxs)(`table`,{className:`av-grid av-grid-dense av-grid-sweeps`,"aria-labelledby":r,children:[(0,$.jsx)(`thead`,{className:`sr-only`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Started`}),a?(0,$.jsx)(`th`,{scope:`col`,children:`Type`}):null,(0,$.jsx)(`th`,{scope:`col`,children:`Trigger`}),i?(0,$.jsx)(`th`,{scope:`col`,children:`Location`}):null,(0,$.jsx)(`th`,{scope:`col`,children:`Duration`}),(0,$.jsx)(`th`,{scope:`col`,children:`Status`})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>{let n=um[e.status],r=e.status===ze.partial||e.status===ze.failed;return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label tabular-nums`,children:(0,$.jsx)(Pa,{run:e,projectName:t,className:`av-link`,label:e.opensSeoWorkspace?`View SEO refresh from ${e.startedAt}`:`View the ${e.startedAt} check`,children:e.startedAt})}),a?(0,$.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.kindLabel}):null,(0,$.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.triggerLabel}),i?(0,$.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.location??`No location`}):null,(0,$.jsx)(`td`,{className:`text-label-13 text-secondary`,children:e.duration}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(`span`,{className:`av-status ${n.tone}`,children:n.word}),r&&e.statusDetail?(0,$.jsx)(`span`,{className:`ml-2 text-label-13 text-secondary`,children:e.statusDetail}):null]})]},e.id)})})]})}),(0,$.jsx)(dc,{items:o})]})})}var fm=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],pm=`Measured answers`,mm=`Close answers`,hm={"non-brand":`Non-brand queries`,branded:`Branded queries`,unknown:`Unclassified queries`},gm={"non-brand":`non-brand queries`,branded:`branded queries`,unknown:`unclassified queries`},_m={up:e=>`Up ${e} pts`,down:e=>`Down ${e} pts`,none:`No change`,previousUnavailable:`No earlier value`,comparedWith:e=>`vs ${e} check`,noPreviousRun:`No earlier check to compare`,definitionChanged:e=>e===null?`Not compared: setup changed`:`Not compared: setup changed since ${e}`,modelChanged:e=>e===null?`Not compared: engines or models changed`:`Not compared: engines or models changed since ${e}`,legacyUnknown:`Not compared: older check lacks comparison details`,partialRun:`Not compared: a check was incomplete`,scopedRun:`Not compared: this check covered part of the project`,explanation:`Change compares this check with the check before it when both completed and used the same setup, engines and models.`},vm={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.`,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.`},ym=`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: 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.`,bm=`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 xm(e){return e.kind===`project`?`Whole site`:e.kind===`group`?`${e.label} · Group`:e.kind===`market`?`${e.label} · Market`:e.label}function Sm(e){return e.reason===`identity-ambiguous`?jn.ambiguous:e.reason===`not-applicable`?`Not applicable`:`Not measured`}function Cm({value:e,signal:t}){if(e.rate===null)return(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:Sm(e)});let n=Fn(e,t);return(0,$.jsxs)(`span`,{className:`inline-flex flex-col gap-1`,children:[(0,$.jsx)(`strong`,{className:`tabular-nums text-heading`,children:St(e.rate)}),(0,$.jsxs)(`span`,{className:`text-label-14 tabular-nums text-secondary`,children:[e.numerator,` of `,e.denominator]}),n?(0,$.jsx)(`span`,{className:`-ml-2 flex`,children:(0,$.jsx)(X,{tone:`caution`,placement:`bottom`,label:n.label,text:n.text})}):null]})}function wm({value:e}){return e.rate===null?null:(0,$.jsx)(`span`,{className:`report-rate-bar`,"aria-hidden":`true`,children:(0,$.jsx)(`span`,{className:`report-rate-bar-fill progress-fill-neutral`,style:{width:`${e.rate*100}%`}})})}function Tm(e,t){if(!e||e.state===`unavailable`)return null;let n=e[t];if(n.state===`unavailable`)switch(n.reason){case lt[`previous-unavailable`]:return{text:_m.previousUnavailable,tone:`text-secondary`};case lt[`current-unavailable`]:case lt[`not-applicable`]:return null}let{direction:r,magnitude:i}=Kt(n.delta);switch(r){case`up`:return{text:_m.up(i),tone:`text-positive`};case`down`:return{text:_m.down(i),tone:`text-negative`};case`none`:return{text:_m.none,tone:`text-secondary`}}}function Em(e,t){let n=ha(e);return t!==null&&ma(n)===ma(ha(t))?ba(n):pa(n)}function Dm(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 Om(e,t){if(!e)return null;if(e.state===`unavailable`){let n=e.previousRun?Em(e.previousRun.createdAt,t):null;switch(e.reason){case De[`no-selected-run`]:return null;case De[`no-previous-run`]:return _m.noPreviousRun;case De[`definition-changed`]:return _m.definitionChanged(n);case De[`model-changed`]:return _m.modelChanged(n);case De[`legacy-unknown`]:return _m.legacyUnknown;case De[`partial-run`]:return _m.partialRun;case De[`scoped-run`]:return _m.scopedRun}}return _m.comparedWith(Em(e.previousRun.createdAt,t))}function km(e,t){let n=`${e.queryCount} ${e.queryCount===1?`query`:`queries`} · ${e.answerCount} ${e.answerCount===1?`answer`:`answers`}`;return t===null?n:`${n} · ${t}`}function Am({label:e,help:t,value:n,signal:r,unit:i,classNoun:a,change:o}){let s=(0,$.jsx)(`span`,{className:`sr-only`,children:` · ${a}`}),c=Fn(n,r);return(0,$.jsxs)(`div`,{className:`report-headline-tile`,children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1 text-label-14 text-secondary`,children:[(0,$.jsx)(`span`,{children:e}),(0,$.jsx)(X,{text:t})]}),n.rate===null?(0,$.jsxs)(`dd`,{className:`text-label-18 text-secondary`,children:[Sm(n),s]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dd`,{className:`report-headline-value`,children:[(0,$.jsx)(`span`,{className:`text-heading-32 tabular-nums text-heading`,children:St(n.rate)}),s,o?(0,$.jsx)(`span`,{className:`text-label-14 ${o.tone}`,children:o.text}):null]}),(0,$.jsx)(`dd`,{className:`text-label-14 tabular-nums text-secondary`,children:`${n.numerator} of ${n.denominator} ${i}`}),c?(0,$.jsx)(`dd`,{className:`-ml-2 flex`,children:(0,$.jsx)(X,{tone:`caution`,placement:`bottom`,label:c.label,text:c.text})}):null]})]})}var jm={otherQueries:`Other queries`},Mm={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 Nm(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(` · `)||jm.otherQueries;return r.sort((e,t)=>e.marketLabel.localeCompare(t.marketLabel)||e.query.localeCompare(t.query))}var Pm={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.`};function Fm({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?Pm.savedCite(r.citedAnswers,r.answers,r.citedTargetKeys.map(i).join(`, `)):Pm.savedCiteNone(e.targetKeys.length===1?i(e.targetKeys[0]):null);return(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:Pm.partlySaved(r.answers)}):null,(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:a})]})}function Im({value:e,signal:n,singleAnswer:r,row:i,targetLabels:a}){if(r&&e.denominator===1&&e.unattributed===void 0&&e.unchecked===void 0&&(e.rate===0||e.rate===1)){let n=e.rate===1;return(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-label-14 ${n?`text-positive`:`text-secondary`}`,children:[n?(0,$.jsx)(l,{size:16,"aria-hidden":`true`}):(0,$.jsx)(t,{size:16,"aria-hidden":`true`}),n?`Yes`:`No`]})}let o=n===`cited`&&i?.uncheckedSources?i:void 0;return(0,$.jsxs)(`span`,{className:`inline-flex items-start gap-1`,children:[(0,$.jsxs)(`span`,{className:`inline-flex flex-col gap-1`,children:[(0,$.jsx)(Cm,{value:e,signal:n}),o?(0,$.jsx)(Fm,{row:o,targetLabels:a??new Map,showCount:e.rate===null}):null]}),o?(0,$.jsx)(X,{text:Pm.help}):e.reason===`evidence-incomplete`?(0,$.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 Lm({targetKeys:e,labels:t}){return e.length===0?(0,$.jsx)(`span`,{children:`No assigned properties`}):e.length===1?(0,$.jsx)(`span`,{children:t.get(e[0])??e[0]}):(0,$.jsxs)(`details`,{children:[(0,$.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,$.jsx)(`ul`,{className:`max-h-48 space-y-2 overflow-y-auto pb-3`,children:e.map(e=>(0,$.jsx)(`li`,{children:t.get(e)??e},e))})]})}function Rm({group:e,queryClass:t,advanced:n,targetLabels:r,marketHeading:i,onViewAnswers:a}){let s=e.rows[0],c=e=>JSON.stringify([...e.targetKeys].sort()),l=e.rows.every(e=>c(e)===c(s)),u=e.rows.every(e=>e.location===s.location),d=e=>e===null?`No location requested`:`Requested search location: ${e}`;return(0,$.jsxs)(`tbody`,{"data-query-key":e.queryKey,children:[i?(0,$.jsx)(`tr`,{children:(0,$.jsx)(`th`,{colSpan:4,className:`border-t border-default py-4 text-left`,children:(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:i})})}):null,(0,$.jsx)(`tr`,{className:`measurement-result-heading`,children:(0,$.jsxs)(`th`,{scope:`rowgroup`,colSpan:4,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,$.jsx)(`h3`,{className:`break-words text-heading-16 text-heading`,children:e.query}),(0,$.jsx)(`div`,{className:`text-label-14`,children:(0,$.jsx)(Ea,{showLabel:!0,queryId:s.queryId,sourceSnapshotIds:e.rows.flatMap(e=>e.sourceSnapshotIds??[]),queryClass:t===`unknown`?null:t,location:u?s.location:void 0})})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-5 text-label-14 text-secondary`,children:[n&&l?(0,$.jsx)(Lm,{targetKeys:s.targetKeys,labels:r}):null,u?(0,$.jsx)(`span`,{children:d(s.location)}):null]})]})}),e.rows.map(e=>(0,$.jsxs)(`tr`,{className:`measurement-engine-result`,children:[(0,$.jsxs)(`td`,{className:`measurement-result-engine`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:oo(e.provider)}),(0,$.jsx)(`span`,{className:`block break-words text-label-14 text-secondary`,children:e.model??`Model not recorded`}),n&&!l?(0,$.jsx)(`div`,{className:`mt-1 text-label-14 text-secondary`,children:(0,$.jsx)(Lm,{targetKeys:e.targetKeys,labels:r})}):null,u?null:(0,$.jsx)(`span`,{className:`mt-1 block text-label-14 text-secondary`,children:d(e.location)}),(0,$.jsx)(Ma,{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,$.jsxs)(`td`,{children:[(0,$.jsx)(`span`,{className:`measurement-result-mobile-label`,"aria-hidden":`true`,children:`Mentioned`}),(0,$.jsx)(Im,{value:e.mentionCoverage,signal:`mentioned`,singleAnswer:e.answerCount===1})]}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(`span`,{className:`measurement-result-mobile-label`,"aria-hidden":`true`,children:`Cited`}),(0,$.jsx)(Im,{value:e.citationCoverage,signal:`cited`,singleAnswer:e.answerCount===1,row:e,targetLabels:r})]}),(0,$.jsx)(`td`,{className:`measurement-result-action`,children:(0,$.jsxs)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`View answers for ${e.query} · ${e.provider}`,onClick:t=>a(e,t.currentTarget),children:[e.answerCount===1?`View answer`:`View answers`,(0,$.jsx)(o,{size:16,"aria-hidden":`true`})]})})]},JSON.stringify([e.provider,e.model,e.location])))]})}var zm=`Cited counts only answers whose sources could be checked.`,Bm=[{key:`mentioned`,label:`Mentioned`,color:ua[1],dashed:!1},{key:`cited`,label:`Cited`,color:ya.positive,dashed:!0}],Vm=`var(--chart-tooltip-bg)`;function Hm({population:e}){let t=(0,Q.useId)(),[n,r]=(0,Q.useState)({mentioned:!0,cited:!0}),i=Bm.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?[`First measurement. A trend appears after another comparable run.`]:[],...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)?[zm]:[]];if(s.length===0)return(0,$.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);return(0,$.jsxs)($.Fragment,{children:[d?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`fieldset`,{className:`flex flex-wrap gap-x-5 py-1 text-label-14 text-secondary`,children:[(0,$.jsx)(`legend`,{className:`sr-only`,children:`Trend legend`}),Bm.map(e=>(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2`,children:[(0,$.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,$.jsxs)(`svg`,{"aria-hidden":`true`,className:`shrink-0`,width:`24`,height:`10`,viewBox:`0 0 24 10`,children:[(0,$.jsx)(`line`,{x1:`0`,y1:`5`,x2:`24`,y2:`5`,stroke:e.color,strokeWidth:`2`,strokeDasharray:e.dashed?`6 4`:void 0}),(0,$.jsx)(`circle`,{cx:`12`,cy:`5`,r:`3`,fill:e.dashed?Vm:e.color,stroke:e.color,strokeWidth:`2`})]}),e.label]},e.key))]}),u.length>0&&(0,$.jsx)(`p`,{id:t,className:`pb-3 text-copy-14 text-secondary`,children:u.join(` `)}),(0,$.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"data-visible-series":i.join(` `),"aria-describedby":u.length>0?t:void 0,"aria-label":`${hm[e.queryClass]} mention and citation trend`,children:(0,$.jsx)(I,{width:`100%`,height:`100%`,children:(0,$.jsxs)(te,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[(0,$.jsx)(M,{stroke:xa,vertical:!1}),(0,$.jsx)(P,{dataKey:`createdAt`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:va,tickLine:!1,axisLine:{stroke:Ca},tickFormatter:e=>new Date(Number(e)).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),minTickGap:24}),(0,$.jsx)(z,{domain:[0,1],tick:va,tickLine:!1,axisLine:!1,width:48,tickFormatter:e=>St(Number(e))}),(0,$.jsx)(N,{...Sa,formatter:e=>typeof e==`number`?St(e):`Not measured`,labelFormatter:e=>new Date(Number(e)).toLocaleDateString()}),c.map(e=>(0,$.jsxs)(Q.Fragment,{children:[n.mentioned?(0,$.jsx)(ee,{type:`linear`,dataKey:`mentioned-${e}`,name:`Mentioned`,stroke:ua[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:ua[1]}}):null,n.cited?(0,$.jsx)(ee,{type:`linear`,dataKey:`cited-${e}`,name:`Cited`,stroke:ya.positive,strokeWidth:2,strokeDasharray:`6 4`,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:Vm,strokeDasharray:`none`}}):null]},e))]})})})]}):(0,$.jsx)(`p`,{className:`py-6 text-copy-14 text-secondary`,children:`No measured trend for this selection.`}),(0,$.jsx)(`div`,{className:d?`sr-only`:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,"aria-label":`${hm[e.queryClass]} trend data`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Date`}),(0,$.jsx)(`th`,{children:`Mentioned`}),(0,$.jsx)(`th`,{children:`Cited`}),(0,$.jsx)(`th`,{children:`Comparison`})]})}),(0,$.jsx)(`tbody`,{children:e.trend.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:new Date(e.createdAt).toLocaleDateString()}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Cm,{value:e.mentionCoverage,signal:`mentioned`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Cm,{value:e.citationCoverage,signal:`cited`})}),(0,$.jsx)(`td`,{children:e.continuity.state.replaceAll(`-`,` `)})]},e.runId))})]})})]})}function Um(e,t){return t?e?.populations.find(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===t)):void 0}function Wm(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=Um(r,t)??Um(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 Gm={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: ${oo(e)}`,model:e=>`Model: ${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(` `)},Km={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},qm=`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 Jm(e,t){return e&&t?Gm.dateRange(e.slice(0,4)===t.slice(0,4)?wa(e):_a(e),_a(t)):e?Gm.dateFrom(_a(e)):t?Gm.dateThrough(_a(t)):null}function Ym(e,t){let n=[];e.provider&&n.push({key:`engine`,label:Gm.engine(e.provider),patch:{measurementProvider:void 0}}),e.model&&n.push({key:`model`,label:Gm.model(e.model),patch:{measurementModel:void 0}}),e.location&&n.push({key:`location`,label:e.location===`none`?Gm.noLocation:Gm.location(e.location),patch:{measurementLocation:void 0}});let r=Jm(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?Gm.resultsFrom(pa(ha(r.createdAt))):Gm.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Xm(e,t,n){return t===``||e.some(e=>e.value===t)?e:[...e,{value:t,label:n}]}function Zm({report:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,reportIsPlaceholder:s=!1}){let[c,l]=(0,Q.useState)(!1),u=(0,Q.useRef)(null),d=(0,Q.useId)(),f=`${d}-filters`,{filterOptions:p,selection:m}=e,g=m.measurement,_=Wm(e,t.queryKey,t.answer),v=t.queryClass===`all`?_.queryClass:t.queryClass,y=Ym(t,e),b=t.measurementScope===`property`?t.measurementScopeKey:void 0,x=b?i?.({id:b,label:ec(e.scopeOptions,t)?.label??b}):null,S=t.provider??``,C=t.model??``,w=t.location??``,T=t.measurementRunId??``,E=!s&&g.awaitingSweep&&g.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,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`mb-1 flex items-center gap-1`,children:[(0,$.jsx)(`label`,{htmlFor:`${d}-${t}`,className:`text-label-14-strong text-heading`,children:e}),a?(0,$.jsx)(X,{text:a}):null]}),(0,$.jsx)(`select`,{id:`${d}-${t}`,className:bm,value:r,onChange:e=>n({[t]:e.target.value||void 0,measurementQueryKey:void 0}),children:i.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),k=(e,t,r,i)=>(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`label`,{htmlFor:`${d}-${t}`,className:`mb-1 block text-label-14-strong text-heading`,children:e}),(0,$.jsx)(`input`,{id:`${d}-${t}`,type:`date`,className:bm,value:r?.slice(0,10)??``,onChange:e=>n({[t]:e.target.value?`${e.target.value}${i}`:void 0})})]});return(0,$.jsxs)(`div`,{className:`visibility-filter-container`,children:[(0,$.jsxs)(`div`,{className:`visibility-results-toolbar`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-x-4 gap-y-2`,children:[(0,$.jsxs)(`label`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:Gm.queryType}),(0,$.jsxs)(`select`,{"aria-label":Gm.queryType,className:qm,value:v,onChange:e=>n({queryClass:e.target.value,measurementQueryKey:void 0}),children:[(0,$.jsx)(`option`,{value:`non-brand`,children:`Non-brand`}),(0,$.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,$.jsx)(`option`,{value:`unknown`,children:`Unclassified`})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(J,{tone:g.state===`measured`?`positive`:`neutral`,children:g.state===`measured`?`Complete`:g.state===`partial`?`Partial`:`Not measured`}),g.completedAt?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:pa(ha(g.completedAt))}):null]})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{ref:u,type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,"aria-expanded":c,"aria-controls":f,onClick:()=>l(e=>!e),children:Gm.filters(y.length)}),y.map(e=>(0,$.jsxs)(q,{type:`button`,variant:`outline`,className:`visibility-filter-token pointer-coarse:min-h-11 rounded-md text-button-14`,"aria-label":Gm.removeFilter(e.label),onClick:()=>{n(e.patch),D()},children:[(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label}),(0,$.jsx)(h,{size:16,className:`shrink-0`,"aria-hidden":`true`})]},e.key)),x,r?(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:r,children:Gm.manageQueries}):null]})]}),(0,$.jsxs)(`div`,{id:f,role:`group`,"aria-label":Gm.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,$.jsxs)(`div`,{className:`visibility-report-filters`,children:[O(`Answer engine`,`measurementProvider`,S,Xm([{value:``,label:`All engines`},...p.providers.map(e=>({value:e,label:oo(e)}))],S,oo(S))),O(`Requested search location`,`measurementLocation`,w,Xm([{value:``,label:`All requested locations`},...p.locations.flatMap(e=>e.kind===`exact`?[{value:e.value,label:e.value}]:e.kind===`none`?[{value:`none`,label:Gm.noLocation}]:[])],w,w===`none`?Gm.noLocation:w)),O(`AI model`,`measurementModel`,C,Xm([{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}))],C,C),`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,Xm([{value:``,label:`Latest saved check`},...[..._.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,$.jsx)(`div`,{className:`flex justify-end pb-3`,children:(0,$.jsx)(q,{type:`button`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:y.length===0,onClick:()=>{n({...Km}),D()},children:Gm.clearFilters})})]}),E?(0,$.jsx)(`p`,{role:`status`,className:`border-b border-default py-3 text-copy-14 text-secondary`,children:Gm.trackingChanged(a?ba(ha(a)):null,g.completedAt?ba(ha(g.completedAt)):null,o??null)}):null]})}function Qm({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,Q.useRef)(null),m=(0,Q.useRef)(void 0),h=(0,Q.useRef)(null),g=Wm(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,Q.useEffect)(()=>{if(!b){t||(m.current=void 0);return}if(m.current===b)return;let e=p.current?.querySelectorAll(`[aria-label="${pm}"]`);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=xm(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,$.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,$.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,$.jsx)(`p`,{children:`These saved results aren't separated by query type.`}),(0,$.jsx)(q,{variant:`outline`,onClick:()=>n({queryClass:`all`,measurementQueryKey:void 0}),children:`View all saved results`})]}):null,[g].map(t=>{let s=Nm(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=gm[t.queryClass],_=Om(t.comparison,Dm(x,t));return(0,$.jsxs)(`section`,{"aria-label":hm[t.queryClass],className:`py-4`,children:[(0,$.jsxs)(`div`,{className:`section-head flex-wrap items-center`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`h2`,{children:hm[t.queryClass]}),(0,$.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,$.jsxs)(`div`,{className:`report-headline-caption`,children:[(0,$.jsx)(`span`,{className:`tabular-nums`,children:km(t.summary,_)}),(0,$.jsx)(X,{text:_m.explanation})]})]}),(0,$.jsxs)(`dl`,{className:`report-headline mt-3`,"data-columns":m?3:2,"aria-label":`${hm[t.queryClass]} headline results`,children:[(0,$.jsx)(Am,{label:m?`Answers mentioning a property`:`Mentioned answers`,help:x.mode===`advanced`?vm.advancedMention:vm.simpleMention,value:t.summary.mentionCoverage,signal:`mentioned`,unit:`answers`,classNoun:g,change:Tm(t.comparison,`mentionCoverage`)}),(0,$.jsx)(Am,{label:m?`Answers citing a property`:`Cited answers`,help:x.mode===`advanced`?vm.advancedCitation:vm.simpleCitation,value:t.summary.citationCoverage,signal:`cited`,unit:`answers`,classNoun:g,change:Tm(t.comparison,`citationCoverage`)}),m?(0,$.jsx)(Am,{label:`Properties mentioned`,help:vm.propertyReach,value:t.summary.propertyReach,signal:`mentioned`,unit:`properties`,classNoun:g,change:Tm(t.comparison,`propertyReach`)}):null]}),(0,$.jsx)(Bo,{queryClass:x.queryClass,manage:!0}),(0,$.jsx)(Hm,{population:t}),m&&(t.breakdown.groups.length>0||t.breakdown.properties.length>0)?(0,$.jsx)($m,{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,$.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":`${hm[t.queryClass]} property outcomes`,children:[(0,$.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,$.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Property outcomes`}),(0,$.jsxs)(`span`,{className:`visibility-disclosure-meta`,children:[t.summary.outcomes.total,` `,t.summary.outcomes.total===1?`property`:`properties`]})]}),(0,$.jsxs)(`div`,{className:`visibility-disclosure-panel flex flex-wrap items-start justify-between gap-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{className:`block tabular-nums text-heading`,children:t.summary.outcomes[e]}),(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:n})]},e))}),t.summary.notMeasuredUnchecked?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:Pm.outcomes(t.summary.notMeasuredUnchecked)}):null]}),(0,$.jsx)(X,{text:ym})]})]}):null,(0,$.jsxs)(`details`,{className:`visibility-disclosure`,"data-query-results":t.queryClass,"aria-label":`${hm[t.queryClass]} query results`,children:[(0,$.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,$.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Query results`}),(0,$.jsxs)(`span`,{className:`visibility-disclosure-meta`,children:[t.queries.total,` `,t.queries.total===1?`result`:`results`,` · `,S]})]}),(0,$.jsxs)(`div`,{className:`visibility-disclosure-panel`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-3`,children:[i?(0,$.jsx)(`input`,{type:`search`,"aria-label":`Search ${hm[t.queryClass]}`,placeholder:`Search queries`,className:`${bm} max-w-sm`,value:a,onChange:e=>i(e.target.value)}):null,(0,$.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,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table measurement-responsive-table measurement-results-table`,"aria-label":`${hm[t.queryClass]} engine results`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Answer engine`}),(0,$.jsx)(`th`,{scope:`col`,children:`Mentioned`}),(0,$.jsx)(`th`,{scope:`col`,children:`Cited`}),(0,$.jsx)(`th`,{scope:`col`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Evidence`})})]})}),s.map((e,r)=>(0,$.jsx)(Rm,{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,$.jsx)(`p`,{className:`py-4 text-copy-14 text-secondary`,children:`No measured queries match this selection.`}):(0,$.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,$.jsx)(q,{variant:`outline`,onClick:()=>r(t.queries.nextCursor),children:`Next queries`}):null,o&&y.includes(t.queryClass)?(0,$.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":pm,"aria-busy":l,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,$.jsx)(`h3`,{className:`min-w-0 flex-1 text-heading-16 text-heading [overflow-wrap:anywhere]`,children:p??`Answers`}),(0,$.jsx)(q,{variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:T,children:mm})]}),l?(0,$.jsx)(`p`,{role:`status`,className:`py-4 text-copy-14 text-secondary`,children:`Loading saved answers…`}):u?(0,$.jsxs)(`div`,{role:`alert`,className:`py-4 text-label-14 text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`Saved answers unavailable: `,u]}),d?(0,$.jsx)(q,{variant:`outline`,onClick:d,children:`Retry answers`}):null]}):(0,$.jsxs)($.Fragment,{children:[c.items.map(e=>(0,$.jsxs)(`article`,{className:`border-b border-default py-4`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-2`,children:[(0,$.jsx)(`strong`,{className:`text-label-14 text-heading`,children:oo(e.provider)}),e.model?(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.model}):null,(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:e.location===null?Gm.noLocation:Gm.location(e.location)}),(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:new Date(e.createdAt).toLocaleDateString()}),(0,$.jsx)(J,{tone:`neutral`,children:e.mentioned===null?e.mentionUnavailableReason===`identity-ambiguous`?jn.ambiguous:`Mention not checked`:e.mentioned?`Mentioned`:`Not mentioned`}),(0,$.jsx)(J,{tone:`neutral`,children:e.cited===null?`Citation not checked`:e.cited?`Cited`:`Not cited`})]}),(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(Ja,{headingLevel:4,copyable:!!e.answerText?.trim(),children:e.answerText??`Answer text unavailable.`})}),e.sources.length>0?(0,$.jsxs)(`details`,{className:`mt-2`,"data-answer-sources":!0,children:[(0,$.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:[Ha,` (`,e.sources.length,`)`]}),(0,$.jsx)(`ul`,{className:`space-y-2 pb-3`,children:e.sources.map(e=>(0,$.jsx)(`li`,{className:`min-w-0`,children:(0,$.jsx)(Jo,{url:e})},e))})]}):null]},e.answerId)),w(t).items.length===0?(0,$.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,$.jsx)(q,{variant:`outline`,onClick:()=>f(w(t).nextCursor),children:`Next answers`}):null]})]}):null]})]}),(0,$.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":`${hm[t.queryClass]} competitors`,children:[(0,$.jsxs)(`summary`,{className:`visibility-disclosure-summary`,children:[(0,$.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Competitors`}),(0,$.jsx)(`span`,{className:`visibility-disclosure-meta`,children:t.competitorAvailability.state===`unavailable`?`Not available`:`${t.competitors.length} measured`})]}),(0,$.jsxs)(`div`,{className:`visibility-disclosure-panel`,children:[t.competitorAvailability.state===`unavailable`?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Competitor rates unavailable for this historical definition.`}):t.competitors.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No measured competitors in this selection.`}):(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Competitor`}),(0,$.jsx)(`th`,{children:`Mentioned`}),(0,$.jsx)(`th`,{children:`Cited`})]})}),(0,$.jsx)(`tbody`,{children:t.competitors.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:e.domain}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Cm,{value:e.mentionCoverage,signal:`mentioned`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Cm,{value:e.citationCoverage,signal:`cited`})})]},e.domain))})]})}),t.observedCompetitors.length>0?(0,$.jsxs)(`details`,{className:`mt-4 text-label-14`,children:[(0,$.jsx)(`summary`,{className:`min-h-11 cursor-pointer py-3 text-heading`,children:`Other names in answers`}),(0,$.jsx)(`ul`,{className:`divide-y divide-default`,children:t.observedCompetitors.map(e=>(0,$.jsxs)(`li`,{className:`flex items-center justify-between gap-4 py-3`,children:[(0,$.jsx)(`span`,{children:e.name}),(0,$.jsxs)(`span`,{className:`tabular-nums text-secondary`,children:[e.answerCount,` `,e.answerCount===1?`answer`:`answers`]})]},e.name))}),(0,$.jsx)(`p`,{className:`py-2 text-secondary`,children:`Observed names, not additions to your tracked competitors.`})]}):null]})]})]},t.queryClass)})]})}function $m({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,Q.useState)(()=>t.kind===`project`&&s.length>0?`groups`:`properties`),u=ws({rows:c===`groups`?s:e.breakdown.properties,getSearchText:e=>e.label});return(0,$.jsxs)(`section`,{className:`border-t border-default py-5`,"aria-label":`Scope breakdown`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3`,children:[(0,$.jsx)(`div`,{className:`flex gap-2`,children:[`groups`,`properties`].map(e=>(0,$.jsx)(q,{variant:c===e?`secondary`:`ghost`,onClick:()=>{l(e),u.setPage(1)},children:e===`groups`?`Groups`:`Properties`},e))}),(0,$.jsx)(`input`,{type:`search`,"aria-label":`Search breakdown`,placeholder:`Search`,value:u.query,onChange:e=>u.setQuery(e.target.value),className:`${bm} max-w-sm`})]}),(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:c===`groups`?`Group`:`Property`}),(0,$.jsx)(`th`,{children:`Queries`}),(0,$.jsx)(`th`,{children:`Mentioned`}),(0,$.jsx)(`th`,{children:`Cited`})]})}),(0,$.jsx)(`tbody`,{children:u.rows.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.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,$.jsx)(`td`,{children:e.queryCount}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(Cm,{value:e.mentionCoverage,signal:`mentioned`}),(0,$.jsx)(wm,{value:e.mentionCoverage})]}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(Cm,{value:e.citationCoverage,signal:`cited`}),(0,$.jsx)(wm,{value:e.citationCoverage})]})]},e.id))})]})}),u.rows.length===0?(0,$.jsxs)(`p`,{className:`py-3 text-copy-14 text-secondary`,children:[`No `,c,` match this search.`]}):null,(0,$.jsx)(Ss,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function eh(e,t,{enabled:n}){return w({...gi({client:K,path:{name:e},query:yo(t)}),enabled:n,staleTime:tr,retry:!1,placeholderData:j})}function th(e,t){return t&&e.selection.mode===`simple`&&e.selection.measurement.state===`not-measured`}function nh({projectName:e,selection:t,onSelectionChange:n,fallback:r,showUnmeasuredFallback:i=!1}){let[a,o]=(0,Q.useState)(),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(),d=S(),f=(0,Q.useMemo)(()=>({scope:t.measurementScope,scopeKey:t.measurementScopeKey,marketKey:t.marketKey,queryClass:t.queryClass,provider:t.provider,model:t.model,location:t.location,from:t.from,to:t.to,revision:t.revision,runId:t.measurementRunId}),[t.measurementScope,t.measurementScopeKey,t.marketKey,t.queryClass,t.provider,t.model,t.location,t.from,t.to,t.revision,t.measurementRunId]),p=w({...gi({client:K,path:{name:e},query:{...yo(t),cursor:a,search:s||void 0}}),staleTime:tr,retry:!1,placeholderData:j}),m={...f,queryKey:t.queryKey,queryClass:t.answer?.queryClass??t.queryClass,provider:t.answer?.provider??t.provider,model:t.answer?t.answer.model??void 0:t.model,location:t.answer?t.answer.location??`none`:t.location,runId:t.answer?.runId??p.data?.selection.run.id??t.measurementRunId,revision:t.answer?.revision??p.data?.selection.revision??t.revision,limit:50},h=JSON.stringify(m),g=w({...gi({client:K,path:{name:e},query:{...m,cursor:l?.selection===h?l.cursor:void 0}}),enabled:!!t.queryKey&&!!p.data&&!p.isPlaceholderData,retry:!1});if((0,Q.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&&!Um(p.data,t.queryKey)&&!g.data)return;let r=Wm(p.data,t.queryKey,t.answer,g.data);if(!a&&!s){let{queryKey:n}=gi({client:K,path:{name:e},query:yo({...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&&th(p.data,i))return(0,$.jsx)($.Fragment,{children:r});if(p.error){let e=ft(xt(p.error)),t=e?.reason===ot[`retired-market`];return(0,$.jsxs)(`section`,{className:`page-section-divider`,role:`alert`,children:[(0,$.jsx)(`h2`,{children:`AI visibility unavailable`}),(0,$.jsx)(`p`,{className:`my-3 text-copy-14 text-secondary`,children:t?Mm.retiredMarket:e?Mm.retiredScope:Te(p.error)}),t?(0,$.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementMarketKey:void 0})},children:Mm.showAllMarkets}):e?(0,$.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),n({measurementScope:`project`,measurementScopeKey:void 0})},children:Mm.showWholeSite}):(0,$.jsx)(q,{variant:`outline`,onClick:()=>{o(void 0),p.refetch()},children:`Retry`})]})}return p.data?(0,$.jsx)(`div`,{"aria-busy":p.isFetching,children:(0,$.jsx)(Qm,{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?Te(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,$.jsx)(`section`,{className:`page-section-divider`,role:`status`,"aria-label":`Loading AI visibility`,children:(0,$.jsx)(`div`,{className:`h-64 animate-pulse rounded-md bg-surface`})})}function rh({projectName:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,fallback:s,showUnmeasuredFallback:c=!1}){let l=eh(e,t,{enabled:!0}),u=l.error?void 0:l.data,d=!l.isPlaceholderData&&u?.selection.availability.state===`available`?u.selection.run.id:null;Qa(d,null);let f=!(!u||u.selection.availability.state!==`available`||th(u,c));return(0,$.jsxs)($.Fragment,{children:[f?(0,$.jsx)(Zm,{report:u,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,reportIsPlaceholder:l.isPlaceholderData}):null,!f&&(u||l.error)?(0,$.jsx)(`div`,{className:`mb-3 flex justify-end`,children:(0,$.jsx)(eo,{})}):null,(0,$.jsx)(nh,{projectName:e,selection:t,onSelectionChange:n,fallback:s,showUnmeasuredFallback:c},`${e}:${JSON.stringify({...t,queryKey:void 0,answer:void 0})}`)]})}var ih=[{value:`byProvider`,label:`By engine`},{value:`overall`,label:`All engines`}],ah=[{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.`}],oh=[{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.`}],sh=ua[2],ch=ua[4],lh=`var(--chart-tooltip-bg)`,uh={up:`text-positive-400`,down:`text-negative-400`,none:`text-muted`};function dh({direction:e,magnitude:t}){switch(e){case`up`:return`up ${t} points`;case`down`:return`down ${t} points`;case`none`:return`no change`}}function fh(e){return e.direction===`none`?`no change over the period`:`${dh(e)} over the period`}function ph(e){return e===`__cited__`||e===`__mentioned__`||e===`__mentionShare__`}function mh(e){return e===`__cited__`?`Cited`:e===`__mentioned__`?`Mentioned`:e===`__mentionShare__`?`Mention share`:oo(e)}function hh(e,t){return e===`__cited__`?ya.positive:e===`__mentioned__`?ua[1]:e===`__mentionShare__`?sh:la(ro(e),t)}function gh(e){return e===`non-brand`?`non-brand answers`:`all answers`}function _h(e){return e===`cited`?`Cited`:e===`mentionShare`?`Mention share`:`Mentioned`}function vh(e,t){return e===`mentionShare`?`Mention share in ${gh(t)}`:_h(e)}function yh(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`}.`}function bh(e){return e===`cited`?`citationRate`:`mentionRate`}function xh(e,t){return t===`cited`?e.cited:e.mentionedCount}function Sh(e,t,n){let r=e.byProvider[t];return r?{count:n===`cited`?r.cited:r.mentionedCount,total:r.total,rate:n===`cited`?r.citationRate:r.mentionRate}:null}function Ch(e,t){if(t===`mentionShare`){let{projectMentionSnapshots:t,competitorMentionSnapshots:n}=e.mentionShare;return`${t} of ${t+n} tracked-brand mentions`}return`${xh(e,t)} of ${e.total} answers`}function wh(e,t){if(t===void 0)return null;let n=String(t);return e.find(e=>e.startDate===n)??null}function Th(e){let t=uo(e);return t===null?[]:Object.entries(t).sort(([e],[t])=>ro(e).localeCompare(ro(t))).map(([e,t])=>`${oo(e)}: ${Na(t)}`)}function Eh(e,t){return new Date(e).toDateString()===new Date(t).toDateString()}function Dh(e){return`${e} ${e===1?`query`:`queries`}`}function Oh(e){let{added:t,removed:n}=e;return[...t.length>0?[`${Dh(t.length)} added`]:[],...n.length>0?[`${t.length>0?n.length:Dh(n.length)} removed`]:[]].join(`, `)}function kh(e,t){let n=mo(e),r=co(e),i=Ya(e,t);if(!n||!r||!i)return null;let a=ka(i.moves),o=Eh(n.start,n.end),s=e=>Un(e,o?n.start:null);return n.sweepCount===2?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:r}),` point mixes the `,(0,$.jsx)(`strong`,{children:s(n.start)}),` check and the `,(0,$.jsx)(`strong`,{children:s(n.end)}),` check, with `,a,` between them`]}):i.moves.added.length+i.moves.removed.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:r}),` point mixes checks with `,a,` between them`]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:r}),` point pools `,(0,$.jsx)(`strong`,{children:n.sweepCount}),` checks, with `,a,` between the first and last`]})}function Ah(e,t,n){let r=kh(t,n);return r?(0,$.jsxs)($.Fragment,{children:[`Not the same queries: `,r]}):e.changes.length>0?(0,$.jsxs)($.Fragment,{children:[`Not the same queries: `,e.changes.map((e,t)=>(0,$.jsxs)(Q.Fragment,{children:[t>0?`, `:``,Oh(e),` `,(0,$.jsx)(`strong`,{children:to(ha(e.at))})]},e.at)),`; first and latest points cover different queries`]}):(0,$.jsxs)($.Fragment,{children:[`Not the same queries: first and latest points have answers for `,(0,$.jsx)(`strong`,{children:e.firstCount}),` and `,(0,$.jsx)(`strong`,{children:e.latestCount}),` queries`]})}var jh=`Queries changed`;function Mh(e){let t=ka(e.moves);return t?`${jh}: ${t} between the first and latest points, so the change compares different queries.`:`${jh}: the first and latest points have answers for ${e.firstCount} and ${e.latestCount} queries, so the change compares different queries.`}function Nh(e){return e.replace(/ /g,`\xA0`)}function Ph({state:e,from:t=!1}){return(0,$.jsx)(`span`,{className:t?`av-model av-model-from`:`av-model`,children:Na(e)})}function Fh(e,t){return e.reroute?`Same preset, answered with a different model.`:Vo(e.provider,e.to)?e.served?`Preset picks its own model. Answered with ${Na(e.served.to)} (was ${Na(e.served.from)}).`:t&&t.length>0?`Preset picks its own model. Answered with ${t.join(`, `)}.`:`Preset picks its own model.`:null}function Ih({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=>to(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,$.jsx)(`span`,{className:`text-strong`,children:Oh(e)}),toHelp:null}))});let p=[...new Set(n.map(e=>e.provider))].sort((e,t)=>oo(e).localeCompare(oo(t)));for(let e of p){let t=r[e]?.latestServedModelIds??null,a=n.filter(t=>t.provider===e);f.push({key:e,label:oo(e),rows:a.map((n,r)=>{let a=d.get(e)===n?i.get(e).text:null,o=[Fh(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,$.jsx)(Ph,{state:n.from,from:!0}),to:(0,$.jsx)(Ph,{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,$.jsxs)($.Fragment,{children:[`Added `,(0,$.jsx)(`strong`,{children:u(e.at)}),`: `,e.added.map(s).join(`, `)]})),e.removed.length>0&&h.push((0,$.jsxs)($.Fragment,{children:[`Removed `,(0,$.jsx)(`strong`,{children:u(e.at)}),`: `,e.removed.map(s).join(`, `)]}));let g=l?co(l):null;for(let[e,t]of Object.entries(l?uo(l)??{}:{}).sort(([e],[t])=>e.localeCompare(t)))t.status===`mixed`&&g&&h.push((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:g}),` point mixes `,oo(e),` models: `,Fa(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)??[],oo(e.provider)])])}for(let[e,t]of _)h.push(e?(0,$.jsxs)($.Fragment,{children:[`Changed before this date range, after the `,(0,$.jsx)(`strong`,{children:e}),` check: `,Da(t)]}):`Changed before this date range: ${Da(t)}`);for(let e of a)h.push(`${oo(e.provider)}: most recent ${e.shown} of ${e.total} changes`);for(let e of o)h.push(`${oo(e)}: may be missing older changes`);for(let[e,t]of i)d.has(e)||h.push((0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[oo(e),`: no model updates on record`,(0,$.jsx)(X,{text:t.text})]}));if(m===0&&h.length===0)return null;for(let[e,t]of Object.entries(r).sort(([e],[t])=>oo(e).localeCompare(oo(t)))){let n=t.latestServedModelIds??[],r=n.length>0?n.join(`, `):Na(t.latestObservation.state);h.push((0,$.jsxs)($.Fragment,{children:[oo(e),` last answered with `,(0,$.jsx)(`strong`,{children:r}),` on `,(0,$.jsx)(`strong`,{children:u(ha(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=>Un(e,e));y+=` ${t} = the ${Da(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=bo(r[0],c,e,o);s&&(y+=` Check before: ${u(s)}.`)}let b=Ta({latest:l,queryChanges:t,modelRows:n})??`No changes in this date range`;return(0,$.jsxs)(`details`,{className:`av-wc`,children:[(0,$.jsxs)(`summary`,{children:[(0,$.jsx)(`span`,{className:`av-card-title`,children:`What changed`}),(0,$.jsx)(`span`,{className:`av-wc-summary av-wc-when-closed`,children:b}),(0,$.jsxs)(`span`,{className:`av-wc-toggle`,children:[(0,$.jsxs)(`span`,{className:`av-wc-when-closed`,children:[m>0?`Show all ${m}`:`Details`,` `,(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`▸`})]}),(0,$.jsxs)(`span`,{className:`av-wc-when-open`,children:[`Hide `,(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`▴`})]})]})]}),(0,$.jsx)(`div`,{className:`av-wc-body`,children:m>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`av-change-table`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Query and model changes, newest first`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Changed`})}),(0,$.jsx)(`th`,{scope:`col`,"aria-label":`Date`,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[`Date`,(0,$.jsx)(X,{text:y})]})}),(0,$.jsx)(`th`,{scope:`col`,children:`From`}),(0,$.jsx)(`th`,{scope:`col`,children:`To`})]})}),f.map(e=>(0,$.jsx)(`tbody`,{children:e.rows.map((t,n)=>(0,$.jsxs)(`tr`,{children:[n===0?(0,$.jsx)(`th`,{scope:`row`,className:`av-engine`,children:e.label}):(0,$.jsx)(`td`,{className:`av-engine`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:e.label})}),(0,$.jsx)(`td`,{className:`av-date`,children:t.onOrBefore?`on or before ${Nh(u(t.at))}`:Nh(u(t.at))}),t.from===null?null:(0,$.jsx)(`td`,{children:t.from}),(0,$.jsx)(`td`,{colSpan:t.from===null?2:void 0,children:(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[t.to,t.toHelp?(0,$.jsx)(X,{text:t.toHelp}):null]})})]},t.key))},e.key))]})}),(0,$.jsx)(dc,{items:h})]}):(0,$.jsx)(`ul`,{className:`av-details-list`,children:h.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})})]})}function Lh({substitutions:e}){return e.length===0?null:(0,$.jsx)(`ul`,{className:`space-y-3`,"aria-label":`Model substitutions`,children:e.map(({provider:e,mismatch:t})=>(0,$.jsxs)(`li`,{className:`av-amber-row border border-caution-800/60 bg-caution-950/20`,children:[(0,$.jsx)(`span`,{className:`av-engine`,children:oo(e)}),(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`selected `,(0,$.jsx)(Ph,{state:t.configured}),` · answered `,(0,$.jsx)(Ph,{state:t.served})]}),(0,$.jsx)(`span`,{className:`av-status text-caution-400`,children:`substituted`})]},e))})}function Rh({active:e,label:t,payload:n,metric:r,mode:i,buckets:a,basketChanges:o}){if(!e)return null;let s=wh(a,t);if(!s)return null;let c=mo(s),l=c!==null&&Eh(c.start,c.end)?c.start:null,u=Do(s,o),d=Th(s),f=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`trend-tooltip-label`,children:ja(s)}),u.map(e=>(0,$.jsxs)(`p`,{className:`trend-tooltip-detail trend-tooltip-note`,children:[Oh(e),` `,Un(e.at,l)]},e.at))]}),p=d.length>0&&(0,$.jsx)(`p`,{className:`trend-tooltip-detail trend-tooltip-models`,children:d.map((e,t)=>(0,$.jsxs)(Q.Fragment,{children:[t>0?`; `:``,(0,$.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,$.jsxs)(`div`,{className:`trend-tooltip`,children:[f,(0,$.jsxs)(`div`,{className:`trend-tooltip-row`,children:[(0,$.jsx)(`span`,{className:`trend-tooltip-swatch trend-tooltip-swatch-ring`,style:{borderColor:sh},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`trend-tooltip-name`,children:vh(`mentionShare`,s.mentionShare.scope)}),(0,$.jsx)(`span`,{className:`trend-tooltip-value`,children:St(s.mentionShare.rate)})]}),(0,$.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`?So:ls}];return(0,$.jsxs)(`div`,{className:`trend-tooltip`,children:[f,m.map((e,t)=>{let n=String(e.dataKey??e.name??``),a=i===`byProvider`?Sh(s,n,r):null,o=a?.count??xh(s,r),c=a?.total??s.total,l=a?a.rate:s[bh(r)],u=e.color??hh(n,t);return(0,$.jsx)(`div`,{className:`trend-tooltip-block`,children:(0,$.jsxs)(`div`,{className:`trend-tooltip-row`,children:[(0,$.jsx)(`span`,{className:`trend-tooltip-swatch`,style:{backgroundColor:u},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`trend-tooltip-name`,children:mh(n)}),(0,$.jsx)(`span`,{className:`trend-tooltip-value`,children:St(l)}),(0,$.jsxs)(`span`,{className:`trend-tooltip-count`,children:[o,` of `,c]})]})},`${n}-${t}`)}),p]})}function zh({buckets:e,metric:t,mode:n,series:r,mentionShareScope:i}){return(0,$.jsx)(`div`,{className:`sr-only`,children:(0,$.jsxs)(`table`,{children:[(0,$.jsxs)(`caption`,{children:[vh(t,i),` trend data`]}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Point`}),(0,$.jsx)(`th`,{scope:`col`,children:`Values`})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>{let i;if(t===`mentionShare`){let t=e.mentionShare.projectMentionSnapshots,n=t+e.mentionShare.competitorMentionSnapshots,r=gh(e.mentionShare.scope);i=n>0?`${St(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=Sh(e,n,t);return r?`${oo(n)} ${St(r.rate)} ${_h(t).toLowerCase()}, ${r.count} of ${r.total} answers`:`${oo(n)} no data`}).join(`; `):`${St(e[bh(t)])} ${_h(t).toLowerCase()}, ${xh(e,t)} of ${e.total} answers`;let a=Th(e);return a.length>0&&(i+=`; models: ${a.join(`; `)}`),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,children:ja(e)}),(0,$.jsx)(`td`,{children:i})]},e.startDate)})})]})})}function Bh({projectName:e,competitorDomains:t=[],competitorAliases:n,analyticsRevision:r=`none`,queryTexts:i=[],classifyQuery:a,sweepTimes:o=[],queryClassSplit:s=!1}){let[c,l]=(0,Q.useState)(`all`),[u,d]=(0,Q.useState)(`mentioned`),[f,p]=(0,Q.useState)(`non-brand`),m=s&&u!==`mentionShare`,h=m?f:`all`,[g,_]=(0,Q.useState)(`byProvider`),v=(0,Q.useId)(),y=(0,Q.useMemo)(()=>so(t,n),[t,n]),b=w({queryKey:[`analytics-metrics`,e,c,y,r,h],queryFn:()=>Fe(e,c,h),staleTime:$n}),x=b.data??null,S=b.error,C=u===`mentionShare`?`overall`:g,T=(0,Q.useMemo)(()=>x?fs(x,u,C):null,[x,u,C]),E=x?za(x):null,D=(0,Q.useMemo)(()=>La(E??{}),[E]),O=(0,Q.useMemo)(()=>ao(E??{}),[E]),k=(0,Q.useMemo)(()=>Object.entries(E??{}).filter(([,e])=>e.anchorUnavailable).map(([e])=>e).sort(),[E]),A=(0,Q.useMemo)(()=>x?Ga(x):{},[x]),j=(0,Q.useMemo)(()=>x?go(Zo(x)):[],[x]),F=(0,Q.useMemo)(()=>x?Va(x):[],[x]),L=(0,Q.useMemo)(()=>x?gs(x):[],[x]),R=(0,Q.useMemo)(()=>$a(E??{},A),[E,A]),re=(0,Q.useMemo)(()=>x?qa(x):{},[x]),B=(0,Q.useMemo)(()=>yn(re,{engineName:oo}),[re]),ie=(0,Q.useMemo)(()=>{let e=new Map;for(let[t,n]of Object.entries(re).sort(([e],[t])=>e.localeCompare(t))){let r=yn({[t]:n},{engineName:oo});r?.kind===`no-known-change`&&e.set(t,{text:`${r.text} ${r.detail}`,modelIds:n.modelIds??[]})}return e},[re]),ae=(0,Q.useMemo)(()=>{let e=new Map(i.map(e=>[Xe(e),e]));return t=>e.get(Xe(t))??t},[i]),oe=u!==`mentionShare`&&C===`byProvider`,V=x?.buckets??[],se=V[V.length-1]?.mentionShare.scope??x?.mentionShareScope??`pooled`,ce=vh(u,se),le=oe?ga.textDim:u===`cited`?ya.positive:u===`mentionShare`?sh:ua[1],ue=(0,Q.useMemo)(()=>{let e=new Map(V.map(e=>[e.startDate,us(e)]));return t=>e.get(String(t))??``},[V]),de=u===`mentionShare`?V.filter(e=>typeof e.mentionShare.rate==`number`&&Number.isFinite(e.mentionShare.rate)):V,fe=de.at(-1),pe=(x?Ua(x,u):[]).at(-1)??null,me=x?Za(x,u):null,he=fo(de,F),ge=vo(he,u,se,a),_e=pe!==null&&me!==null?Kt(me.delta):null,U=_e!==null&&!ge,ve=t.length,be=[];if(pe!==null&&fe&&be.push((0,$.jsxs)($.Fragment,{children:[`Latest point: `,(0,$.jsx)(`strong`,{children:Ch(fe,u)})]})),fe&&me!==null&&he&&!ge&&be.push(Ah(he,fe,F)),fe&&de.length===1){let e=kh(fe,F);e&&!vo(Ya(fe,F),u,se,a)&&be.push(e)}if(_e!==null&&de[0]){let e=co(de[0]);e&&be.push((0,$.jsxs)($.Fragment,{children:[`Base: `,(0,$.jsx)(`strong`,{children:e}),` point`]}))}oe&&pe!==null&&be.push((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:St(pe)}),` pools all answers; not an average of engines`]}));let xe=[...new Set([...D.buckets.map(e=>e.bucketStartDate),...V.filter(e=>Do(e,F).length>0).map(e=>e.startDate)])].sort(),Se=pe!==null&&fe&&(0,$.jsxs)(`div`,{className:`visibility-trend-current`,children:[(0,$.jsx)(`span`,{className:`visibility-trend-current-dot`,style:{backgroundColor:le},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`visibility-trend-current-label`,children:ce}),(0,$.jsx)(`span`,{className:`visibility-trend-current-value`,children:St(pe)}),_e!==null&&(0,$.jsx)(`span`,{className:`visibility-trend-current-delta ${U?`text-muted`:uh[_e.direction]}`,children:dh(_e)}),U&&he?(0,$.jsx)(X,{tone:`caution`,label:`Queries changed`,text:Mh(he)}):null]}),Ce=(0,$.jsxs)(`div`,{className:`visibility-trend-controls`,children:[m&&(0,$.jsx)(Io,{options:ah,value:f,onChange:p,label:`Query type`}),(0,$.jsx)(Io,{options:oh,value:u,onChange:d,label:`Metric`,className:`visibility-trend-metric-control`}),u!==`mentionShare`&&(0,$.jsx)(Io,{options:ih,value:g,onChange:_,label:`Series`}),(0,$.jsx)(Io,{options:fm,value:c,onChange:l,label:`Time window`,className:`sm:ml-auto`})]}),we;if(S)we=(0,$.jsx)(`p`,{className:`text-copy-14 text-negative-400`,children:Te(S)});else if(b.isLoading&&!x)we=(0,$.jsx)(`div`,{className:`visibility-trend-chart animate-pulse rounded-md bg-bg-elevated/40`,"aria-hidden":`true`});else if(u===`mentionShare`&&ve===0)we=(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Add tracked competitors to measure mention share over time.`});else if(!x||!T)we=null;else{let{rows:e,series:t,hasData:n}=T;if(!n)we=(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:u===`mentionShare`?`No answer-text brand mentions for you or tracked competitors in ${gh(se)} in this window yet.`:h===`all`?H()?Ba:`Run a check to start tracking citations and mentions over time.`:`No ${h} answers in this window.`});else if(oe&&t.length===0)we=(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`No per-engine breakdown for this data yet. Switch to `,(0,$.jsx)(`span`,{className:`text-strong`,children:`All engines`}),` to see the trend.`]});else{let n=`${ce} rate${h===`all`?``:` in ${h} answers`} across ${e.length} ${e.length===1?`check`:`checks`}. Latest ${St(pe)}${_e===null?``:`, ${fh(_e)}${U?`, not the same queries`:``}`}.`;we=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`sr-only`,children:n}),(0,$.jsx)(zh,{buckets:V,metric:u,mode:C,series:t,mentionShareScope:se}),oe&&t.length>0&&(0,$.jsx)(`ul`,{className:`trend-legend`,"aria-label":`Engines`,children:t.map((e,t)=>{let n=zo(x,e,u);return(0,$.jsxs)(`li`,{className:`trend-legend-item`,children:[(0,$.jsx)(`span`,{className:`trend-legend-swatch`,style:{backgroundColor:hh(e,t)},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`trend-legend-name`,children:mh(e)}),n!==null&&(0,$.jsx)(`span`,{className:`trend-legend-value`,children:St(n)})]},e)})}),(0,$.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"aria-label":`${ce} trend chart over ${e.length} ${e.length===1?`point`:`points`}`,children:(0,$.jsx)(I,{width:`100%`,height:`100%`,children:(0,$.jsxs)(te,{data:e,margin:{top:8,right:20,bottom:0,left:0},children:[(0,$.jsx)(M,{stroke:xa,vertical:!1}),(0,$.jsx)(P,{dataKey:`date`,tick:va,tickLine:!1,axisLine:{stroke:Ca},tickFormatter:ue,minTickGap:24}),(0,$.jsx)(z,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:e=>St(e,ye.percent),tick:va,tickLine:!1,axisLine:!1,width:48}),(0,$.jsx)(N,{cursor:{stroke:Ca,strokeWidth:1},content:(0,$.jsx)(Rh,{metric:u,mode:C,buckets:V,basketChanges:F})}),xe.map(e=>(0,$.jsx)(ne,{x:e,stroke:ch,strokeDasharray:`4 4`,strokeWidth:1.5,ifOverflow:`extendDomain`},`setup-change-${e}`)),t.map((e,t)=>(0,$.jsx)(ee,{type:`monotone`,dataKey:e,name:e,stroke:hh(e,t),strokeDasharray:e===`__mentionShare__`?`5 4`:void 0,strokeWidth:ph(e)?2.5:2,dot:e===`__mentionShare__`?{r:2.75,fill:`var(--chart-tooltip-bg)`,stroke:hh(e,t),strokeWidth:1.5}:{r:2.5,fill:hh(e,t),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:lh},connectNulls:e!==ms,isAnimationActive:!1},e))]})})}),xe.length>0&&(0,$.jsxs)(`p`,{className:`visibility-trend-key`,children:[(0,$.jsx)(`span`,{className:`visibility-trend-key-swatch`,"aria-hidden":`true`}),`Setup changed`]})]})}}return(0,$.jsxs)(`div`,{className:`visibility-trend-stack`,children:[(0,$.jsxs)(`section`,{className:`visibility-trend`,"aria-labelledby":v,children:[(0,$.jsxs)(`div`,{className:`av-card-head`,children:[(0,$.jsxs)(`div`,{className:`inline-flex items-center`,children:[(0,$.jsx)(`h2`,{id:v,className:`av-card-title`,children:`AI answers over time`}),(0,$.jsx)(X,{text:yh(se)})]}),fe?(0,$.jsx)(`p`,{className:`av-card-meta`,children:ja(fe)}):null]}),(0,$.jsxs)(`div`,{className:`visibility-trend-body`,children:[B?.kind===`change`&&(0,$.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:B.text}),Se,Ce,we]}),(0,$.jsx)(dc,{items:be})]}),x&&!S?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ih,{buckets:V,queryChanges:L,modelRows:R,served:A,pointerNotices:ie,truncated:O,incompleteHistory:k,queryName:ae,sweepTimes:o}),(0,$.jsx)(Lh,{substitutions:j})]}):null]})}var Vh=new Set([At.queued,At.running]),Hh={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 Uh({projectName:e,onReviewForTracking:t,scopeOptions:n,planRevision:r,selectedScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c=[],viewerResearchConfig:l=null}){let u=S(),{account:d,canWrite:f}=qn(),p=d?.role===`viewer`&&l!==null,m=!f,h=Ze(),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(null),[T,E]=(0,Q.useState)([]),O=(0,Q.useRef)(null),k=(0,Q.useRef)(!1),[A,j]=(0,Q.useState)(0),M=w({...Qi({client:K,path:{name:e}}),staleTime:6e4}),N=w({...ci({client:K}),enabled:!m&&!h,staleTime:6e4}),P={client:K,path:{name:e},query:{limit:20}},F=D({...Qr(P),initialData:void 0,initialPageParam:P,getNextPageParam:e=>e.nextCursor?{path:P.path,query:{...P.query,cursor:e.nextCursor}}:void 0,refetchInterval:e=>e.state.data?.pages.some(e=>e.runs.some(e=>Vh.has(e.status)))?3e3:!1}),I=F.isError&&!F.isFetchNextPageError,L=F.data?.pages.at(-1),R=I?[]:[...new Map((F.data?.pages.flatMap(e=>e.runs)??[]).map(e=>[e.id,e])).values()],z=L?.access?.canRun??(f||p),ee=L?.access?L.access.dailyRunLimit:p?l.viewerDailyRunLimit:null;(0,Q.useEffect)(()=>{!b&&R[0]&&x(R[0].id)},[R,b]);let te=R.find(e=>e.id===b)??null,ne=w({...ta({client:K,path:{name:e,runId:b??``}}),enabled:!I&&!!b,refetchInterval:te&&Vh.has(te.status)?3e3:!1}),B=I||ne.isError?null:ne.data??null,ie=M.data?.locations??[],ae=(0,Q.useMemo)(()=>{if(m)return(L?.providers??[]).filter(e=>e.name!==`openrouter`).map(e=>({...e,catalog:e}));let e=N.data?.providerCatalog??[],t=new Map(e.map(e=>[e.name,e])),n=Oo(e),r=new Map((N.data?.providers??[]).filter(e=>e.configured).map(e=>[e.name,e])),i=[...r.values()].filter(e=>!os(e.name,n)&&!ut(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=>Ho(e,ts)&&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((L?.providers??[]).filter(e=>ut(e.name)).map(e=>[e.name,e]));if(!r.has(`openrouter`)&&s.size===0)return[...i,...a];let c=[...new Set([...M.data?.providers??[],...s.keys()])].filter(ut).flatMap(e=>{let n=re(e);if(!n)return[];let r=t.get(e),i=s.get(e),a=r??(o?{...o,name:e,displayName:i?.displayName??oo(e),modelConfigurable:!1,defaultModel:n,knownModels:o.knownModels.filter(e=>e.id===n)}:i);return a?[{name:e,displayName:i?.displayName??oo(e),configured:!0,defaultModel:n,catalog:a}]:[]});return[...i,...c,...a]},[L?.providers,m,M.data?.providers,N.data]),oe=!(m?F.isPending:N.isPending)&&ae.length===0,V=ae.find(e=>e.name===g)??null;(0,Q.useEffect)(()=>{if(!g&&M.data&&!M.isError&&!N.isError){let e=ae.filter(e=>!(`kind`in e)||e.kind!==`answer-service`),t=M.data.providers.find(t=>e.some(e=>e.name===t));_(t??e[0]?.name??``)}},[g,ae,M.data,M.isError,N.isError]);let se=V?.catalog.modelConfigurable??!1,H=m?V?.catalog.defaultModel:(V?M.data?.providerModels[V.name]:``)||V?.catalog.defaultModel,ce=(se?v.trim():``)||H,le=V?[...new Map([{id:V.catalog.defaultModel,displayName:V.catalog.defaultModel},...v.trim()?[{id:v.trim(),displayName:v.trim()}]:[],...V.catalog.knownModels].map(e=>[e.id,e])).values()]:[],ue=C({...Ai(),onSuccess:async e=>{O.current=null,j(e=>e+1),E(e.runs),x(e.runs[0]?.id??null),await ag(u),Xn({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=>{Xn({title:`Could not start research`,detail:e instanceof Error?e.message:`Check the provider, model, and location, then try again.`,tone:`negative`})},onSettled:()=>{k.current=!1}});return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-4`,children:[h?(0,$.jsx)(Z,{className:`surface-card min-w-0`,children:(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`This public demo shows saved research results. Running research is unavailable.`})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Kh,{projectName:e,canWrite:f,researchAllowed:z&&!I,limitedAccess:m,isEmbed:Y(),scopeOptions:n??[],planRevision:r??i?.planRevision??null,initialScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c,locations:ie,defaultLocation:M.data?.defaultLocation??null,providerOptions:ae,provider:g,onProviderChange:e=>{_(e),y(``)},resolvedModel:ce,visibilityModel:H,configurableModel:se,model:v,onModelChange:y,modelOptions:le,settingsReady:m?!F.isPending&&!I:!N.isPending&&!N.isError&&!N.isFetching,projectReady:!M.isPending&&!M.isError&&!M.isFetching,isPending:ue.isPending,errorMessage:ue.isError?`The request could not be confirmed.`:void 0,onSubmit:(t,n)=>{!z||I||Y()||k.current||(O.current?.fingerprint!==n&&(O.current={fingerprint:n,key:crypto.randomUUID()}),k.current=!0,ue.mutate({client:K,path:{name:e},body:{...t,idempotencyKey:O.current.key}}))}},`${e}:${A}`),ee!==null&&(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Up to `,ee,` destination runs per project per day.`]}),!m&&N.isError?(0,$.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load API providers.`}),(0,$.jsx)(q,{variant:`outline`,onClick:()=>{N.refetch()},children:`Retry providers`})]}):null,M.isError?(0,$.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load project locations.`}),(0,$.jsx)(q,{variant:`outline`,onClick:()=>{M.refetch()},children:`Retry locations`})]}):null,!(m?I:N.isError)&&oe&&(0,$.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.`}),T.length>0&&(0,$.jsxs)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:[`Saved runs: `,T.map((e,t)=>(0,$.jsxs)(`span`,{children:[t>0?`, `:``,(0,$.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,$.jsxs)(Z,{className:`surface-card min-w-0`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsx)(`div`,{children:(0,$.jsx)(`h3`,{children:Hh.historyTitle})}),F.isFetching&&(0,$.jsx)(J,{tone:`neutral`,children:`Loading`})]}),I?(0,$.jsxs)(`div`,{role:`alert`,className:`mt-4 text-label-14 text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load research history.`}),(0,$.jsx)(q,{variant:`outline`,onClick:()=>{F.refetch()},children:`Retry history`})]}):F.isPending?(0,$.jsx)(`p`,{role:`status`,children:`Loading research history…`}):R.length===0?(0,$.jsx)(`p`,{className:`mt-4 text-copy-14 text-muted`,children:Hh.emptyHistory}):(0,$.jsx)(`div`,{className:`mt-4 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[760px] [overflow-wrap:anywhere]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Run`}),(0,$.jsx)(`th`,{children:`Model`}),(0,$.jsx)(`th`,{children:`Destination`}),(0,$.jsx)(`th`,{children:`Location`}),(0,$.jsx)(`th`,{children:`Progress`}),(0,$.jsx)(`th`,{children:`Status`})]})}),(0,$.jsx)(`tbody`,{children:R.map(e=>(0,$.jsxs)(`tr`,{className:b===e.id?`bg-bg-elevated/40`:void 0,children:[(0,$.jsx)(`td`,{children:(0,$.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:tg(e.createdAt)})}),(0,$.jsxs)(`td`,{className:`text-secondary`,children:[(0,$.jsx)(`span`,{className:`block`,children:e.provider}),(0,$.jsx)(`span`,{className:`text-label-12-mono text-muted`,children:e.requestedModel??e.resolvedModel})]}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.scope?.label??`Whole site`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.location?.label??`No location`}),(0,$.jsxs)(`td`,{className:`tabular-nums text-secondary`,children:[e.completedQueries+e.failedQueries,`/`,e.totalQueries]}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:rg(e.status),children:e.status})})]},e.id))})]})}),F.isFetchNextPageError&&(0,$.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:Hh.historyMoreError}),F.hasNextPage&&(0,$.jsx)(q,{className:`mt-3`,variant:`outline`,disabled:F.isFetching,onClick:()=>{F.fetchNextPage()},children:F.isFetchingNextPage?Hh.historyLoading:Hh.historyMore})]})]}),!I&&ne.isError?(0,$.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load saved research results.`}),(0,$.jsx)(q,{variant:`outline`,onClick:()=>{ne.refetch()},children:`Retry results`})]}):I?null:(0,$.jsx)(Zh,{detail:B,isLoading:ne.isFetching,onReviewForTracking:h?void 0:t})]})}var Wh=`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`,Gh=`__none__`;function Kh(e){let{projectName:t,locations:n,provider:r,resolvedModel:i,planRevision:a}=e,o=S(),[s,c]=(0,Q.useState)(`once`),[l,u]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`),[g,_]=(0,Q.useState)(null),[v,b]=(0,Q.useState)([]),[x,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)({}),[D,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)([]),[j,M]=(0,Q.useState)(null),[N,P]=(0,Q.useState)(!1),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(``),[z,ee]=(0,Q.useState)(``),te=(0,Q.useRef)(null),ne=(0,Q.useRef)(!1),re=(0,Q.useRef)(null),B=e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`;(0,Q.useEffect)(()=>{h(B),O(null)},[B]);let ie=e.scopeOptions.filter(e=>e.kind===`market`||e.kind===`property`),ae=s===`markets`?`market`:`property`,oe=ie.filter(e=>e.kind===ae),V=t=>({kind:t.kind,key:t.id,label:t.label,planRevision:a??e.initialScope?.planRevision??0}),se=e=>e===Gh?null:n.find(t=>t.label===e),H=g??e.defaultLocation??Gh,ce=ie.find(e=>`${e.kind}:${e.id}`===m),le=ce?V(ce):null,ue=s===`once`?[{scope:le,location:se(H)}]:s===`locations`?v.map(e=>({scope:null,location:se(e)})):v.map(e=>oe.find(t=>`${t.kind}:${t.id}`===e)).map(e=>e?{scope:V(e),location:se(T[`${e.kind}:${e.id}`]??Gh)}:null),de=[...new Map([...k,...e.templates].map(e=>[e.id,e])).values()],fe=D?de.find(e=>e.id===D.id):null,pe=D!==null&&fe?.version!==D.version,me=s===`once`?l:f,he=me.split(/\r?\n/).filter(e=>e.trim()),ge=cn(he),_e=[...new Set([...f.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))],U=/[{}]/.test(f.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,``)),ve=[];he.length||ve.push(s===`once`?`Enter at least one query.`:`Enter at least one query pattern.`),he.some(e=>e.length>4e3)&&ve.push(`Keep each query under 4,001 characters.`),s!==`once`&&U&&ve.push(`Use the name buttons to insert a supported variable. Remove unknown or incomplete braces.`),ue.length||ve.push(s===`locations`?`Select at least one location.`:`Select at least one destination.`),ue.some(e=>!e||e.location===void 0)&&ve.push(`A selected destination or location is no longer available. Update your selection.`);let ye=s===`once`&&m!==`project`||s===`markets`||s===`properties`;ye&&(e.scopePending||e.scopeError||!a||ue.some(e=>!e?.scope))&&ve.push(`Load the current published markets and properties before running scoped research.`);let be=(s===`once`?ge.length:he.length)*ue.length;if(ue.length>20&&ve.push(`Select at most 20 destinations.`),be>50&&ve.push(`${be} queries selected. Reduce the selection to 50 or fewer.`),pe&&ve.push(`This saved pattern changed. Select its current version from Saved patterns.`),s!==`once`&&!U){for(let e of ue)if(e&&e.location!==void 0)try{Xt(D??{pattern:f,variables:_e},e.scope,e.location)}catch{ve.push(`Choose a location for {location}, or use only variables available for ${s===`markets`?`markets`:s===`properties`?`properties`:`locations`}.`);break}}let xe=JSON.stringify({mode:s,source:me,contexts:ue,provider:r,resolvedModel:i,template:D,...ye?{planRevision:a}:{}}),Se=j!==null&&j.signature!==xe,Ce=s===`once`?ge.map((e,t)=>({id:String(t),query:e,scope:le,location:ue[0]?.location??null})):j?.rows??[],we=Xh(Ce),Te=[];s!==`once`&&j&&(Se&&Te.push(`Setup changed. Your edited queries are preserved. Regenerate the preview to use the new setup.`),Ce.some(e=>!e.query.trim()||e.query.length>4e3||/\{(?:market|submarket|property|propertyBrand|location)\}/.test(e.query))&&Te.push(`Every preview row needs a complete query of 1 to 4,000 characters, with no unresolved variables.`),Ce.some(e=>e.location&&!n.some(t=>JSON.stringify(t)===JSON.stringify(e.location)))&&Te.push(`A preview location changed. Regenerate the preview.`),we.some(e=>cn(e.queries).length!==e.queries.length)&&Te.push(`Remove duplicate queries within each destination and location.`),we.length>20&&Te.push(`The preview exceeds 20 runs.`));let Ee=e.researchAllowed&&!e.isEmbed&&!e.isPending&&e.settingsReady&&e.projectReady&&!!(r&&i)&&!ve.length&&!Te.length&&(s===`once`||j!==null),De=()=>({runs:we.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}:{}}))}),Oe=()=>{if(P(!0),ve.length)return;let e=ue.flatMap((e,t)=>he.map((n,r)=>({id:`${t}:${r}`,scope:e.scope,location:e.location,...D?{template:{templateId:D.id,templateVersion:D.version,bindingLocation:e.location}}:{},query:Xt({pattern:n,variables:[...new Set([...n.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))]},e.scope,e.location).output})));M({signature:xe,rows:e})},ke=e=>{c(e),b([]),O(null),w(``),P(!1)},Ae=e=>{if(ee(``),s===`once`)try{u(Xt(e,le,se(H)).output)}catch{ee(`Select a matching market, property, or location before using this pattern.`);return}else p(e.pattern);O(e)},je=e=>{let t=re.current,n=t?.selectionStart??f.length,r=t?.selectionEnd??n;p(`${f.slice(0,n)}{${e}}${f.slice(r)}`),O(null),requestAnimationFrame(()=>{t?.focus(),t?.setSelectionRange(n+e.length+2,n+e.length+2)})},W=C({...Tr(),onSuccess:async e=>{let n={id:e.id,version:e.updatedAt,label:e.name,pattern:e.pattern,variables:e.variables};A(t=>[...t.filter(t=>t.id!==e.id),n]),O(n),I(!1),R(``),ee(``),te.current=null,await o.invalidateQueries({queryKey:Pi({client:K,path:{name:t}})}),Xn({title:`Pattern saved`,detail:`Available in Saved patterns. Tracking was not changed.`,tone:`positive`})},onError:()=>ee(`Could not save the pattern. Your text is preserved. Retry to save the same pattern.`),onSettled:()=>{ne.current=!1}}),Me=()=>{if(!e.canWrite||e.isEmbed||ne.current)return;let n=s===`once`?l:f,r=s===`once`?[]:_e;if(!L.trim()||!n.trim()||n.length>4e3||s!==`once`&&U){ee(`Enter a name and a valid pattern of 1 to 4,000 characters.`);return}let i={name:L.trim(),pattern:n,variables:r},a=JSON.stringify(i);te.current?.fingerprint!==a&&(te.current={fingerprint:a,id:crypto.randomUUID()}),ne.current=!0,W.mutate({client:K,path:{name:t,templateId:te.current.id},body:i})},Ne=[...new Set([...N||me.trim()?ve:[],...Te])],Pe=de.filter(e=>{let t=s===`once`?Pt(le,se(H)):Pt(s===`markets`?{kind:`market`,label:`Market`}:s===`properties`?{kind:`property`,label:`Property`}:null,{label:`Location`});return e.variables.every(e=>t[e]!==void 0)});return(0,$.jsxs)(Z,{className:`surface-card min-w-0`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{children:`Test queries`}),(0,$.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,$.jsxs)(`fieldset`,{"aria-label":`Research setup`,className:`mt-5 min-w-0 space-y-5`,disabled:e.isPending||W.isPending,children:[(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Run mode`}),(0,$.jsxs)(`select`,{className:Wh,value:s,disabled:e.isPending,onChange:e=>ke(e.target.value),children:[(0,$.jsx)(`option`,{value:`once`,children:`Run once`}),(0,$.jsx)(`option`,{value:`markets`,disabled:!ie.some(e=>e.kind===`market`),children:`Repeat across markets`}),(0,$.jsx)(`option`,{value:`properties`,disabled:!ie.some(e=>e.kind===`property`),children:`Repeat across properties`}),(0,$.jsx)(`option`,{value:`locations`,disabled:!n.length,children:`Repeat across locations`})]})]}),s===`once`&&(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(ie.length>0||m!==`project`)&&(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Save results under`}),(0,$.jsxs)(`select`,{className:Wh,value:m,onChange:e=>{h(e.target.value),O(null)},children:[(0,$.jsx)(`option`,{value:`project`,children:`Whole site`}),m!==`project`&&!ce&&(0,$.jsx)(`option`,{value:m,disabled:!0,children:`Selected destination unavailable`}),ie.map(e=>(0,$.jsxs)(`option`,{value:`${e.kind}:${e.id}`,children:[e.label,` (`,e.kind,`)`]},`${e.kind}:${e.id}`))]})]}),(0,$.jsx)(qh,{label:`Answer engine location`,value:H,locations:n,onChange:e=>{_(e),O(null)}})]}),s!==`once`&&(0,$.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,$.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:s===`locations`?`Select locations`:`Select ${s}`}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose each destination explicitly. Each selected destination gets its own saved research run.`}),(0,$.jsx)(`input`,{type:`search`,"aria-label":`Search destinations`,className:Wh,placeholder:`Search ${s}`,value:x,onChange:e=>w(e.target.value)}),(0,$.jsx)(`div`,{className:`max-h-72 space-y-2 overflow-y-auto pr-1`,children:(s===`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(x.toLocaleLowerCase())).map(e=>{let t=v.includes(e.key);return(0,$.jsxs)(`div`,{className:`grid items-center gap-2 border-b border-default pb-2 sm:grid-cols-[minmax(0,1fr)_16rem]`,children:[(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-3 text-label-14 text-heading`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t,onChange:()=>b(n=>t?n.filter(t=>t!==e.key):[...n,e.key])}),e.label]}),t&&s!==`locations`&&(0,$.jsx)(qh,{label:`Answer engine location for ${e.label}`,value:T[e.key]??Gh,locations:n,onChange:t=>E(n=>({...n,[e.key]:t}))})]},e.key)})}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[v.length,` selected. A market or property name changes query text, not the answer engine's location.`]})]}),e.scopeError&&(0,$.jsxs)(`p`,{className:`text-copy-14 text-caution`,children:[`Markets and properties could not load. Whole-site and location research remain available. `,(0,$.jsx)(q,{variant:`outline`,onClick:e.onRetryScope,children:`Retry destinations`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`block`,htmlFor:`research-query-editor`,children:(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:s===`once`?`Queries`:`Query pattern`})}),(0,$.jsx)(`p`,{id:`research-query-guidance`,className:`mt-1 text-copy-14 text-secondary`,children:s===`once`?`Enter one query per line. The answer engine receives exactly this text.`:`Use {${s===`markets`?`market`:s===`properties`?`property`:`location`}} where each name belongs. Preview the resolved queries before running.`}),(0,$.jsx)(`textarea`,{id:`research-query-editor`,ref:re,className:`${Wh} min-h-32`,"aria-describedby":`research-query-guidance research-query-count`,value:me,placeholder:s===`once`?Hh.queryPlaceholder:s===`markets`?`Best apartments in {market}`:s===`properties`?`What amenities does {property} offer?`:`Best apartments in {location}`,onChange:e=>{s===`once`?u(e.target.value):(p(e.target.value),O(null))}}),s!==`once`&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-2`,children:[(0,$.jsxs)(q,{size:`sm`,variant:`outline`,onClick:()=>je(s===`markets`?`market`:s===`properties`?`property`:`location`),children:[`Insert `,s===`markets`?`market`:s===`properties`?`property`:`location`,` name`]}),(0,$.jsx)(`span`,{className:`self-center text-label-14 text-secondary`,children:`One pattern per line.`})]}),(0,$.jsxs)(`p`,{id:`research-query-count`,className:`mt-2 text-copy-14 text-secondary`,children:[be,` / `,50,` queries`,s===`once`?``:` across ${ue.length} destinations`]})]}),s!==`once`&&(0,$.jsxs)(`details`,{className:`border-t border-default pt-3`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading focus-visible:outline focus-visible:outline-2`,children:[`Saved patterns `,(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`(optional)`})]}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.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.`}),Pe.length?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Pe.map(e=>(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>Ae(e),children:e.label},e.id))}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No saved patterns for this selection.`}),D&&(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`Using: `,D.label]}),e.canWrite&&!e.isEmbed&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>I(!F),children:F?`Cancel save`:`Save as a pattern`}),F&&(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[(0,$.jsxs)(`label`,{className:`min-w-48 flex-1 text-label-14 text-heading`,children:[`Pattern name`,(0,$.jsx)(`input`,{className:Wh,value:L,maxLength:120,onChange:e=>R(e.target.value)})]}),(0,$.jsx)(q,{size:`sm`,disabled:W.isPending||!L.trim()||!me.trim(),onClick:Me,children:W.isPending?`Saving…`:`Save pattern`})]})]}),z&&(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:z})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Answer engine`,(0,$.jsxs)(`select`,{className:Wh,value:r,onChange:t=>e.onProviderChange(t.target.value),children:[(0,$.jsx)(`option`,{value:``,disabled:!0,children:`Choose an answer engine`}),e.providerOptions.map(e=>(0,$.jsx)(`option`,{value:e.name,children:e.displayName??e.name},e.name))]})]}),(0,$.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Model`,e.limitedAccess?(0,$.jsxs)(`select`,{className:Wh,value:e.model,disabled:!r||!e.configurableModel,onChange:t=>e.onModelChange(t.target.value),children:[(0,$.jsxs)(`option`,{value:``,children:[`Use AI Visibility model · `,e.visibilityModel]}),e.modelOptions.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.displayName},e.id))]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`input`,{"aria-label":`Model`,className:Wh,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,$.jsx)(`datalist`,{id:`research-known-models`,children:e.modelOptions.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.displayName},e.id))})]})]})]}),Ne.length>0&&(0,$.jsx)(Yh,{errors:Ne}),s!==`once`&&(0,$.jsxs)(`div`,{className:`space-y-4 border-t border-default pt-4`,children:[(0,$.jsxs)(q,{variant:`outline`,size:`sm`,disabled:e.isPending||!e.projectReady,onClick:Oe,children:[(0,$.jsx)(d,{size:14}),j?Hh.refreshPreview:`Preview queries`]}),j&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Queries to run`}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[Ce.length,` query executions in `,we.length,` saved runs · `,r,` · `,i,`. Edit any query or location below.`]}),(0,$.jsx)(Jh,{rows:Ce,locations:n,onChange:(e,t)=>M(n=>n&&{...n,rows:n.rows.map(n=>n.id===e?{...n,...t}:n)})})]})]}),e.errorMessage&&(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 border-t border-default pt-4`,children:[!e.isEmbed&&(0,$.jsxs)(q,{size:`sm`,disabled:!Ee,onClick:()=>{if(Ee){let n=De();e.onSubmit(n,JSON.stringify({projectName:t,...n}))}},children:[(0,$.jsx)(y,{size:14}),e.isPending?`Starting…`:Hh.runAction]}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[s===`once`?`${ge.length} queries`:`${Ce.length} reviewed queries`,` · `,r||`Choose an engine`,` · `,i||`Choose a model`,`. Uses your configured answer engine.`]})]})]})]})}function qh({label:e,value:t,locations:n,onChange:r}){return(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e}),(0,$.jsxs)(`select`,{className:Wh,value:t,onChange:e=>r(e.target.value),children:[(0,$.jsx)(`option`,{value:Gh,children:`No location context`}),n.map(e=>(0,$.jsx)(`option`,{value:e.label,children:e.label},e.label))]})]})}function Jh({rows:e,locations:t,onChange:n}){return(0,$.jsx)(`ol`,{className:`divide-y divide-default`,children:e.map((e,r)=>(0,$.jsxs)(`li`,{className:`grid gap-3 py-4 md:grid-cols-[10rem_minmax(0,1fr)_15rem]`,children:[(0,$.jsxs)(`div`,{className:`text-label-14`,children:[(0,$.jsxs)(`span`,{className:`block text-secondary`,children:[`Query `,r+1]}),(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.scope?.label??e.location?.label??`Whole site`}),e.scope&&(0,$.jsx)(`span`,{className:`block text-secondary`,children:e.scope.kind})]}),(0,$.jsxs)(`label`,{className:`block text-label-14-strong text-heading`,children:[`Query`,(0,$.jsx)(`textarea`,{className:`${Wh} 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,$.jsx)(qh,{label:`Location for query ${r+1}`,value:e.location?.label??Gh,locations:t,onChange:r=>n(e.id,{location:t.find(e=>e.label===r)??null})})]},e.id))})}function Yh({errors:e}){return(0,$.jsx)(`div`,{role:`alert`,className:`text-label-14 text-negative`,children:(0,$.jsx)(`ul`,{className:`list-disc space-y-1 pl-5`,children:e.map(e=>(0,$.jsx)(`li`,{children:e},e))})})}function Xh(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 Zh({detail:e,isLoading:t,onReviewForTracking:n}){let[r,i]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{i(e?.queries[0]?.id??null)},[e?.id]);let a=e?.queries.find(e=>e.id===r)??e?.queries[0]??null;return(0,$.jsxs)(Z,{id:e?`research-run-${e.id}`:void 0,className:`surface-card min-w-0`,role:`region`,"aria-label":Hh.resultsTitle,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Results`}),(0,$.jsx)(`h3`,{children:e?`Research run ${ng(e.id)}`:Hh.resultsEmpty})]}),e&&(0,$.jsx)(J,{tone:rg(e.status),children:e.status})]}),e&&(0,$.jsxs)(`div`,{className:`mt-3 space-y-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`dl`,{className:`flex flex-wrap gap-x-6 gap-y-2 [overflow-wrap:anywhere]`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Answer engine`}),(0,$.jsx)(`dd`,{children:e.provider})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Requested model`}),(0,$.jsx)(`dd`,{className:`font-mono`,children:e.requestedModel??e.resolvedModel})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Location`}),(0,$.jsx)(`dd`,{children:e.location?.label??`No location`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Destination`}),(0,$.jsx)(`dd`,{children:e.scope?.label??`Whole site`})]})]}),e.template&&(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{className:`cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2`,children:Hh.templateProvenance}),(0,$.jsxs)(`dl`,{className:`mt-2 space-y-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Saved pattern`}),(0,$.jsx)(`dd`,{className:`whitespace-pre-wrap`,children:e.template.template})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Names used`}),(0,$.jsx)(`dd`,{children:Object.entries(e.template.bindings).map(([e,t])=>`${e}: ${t}`).join(` · `)||`No variables`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-14-strong`,children:`Original resolved text`}),(0,$.jsx)(`dd`,{className:`whitespace-pre-wrap`,children:e.template.output})]})]}),(0,$.jsx)(`p`,{className:`mt-2`,children:`The queries below are the final text sent to the answer engine, including any edits.`}),(0,$.jsxs)(`p`,{className:`mt-2 text-copy-13-mono`,children:[e.template.templateId,` · `,e.template.templateVersion]})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsx)(`summary`,{className:`cursor-pointer focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2`,children:Hh.methodologySummary}),(0,$.jsx)(`p`,{className:`mt-2 max-w-prose text-copy-14`,children:Hh.methodology})]})]}),e?(0,$.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[760px] [overflow-wrap:anywhere]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Query`}),(0,$.jsx)(`th`,{children:`Class`}),(0,$.jsx)(`th`,{children:`Status`}),(0,$.jsx)(`th`,{children:`Brand-name match`}),(0,$.jsx)(`th`,{children:`Project domain cited`})]})}),(0,$.jsx)(`tbody`,{children:e.queries.map(e=>(0,$.jsxs)(`tr`,{className:a?.id===e.id?`bg-bg-elevated/40`:void 0,children:[(0,$.jsx)(`td`,{children:(0,$.jsx)(`button`,{type:`button`,className:`text-left text-button-14 text-heading hover:text-link focus:outline-none focus:underline`,onClick:()=>i(e.id),children:e.query})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:e.queryClass===`branded`?`positive`:e.queryClass===`non-brand`?`neutral`:`caution`,children:e.queryClass===`branded`?Hh.brandedQuery:e.queryClass===`non-brand`?Hh.discoveryQuery:Hh.unclassifiedQuery})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:ig(e.status),children:e.status})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:e.answerMentioned===!0?`positive`:e.answerMentioned===!1?`neutral`:e.status===Et.failed?`negative`:`caution`,children:e.answerMentioned===null?e.status===Et.failed?`Unavailable`:`Pending`:e.answerMentioned?`Matched`:`No match`})}),(0,$.jsx)(`td`,{children:e.citationMeasured===!1&&e.status===Et.completed?(0,$.jsx)(J,{tone:`neutral`,children:`Not measured`}):(0,$.jsx)(J,{tone:e.citationState===`cited`?`positive`:e.citationState===`not-cited`?`neutral`:e.status===Et.failed?`negative`:`caution`,children:e.citationState===null?e.status===Et.failed?`Unavailable`:`Pending`:e.citationState===`cited`?`Cited`:`Not cited`})})]},e.id))})]})}),(0,$.jsx)(Qh,{query:a,scope:e.scope??null,isLoading:t,onReviewForTracking:n})]}):(0,$.jsx)(`p`,{className:`mt-4 text-copy-14 text-muted`,children:`Select a saved run to inspect each answer and its source links.`})]})}function Qh({query:e,isLoading:t,scope:n,onReviewForTracking:r}){return e?(0,$.jsxs)(`div`,{className:`min-w-0 space-y-4 border-t border-default pt-4 [overflow-wrap:anywhere]`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Selected query`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-heading`,children:e.query})]}),!Y()&&r&&(0,$.jsxs)(`div`,{className:`material-base px-3 py-3`,children:[(0,$.jsx)(hs,{type:`button`,size:`sm`,onClick:()=>r({researchRunQueryId:e.id,scope:n}),children:`Review for tracking`}),(0,$.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,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Partial answer, not measured`}),(0,$.jsx)(`div`,{className:`mt-1`,children:(0,$.jsx)(Ja,{headingLevel:4,copyable:!0,children:e.answerText})})]}):e.error?null:e.answerText?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Answer`}),(0,$.jsx)(`div`,{className:`mt-1`,children:(0,$.jsx)(Ja,{headingLevel:4,copyable:!0,children:e.answerText})})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:e.status===Et.failed?`This query did not return an answer.`:e.status===Et[`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,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Named in answer`}),(0,$.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:e.namedCompetitors.map(e=>(0,$.jsx)(`span`,{className:`mention-chip mention-chip--competitor`,children:e},e))})]}),e.citedCompetitorDomains.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Cited competitor domains`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:`Cited as a source, not merely named in the answer.`}),(0,$.jsx)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:e.citedCompetitorDomains.map(e=>(0,$.jsx)(`span`,{className:`mention-chip mention-chip--competitor`,children:e.replace(/^www\./,``)},e))})]}),e.groundingSources.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Source links`}),(0,$.jsx)(`ul`,{className:`mt-2 space-y-3`,children:e.groundingSources.map((e,t)=>(0,$.jsx)(`li`,{className:`min-w-0`,children:(0,$.jsx)(Jo,{url:e.uri,title:e.title})},`${e.uri}-${t}`))})]}),e.evidence&&(0,$.jsx)(eg,{evidence:e.evidence})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:t?`Loading saved answers…`:`Select a query to inspect its answer.`})}var $h={"explicit-citation":`Cited in the answer`,"answer-support":`Used for the answer`,"search-result":`Search result`,"page-read":`Page read`};function eg({evidence:e}){let t=e.sources.filter(e=>e.relationship===`search-result`||e.relationship===`page-read`);return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Answer service evidence`}),(0,$.jsxs)(`dl`,{className:`definition-list`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Status`}),(0,$.jsx)(`dd`,{children:Ne(e.completion.status)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Profile`}),(0,$.jsx)(`dd`,{className:`text-label-12-mono`,children:e.identity.route})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Model`}),(0,$.jsx)(`dd`,{children:e.identity.disclosedModel?`${e.identity.disclosedModel}${e.identity.disclosedModelKind===`service-tier`?` (service tier)`:``}`:`Not disclosed`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Cost`}),(0,$.jsx)(`dd`,{children:Ie(e.usage.cost)})]}),!e.citationMeasurable&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Citations`}),(0,$.jsx)(`dd`,{children:`Not measured: this service does not tie its sources to the answer.`})]})]}),t.length>0&&(0,$.jsx)(`ul`,{className:`space-y-3`,children:t.map((e,t)=>(0,$.jsxs)(`li`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`text-copy-13 text-muted`,children:$h[e.relationship]}),(0,$.jsx)(Jo,{url:e.url,title:e.title??e.url})]},`${e.url}-${t}`))})]})}function tg(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 ng(e){return e.length>8?e.slice(0,8):e}function rg(e){return e===At.completed?`positive`:e===At.partial||e===At[`waiting-upstream`]?`caution`:e===At.failed?`negative`:`neutral`}function ig(e){return e===Et.completed?`positive`:e===Et.failed?`negative`:e===Et[`waiting-upstream`]?`caution`:`neutral`}async function ag(e){await Zn(e,`researchRuns`)}var og=new Set([`queued`,`seeding`,`probing`]);function sg({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}=qn(),[d,f]=(0,Q.useState)(`tracked`),[p,m]=(0,Q.useState)(`find`),[h,g]=(0,Q.useState)(null),_=u?.role===`viewer`?Jt():null,v=Zs(u?.role,_),y=Qs(t??d,v),b=r??p,x=e=>{t===void 0&&f(e),n?.(e)};return(0,$.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`queries-heading`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsx)(`h2`,{id:`queries-heading`,children:`Queries`})}),(0,$.jsxs)(`div`,{className:`mt-3 flex border-b border-default`,role:`tablist`,"aria-label":`Query workspace`,children:[(0,$.jsx)(cg,{active:y===`tracked`,label:`Tracked`,onClick:()=>x(`tracked`)}),v?(0,$.jsx)(cg,{active:y===`research`,label:`Research`,onClick:()=>x(`research`)}):null]}),(0,$.jsx)(`div`,{className:`mt-4`,children:y===`tracked`?(0,$.jsx)(Gg,{projectName:e,selection:a,onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,pendingTrackingSource:h,onPendingTrackingSourceHandled:()=>g(null),publishGuard:l}):(0,$.jsx)(lg,{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}),x(`tracked`)},onSelectionChange:o,viewerResearchConfig:_})})]})}function cg({active:e,label:t,onClick:n}){return(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":e,className:`-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 ${e?`border-mono-400 text-heading`:`border-transparent text-muted hover:border-strong hover:text-strong`}`,onClick:n,children:t})}function lg({projectName:e,selection:t,mode:n,onModeChange:r,onReviewSavedSource:i,viewerResearchConfig:a}){let{canWrite:o}=qn(),s=!o||n===`test`,c=w({...Yr({client:K,path:{name:e}}),enabled:s,staleTime:6e4}),l=w({...Bi({client:K,path:{name:e}}),enabled:s,staleTime:6e4}),u=(0,Q.useMemo)(()=>{let e=c.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)}:{}}))]},[c.data]),d=(0,Q.useMemo)(()=>(l.data?.templates??[]).map(e=>({id:e.id,version:e.updatedAt,label:e.name,pattern:e.pattern,variables:e.variables})),[l.data]),f={projectName:e,scopeOptions:u,planRevision:c.data?.active?.revision??null,selectedScope:(()=>{let e=u.find(e=>e.kind===t.measurementScope&&e.id===t.measurementScopeKey),n=c.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:c.isPending||c.isFetching,scopeError:c.isError,onRetryScope:()=>{c.refetch()},templates:d};return o?(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`flex border-b border-default`,role:`tablist`,"aria-label":`Research workspace`,children:[(0,$.jsx)(cg,{active:n===`find`,label:`Find queries`,onClick:()=>r(`find`)}),(0,$.jsx)(cg,{active:n===`test`,label:`Test queries`,onClick:()=>r(`test`)})]}),(0,$.jsx)(`div`,{className:`mt-4`,children:n===`find`?(0,$.jsx)(Kg,{projectName:e,onReviewDiscoveryProbe:e=>i({source:`discovery`,discoveryProbeId:e})}):(0,$.jsx)(Uh,{...f,onReviewForTracking:({researchRunQueryId:e,scope:t})=>i({source:`research`,researchRunQueryId:e},t??null)})})]}):(0,$.jsx)(Uh,{...f,viewerResearchConfig:a})}function ug({workspace:e,selection:t,onSelectionChange:r,trackingQueryId:i,onTrackingQueryIdChange:a,pendingTrackingSource:o,onPendingTrackingSourceHandled:c,templates:l,preview:u,isPreviewing:d,isCommitting:p,onPreview:m,onCommit:h,publishGuard:g}){let[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(()=>dg(t)),[x,S]=(0,Q.useState)(null),C=(0,Q.useRef)(null),w=(0,Q.useRef)(null),T=$s(e,t),E=(0,Q.useMemo)(()=>xg(e.tracked,t,e.mode),[t,e.mode,e.tracked]),D=ws({rows:E,getSearchText:e=>`${e.queryText} ${e.provenance?.source??`legacy`} ${e.assignments.map(e=>e.queryClass??`unknown`).join(` `)}`});(0,Q.useEffect)(()=>{if(T)return;if(!i){w.current=null;return}let n=`${i}:${Cg(t)}`;if(w.current===n)return;let r=e.tracked.find(e=>e.queryId===i);r&&(w.current=n,v({kind:`edit`,row:r,audience:e.mode===`advanced`?vg(t):void 0,scopeLabel:yg(t,e)}),b(fg(r,t)),S(null))},[t,i,T,e]),(0,Q.useEffect)(()=>{if(T||!o)return;let e=dg(o.trackingSelection??t);v({kind:`add`}),b(o.source===`research`?{...e,source:`research`,researchRunQueryId:o.researchRunQueryId}:{...e,source:`discovery`,discoveryProbeId:o.discoveryProbeId}),S(null),c()},[c,o,t,T]),(0,Q.useEffect)(()=>{T&&(v(null),S(null),i!==void 0&&a?.(void 0))},[a,i,T]),(0,Q.useEffect)(()=>{if(!_||_.kind===`remove`)return;let e=C.current;e&&(e.scrollIntoView?.({block:`start`}),e.focus({preventScroll:!0}))},[_]);function O(e=`manual`){v({kind:`add`}),b({...dg(t),source:e}),S(null),a?.(void 0)}function k(n){w.current=`${n.queryId}:${Cg(t)}`,v({kind:`edit`,row:n,audience:e.mode===`advanced`?vg(t):void 0,scopeLabel:yg(t,e)}),b(fg(n,t)),S(null),a?.(n.queryId)}function A(n){w.current=`${n.queryId}:${Cg(t)}`,v({kind:`remove`,row:n,audience:e.mode===`advanced`?vg(t):void 0,scopeLabel:yg(t,e)}),S(null),a?.(n.queryId)}function j(){v(null),S(null),a?.(void 0)}let M=_?pg(_,y,e):null,N=_!==null&&_.kind===`add`&&e.mode===`advanced`&&!gg(y),P=M!==null&&(!N||y.contexts.length>0)&&!d;return T?(0,$.jsx)(`div`,{className:`query-tracking-workspace space-y-4`,children:(0,$.jsxs)(`section`,{"aria-label":`Tracked queries`,className:`py-4 text-label-14 text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`This saved `,t.measurementScope,` filter is unavailable in the current measurement.`]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>r?.({measurementScope:`project`,measurementScopeKey:void 0}),children:`Show whole site`})]})}):(0,$.jsxs)(`div`,{className:`query-tracking-workspace space-y-4`,children:[(0,$.jsxs)(`section`,{"aria-label":`Tracked queries`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end gap-3`,children:[e.mode===`advanced`?(0,$.jsx)(Sg,{selection:t,onSelectionChange:r}):null,(0,$.jsx)(Os,{value:D.query,onChange:D.setQuery,label:`Filter tracked queries`,placeholder:`Search tracked queries`,className:`min-w-64 flex-[2]`}),!Y()&&(0,$.jsxs)(hs,{type:`button`,size:`sm`,onClick:()=>O(),children:[(0,$.jsx)(n,{"aria-hidden":`true`,size:14}),`Add query`]})]}),(0,$.jsxs)(`p`,{className:`mt-2 text-copy-13 text-secondary`,children:[D.totalRows.toLocaleString(`en-US`),` saved query `,D.totalRows===1?`record`:`records`,` in this view. Each record can have more than one property, group, or market assignment.`]}),t.measurementScope===`group`?(0,$.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.active?null:(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-caution`,children:`No published measurement yet.`}),D.rows.length===0?(0,$.jsx)(`p`,{className:`mt-5 text-copy-14 text-muted`,children:D.hasQuery?`No tracked queries match that search.`:`No tracked queries in this scope yet.`}):(0,$.jsx)(`div`,{className:`mt-5 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table measurement-responsive-table min-w-[760px] table-auto`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Query`}),(0,$.jsx)(`th`,{children:`Scope`}),e.mode===`advanced`?(0,$.jsx)(`th`,{children:`Class`}):null,(0,$.jsx)(`th`,{children:`Source`}),(0,$.jsx)(`th`,{children:`Measurement`}),(0,$.jsx)(`th`,{className:`measurement-table-actions`,children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Actions`})})]})}),(0,$.jsx)(`tbody`,{children:D.rows.map(n=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tracking-query-cell break-words text-label-14-strong text-heading`,children:n.queryText}),(0,$.jsx)(`td`,{className:`tracking-scope-cell text-secondary`,children:(0,$.jsx)(Eg,{row:n,workspace:e,selection:t})}),e.mode===`advanced`?(0,$.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,$.jsx)(Og,{row:n})}):null,(0,$.jsx)(`td`,{className:`whitespace-nowrap text-secondary`,children:wg(n)}),(0,$.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,$.jsx)(kg,{row:n,outsidePlan:e.mode===`advanced`&&n.assignments.length===0})}),(0,$.jsx)(`td`,{className:`measurement-table-actions whitespace-nowrap text-right`,children:!Y()&&(0,$.jsxs)(`div`,{className:`tracking-row-actions flex min-w-max justify-end gap-2`,children:[(0,$.jsxs)(hs,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Edit ${n.queryText}`,onClick:()=>k(n),children:[(0,$.jsx)(s,{"aria-hidden":`true`,size:13}),` Edit`]}),(0,$.jsxs)(hs,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Remove ${n.queryText}`,onClick:()=>A(n),children:[(0,$.jsx)(f,{"aria-hidden":`true`,size:13}),` Remove`]})]})})]},n.queryId))})]})}),(0,$.jsx)(Ss,{page:D.page,pageSize:D.pageSize,visibleRows:D.rows.length,totalRows:D.totalRows,itemLabel:`queries`,onPageChange:D.setPage})]}),_&&!Y()&&(0,$.jsx)(Ag,{workspace:e,templates:l,action:_,draft:y,onDraftChange:e=>{b(e),S(null)},onClose:j,canReview:P,isPreviewing:d,editorHeadingRef:C,onReview:()=>{M&&(S(M),m(M))}}),u&&x&&_&&(0,$.jsx)(Bg,{preview:u,workspace:e,isCommitting:p,sweepActive:g?.sweepActive??!1,onConfirm:()=>{h({...x,expectedWorkspaceVersion:u.workspaceVersion,previewToken:u.previewToken,reviewedAt:u.reviewedAt})}})]})}function dg(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 fg(e,t){return{...dg(t),text:e.queryText,queryClass:`keep`}}function pg(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=mg(t);if(!i||_g(t)||r&&!t.wholeSite&&t.targetKeys.length+t.groupKeys.length+t.marketKeys.length===0)return null;let a=r?hg(t,n):void 0;return{additions:[{input:i,...a?{audience:a}:{},...r&&!gg(t)&&t.contexts.length>0?{contexts:t.contexts}:{},...r&&t.queryClass!==`auto`&&t.queryClass!==`keep`?{queryClass:t.queryClass}:{}}],removals:[]}}function mg(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 hg(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 gg(e){return e.marketKeys.length>0&&e.targetKeys.length===0&&e.groupKeys.length===0}function _g(e){return e.source===`template`&&e.template.includes(`{market}`)&&(e.wholeSite||e.marketKeys.length===0)}function vg(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 yg(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 bg(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 xg(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=>bg(e,t)))}function Sg({selection:e,onSelectionChange:t}){return(0,$.jsxs)(`label`,{className:`min-w-40 flex-1`,children:[(0,$.jsx)(`span`,{className:`mb-1 block text-label-12-strong text-secondary`,children:`Query type`}),(0,$.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,$.jsx)(`option`,{value:`all`,children:`All query types`}),(0,$.jsx)(`option`,{value:`non-brand`,children:`Non-brand`}),(0,$.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,$.jsx)(`option`,{value:`unknown`,children:`Unclassified`})]})]})}function Cg(e){return e.measurementScopeKey&&e.measurementScope!==`project`?`${e.measurementScope}:${e.measurementScopeKey}`:`project`}function wg(e){switch(e.provenance?.source){case`manual`:return`Manual`;case`template`:return`Template`;case`research`:return`Saved research`;case`discovery`:return`Discovery`;default:return`Legacy`}}function Tg(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=>bg(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 Eg({row:e,workspace:t,selection:n}){let r=Dg(e,t,n);return(0,$.jsxs)(`details`,{className:`group min-w-48`,children:[(0,$.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:Tg(e,t,n)}),(0,$.jsxs)(`div`,{className:`mt-2 material-base p-2 text-label-12 text-secondary`,children:[(0,$.jsx)(`p`,{className:`text-copy-13-strong text-strong`,children:`Assigned relationships`}),(0,$.jsx)(`ul`,{className:`mt-1 list-disc space-y-1 pl-4`,children:r.map(e=>(0,$.jsx)(`li`,{children:e},e))})]})]})}function Dg(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=>bg(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 Og({row:e}){let t=[...new Set(e.assignments.map(e=>e.queryClass??`unknown`))],n=t.join(`, `);return(0,$.jsx)(J,{tone:t.includes(`unknown`)?`caution`:`neutral`,children:n||`Unknown`})}function kg({row:e,outsidePlan:t=!1}){return t?(0,$.jsx)(J,{tone:`neutral`,children:`Not in current plan`}):e.state===`tracked`?(0,$.jsx)(J,{tone:`positive`,children:`Measured`}):(0,$.jsx)(J,{tone:`caution`,children:`Awaiting check`})}function Ag({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;return n.kind===`remove`?(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{children:`Remove query`}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[`Remove “`,n.row.queryText,`” from future tracking?`]}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:`All assignments will be removed.`,` Earlier results stay unchanged.`]})]})}),(0,$.jsx)(zg,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):n.kind===`edit`?(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline gap-4`,children:[(0,$.jsx)(`h3`,{ref:c,tabIndex:-1,children:`Edit query`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:a,children:`Cancel`})]}),(0,$.jsxs)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:[n.audience?`Changes apply only to assignments in ${n.scopeLabel}.`:`Changes apply to every assignment of this query.`,` Earlier results stay unchanged.`]}),(0,$.jsxs)(`div`,{className:`mt-4 max-w-2xl space-y-4`,children:[(0,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-text`,children:[(0,$.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Query text`}),(0,$.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,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-class`,children:[(0,$.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Classification`}),(0,$.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,$.jsx)(`option`,{value:`keep`,children:`Keep existing classifications`}),(0,$.jsx)(`option`,{value:`auto`,children:`Automatic`}),(0,$.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,$.jsx)(`option`,{value:`non-brand`,children:`Non-brand`})]})]}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Existing locations and engines are preserved. Use Add query to create assignments in another scope.`})]}),(0,$.jsx)(zg,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]}):(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline gap-4`,children:[(0,$.jsx)(`h3`,{ref:c,tabIndex:-1,children:`Add query`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:a,children:`Cancel`})]}),(0,$.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,$.jsxs)(`div`,{className:`space-y-4`,children:[r.source===`manual`?(0,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-text`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-secondary`,children:`Question`}),(0,$.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,$.jsx)(jg,{templates:t,advanced:e.mode===`advanced`,draft:r,onDraftChange:i}):null,r.source===`research`?(0,$.jsx)(Mg,{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,$.jsx)(Mg,{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,(0,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-source`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-secondary`,children:`Query source`}),(0,$.jsxs)(`select`,{id:`tracking-query-source`,"aria-describedby":u?void 0:`tracking-query-source-no-templates`,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,$.jsx)(`option`,{value:`manual`,children:`Write a question`}),u?(0,$.jsx)(`option`,{value:`template`,children:`Saved template`}):null,(0,$.jsxs)(`option`,{value:`research`,disabled:e.savedSources.research.length===0,children:[`Saved research`,e.savedSources.research.length===0?` (none available)`:``]}),(0,$.jsxs)(`option`,{value:`discovery`,disabled:e.savedSources.discovery.length===0,children:[`Discovery result`,e.savedSources.discovery.length===0?` (none available)`:``]})]})]}),u?null:(0,$.jsx)(`p`,{id:`tracking-query-source-no-templates`,className:`text-copy-14 text-secondary`,children:`No saved templates are set up for this portfolio. Write a question, or use saved research or a discovery result.`})]}),e.mode===`advanced`?(0,$.jsx)(Rg,{workspace:e,draft:r,onDraftChange:i}):null]}),e.mode===`advanced`&&!gg(r)?(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(Lg,{workspace:e,draft:r,onDraftChange:i})}):null,(0,$.jsxs)(`details`,{className:`mt-4 border-t border-default text-label-14 text-secondary`,children:[(0,$.jsx)(`summary`,{className:`min-h-11 cursor-pointer py-3`,children:`Measurement options`}),(0,$.jsx)(`div`,{className:`grid gap-4 pb-3 sm:grid-cols-2`,children:e.mode===`advanced`?(0,$.jsxs)(`div`,{className:`block`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,htmlFor:`tracking-query-class`,children:`Classification`}),(0,$.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,$.jsx)(`option`,{value:`auto`,children:`Automatic`}),(0,$.jsx)(`option`,{value:`branded`,children:`Branded`}),(0,$.jsx)(`option`,{value:`non-brand`,children:`Non-brand`})]})]}):(0,$.jsxs)(`div`,{className:`material-base px-3 py-2`,children:[(0,$.jsx)(`p`,{className:`text-copy-13-strong text-secondary`,children:`Classification`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-strong`,children:`Automatic`})]})})]}),r.source===`research`&&(0,$.jsx)(`p`,{className:`mt-4 material-base px-3 py-2 text-copy-14 text-secondary`,children:`Only the saved query is added.`}),(0,$.jsx)(zg,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]})}function jg({templates:e,advanced:t,draft:n,onDraftChange:r}){return(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-template-source`,children:[(0,$.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Saved template`}),(0,$.jsxs)(`select`,{id:`tracking-template-source`,"aria-describedby":_g(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,$.jsx)(`option`,{value:``,children:`Choose a template`}),e.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),n.template?(0,$.jsx)(`span`,{className:`mt-1 block text-label-12 text-muted`,children:n.template}):null]}),_g(n)?(0,$.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 location alone does not select a market.`:`This template needs a market, and this project has no markets. Write a question instead.`}):null]})}function Mg({id:e,label:t,value:n,options:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`block`,htmlFor:e,children:[(0,$.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:t}),(0,$.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,$.jsx)(`option`,{value:``,children:`Choose a saved query`}),r.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.label,` · `,e.detail]},e.id))]})]})}function Ng(e){return{providers:[...e.providers],models:{...e.models},location:e.location?.label??null}}function Pg(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 Fg(e){return[...new Map(e.map(e=>[Pg(e),e])).values()]}function Ig(e){let t=e.providers.map(t=>{let n=e.models[t];return n?`${t} (${n})`:t}).join(`, `);return`${e.location??`No location`} · ${t}`}function Lg({workspace:e,draft:t,onDraftChange:n}){let r=(0,Q.useMemo)(()=>Fg([...e.defaultContexts.map(Ng),...t.contexts]),[t.contexts,e.defaultContexts]),i=t.contexts.length===1?Pg(t.contexts[0]):t.contexts.length>1?`__existing__`:``;return(0,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-context`,children:[(0,$.jsx)(`span`,{className:`text-label-12-strong text-secondary`,children:`Location and engines`}),(0,$.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=>Pg(t)===e.target.value),a=e.target.value===`__existing__`?t.contexts:i?[i]:[];n({...t,contexts:a})},children:[(0,$.jsx)(`option`,{value:``,children:`Choose a location and engines`}),t.contexts.length>1?(0,$.jsxs)(`option`,{value:`__existing__`,children:[`Keep `,t.contexts.length,` existing contexts`]}):null,r.map(e=>(0,$.jsx)(`option`,{value:Pg(e),children:Ig(e)},Pg(e)))]}),(0,$.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 Rg({workspace:e,draft:t,onDraftChange:n}){let{canWrite:r}=qn(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(()=>t.wholeSite||t.targetKeys.length!==1||t.groupKeys.length>0||t.marketKeys.length>0),c=(0,Q.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,$.jsxs)(`fieldset`,{className:`self-start material-base p-3`,children:[(0,$.jsx)(`legend`,{className:`px-1 text-label-12-strong text-secondary`,children:`Apply to`}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`p`,{className:`text-copy-14 text-strong`,children:[`Property: `,n?.label??t.targetKeys[0]]}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Change tracking destination`,onClick:()=>s(!0),children:`Change`})]})]})}return(0,$.jsxs)(`fieldset`,{className:`material-base p-3`,children:[(0,$.jsx)(`legend`,{className:`px-1 text-label-12-strong text-secondary`,children:`Apply to`}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose where this question should be tracked.`}),r?(0,$.jsxs)(`label`,{className:`mt-3 flex min-h-9 items-center gap-2 rounded px-1 text-label-14 text-strong`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.wholeSite,onChange:e=>{n({...t,wholeSite:e.target.checked,targetKeys:[],groupKeys:[],marketKeys:[]})}}),`Every location (`,e.targets.length,`)`]}):null,!t.wholeSite&&!d?(0,$.jsx)(`p`,{role:`status`,className:`mt-2 text-copy-14 text-caution`,children:`Choose at least one location, group, or market.`}):null,(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Group: properties grouped together. Market: search context.`}),(0,$.jsx)(Os,{value:i,onChange:a,label:`Filter assignments`,placeholder:`Search Properties, Groups, Markets`,className:`mt-3`}),(0,$.jsx)(`div`,{className:`mt-3 max-h-64 space-y-1 overflow-y-auto pr-1`,children:u.length===0?(0,$.jsx)(`p`,{className:`px-1 py-2 text-copy-14 text-muted`,children:`No assignment matches that search.`}):u.map(e=>(0,$.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,$.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,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.label}),(0,$.jsx)(`span`,{className:`text-label-12 text-muted`,children:e.detail})]},`${e.kind}:${e.key}`))})]})}function zg({canReview:e,isPreviewing:t,onCancel:n,onReview:r}){return(0,$.jsxs)(`div`,{className:`mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4`,children:[(0,$.jsx)(hs,{type:`button`,size:`sm`,disabled:!e,onClick:r,children:t?`Reviewing…`:`Review changes`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:n,children:`Cancel`}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Publishing does not run a check.`})]})}function Bg({preview:e,workspace:t,isCommitting:n,sweepActive:r,onConfirm:i}){let a=(0,Q.useRef)(null);(0,Q.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. Location 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,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{ref:a,tabIndex:-1,children:o?`Confirm tracked query changes`:`No tracking changes`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-strong`,children:Vg(e)}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:s})]}),(0,$.jsx)(J,{tone:o?`caution`:`neutral`,children:o?`Ready to confirm`:`No-op`})]}),c.length>0?(0,$.jsx)(`div`,{className:`mt-4 space-y-4`,children:c.map(n=>(0,$.jsx)(Hg,{label:n.label,rows:n.rows,workspace:t,tracked:e.tracked},n.label))}):null,e.diff.unchanged.length>0?(0,$.jsxs)(`details`,{className:`mt-4 border-t border-default pt-2 text-label-14 text-secondary`,children:[(0,$.jsxs)(`summary`,{className:`min-h-11 cursor-pointer py-3`,children:[e.diff.unchanged.length,` unchanged `,e.diff.unchanged.length===1?`query`:`queries`]}),(0,$.jsx)(Hg,{label:`Unchanged`,rows:e.diff.unchanged,workspace:t,tracked:e.tracked})]}):null,(0,$.jsxs)(`div`,{className:`mt-5 flex flex-wrap items-center gap-3 border-t border-default pt-4`,children:[(0,$.jsx)(hs,{type:`button`,size:`sm`,disabled:!o||n||r,onClick:i,children:n?`Confirming…`:`Confirm changes`}),o&&r?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`A check is queued or running. Publish after it finishes.`}):null]})]})}function Vg(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 Hg({label:e,rows:t,workspace:n,tracked:r}){return(0,$.jsxs)(`section`,{"aria-label":`${e} queries`,children:[(0,$.jsxs)(`p`,{className:`text-copy-13-strong text-secondary`,children:[t.length,` `,e.toLocaleLowerCase(),t.length===1?``:`s`]}),(0,$.jsx)(`ul`,{className:`mt-2 divide-y divide-default`,children:t.map(t=>(0,$.jsxs)(`li`,{className:`py-2 text-label-14`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:t.queryText}),(0,$.jsx)(`p`,{className:`mt-1 text-secondary`,children:e===`Removed`?`${t.assignmentCount} ${t.assignmentCount===1?`assignment`:`assignments`} removed`:Wg(t,r,n)}),e===`Added`||e===`Reused`?(0,$.jsx)(Ug,{row:r.find(e=>e.queryId===t.queryId),workspace:n}):null]},`${e}:${t.queryId}`))})]})}function Ug({row:e,workspace:t}){if(!e?.assignments.length)return null;let n=new Set(e.assignments.map(e=>e.targetKey)).size;return(0,$.jsxs)(`details`,{className:`mt-2 text-secondary`,children:[(0,$.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,$.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=>Ig(Ng(e))).join(`; `);return(0,$.jsx)(`li`,{children:[r,i,a].filter(Boolean).join(` · `)},`${e.targetKey}:${n}`)})})]})}function Wg(e,t,n){let r=t.find(t=>t.queryId===e.queryId);if(!r)return`${e.assignmentCount} ${e.assignmentCount===1?`assignment`:`assignments`}`;let i=Fg(r.assignments.flatMap(e=>e.contexts).map(Ng)),a=i.length===1?Ig(i[0]):i.length>1?`${i.length} contexts`:null;return[Tg(r,n),a].filter(e=>e!==null).join(` · `)}function Gg({projectName:e,selection:t={measurementScope:`project`,queryClass:`all`},onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s}){let c=S(),[l,u]=(0,Q.useState)(null),d=w({...Yr({client:K,path:{name:e}})}),f=w({...Bi({client:K,path:{name:e}}),staleTime:6e4}),p=C({...zr(),onSuccess:e=>u(e),onError:async t=>{u(null),await c.invalidateQueries({queryKey:dr({client:K,path:{name:e}})}),Xn({title:`Could not review tracking changes`,detail:t instanceof Error?t.message:`Update the draft and review it again.`,tone:`negative`})}}),m=C({...pr(),onSuccess:async t=>{u(null),i?.(void 0),await nr(c,e),Xn({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 nr(c,e),Xn({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,$.jsx)(Z,{className:`surface-card`,children:(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Loading tracked queries…`})}):d.isError||!d.data?(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-negative`,children:`Could not load tracked queries.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void d.refetch(),children:`Try again`})]}):(0,$.jsx)(ug,{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:K,path:{name:e},body:{...t,expectedWorkspaceVersion:d.data.workspaceVersion}})},onCommit:t=>m.mutate({client:K,path:{name:e},body:t})})}function Kg({projectName:e,onReviewDiscoveryProbe:t}){let n=S(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(`100`),l=w({...Xr({client:K,path:{name:e},query:{limit:`10`}}),refetchInterval:e=>e.state.data?.some(e=>og.has(e.status))?3e3:!1}),u=l.data??[];(0,Q.useEffect)(()=>{!r&&u[0]&&i(u[0].id)},[r,u]);let f=u.find(e=>e.id===r)??null,p=w({...$i({client:K,path:{name:e,id:r??``}}),enabled:!!r,refetchInterval:f&&og.has(f.status)?3e3:!1}),m=p.data??null,h=C({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),gn(e,t)},onSuccess:async t=>{i(t.sessionId),o(``),await $g(n,e,t.sessionId),Xn({title:`Discovery started`,detail:`Run ${Qg(t.sessionId)} is testing questions your customers might ask.`,tone:`neutral`,dedupeKey:`discovery:start:${t.sessionId}`,dedupeMode:`replace`})},onError:e=>{Xn({title:`Discovery failed to start`,detail:e instanceof Error?e.message:`Could not start discovery.`,tone:`negative`})}}),g=m??f,_=(0,Q.useMemo)(()=>(m?.probes??[]).slice(0,30),[m?.probes]);async function v(){try{let t=await l.refetch();if(t.error)throw t.error;let n=t.data?.length??0;Xn({title:`Discovery sessions refreshed`,detail:`${n} recent session${n===1?``:`s`} loaded.`,tone:`positive`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}catch(t){Xn({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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Step 1`}),(0,$.jsx)(`h2`,{children:`Generate and check questions`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-3xl text-copy-14 text-secondary`,children:Y()?`Generate customer questions and check whether your site is already visible.`:`Generate customer questions, check current visibility, then choose what to track.`})]}),(0,$.jsxs)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:l.isFetching,onClick:()=>void v(),children:[(0,$.jsx)(d,{className:`size-3.5 ${l.isFetching?`animate-spin`:``}`,"aria-hidden":`true`}),`Refresh`]})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]`,children:[(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Step 1`}),(0,$.jsx)(`h3`,{children:`Describe your customer`})]}),(0,$.jsx)(J,{tone:`neutral`,children:`Runs on Gemini`})]}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Who is your ideal customer?`}),(0,$.jsx)(`textarea`,{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. Leave blank to use the customer profile saved on this project.`,value:a,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`How many questions to test`}),(0,$.jsx)(`input`,{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)}),(0,$.jsx)(`span`,{className:`mt-1 block text-label-14 text-secondary`,children:`More questions means broader coverage but a longer run. 100 is a good default.`})]}),!Y()&&(0,$.jsxs)(hs,{type:`button`,size:`sm`,disabled:h.isPending,onClick:()=>h.mutate(),children:[(0,$.jsx)(y,{size:14}),h.isPending?`Starting…`:`Find queries`]})]})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`History`}),(0,$.jsx)(`h3`,{children:`Recent runs`})]}),l.isFetching&&(0,$.jsx)(J,{tone:`neutral`,children:`Loading`})]}),u.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No discovery runs yet. Describe your customer above to start your first one.`}):(0,$.jsx)(`div`,{className:`space-y-2`,children:u.map(e=>(0,$.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,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:Qg(e.id)}),(0,$.jsx)(J,{tone:Jg(e.status),children:e.status})]}),(0,$.jsxs)(`div`,{className:`mt-2 grid grid-cols-3 gap-2 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Cited queries `,e.citedCount??0]}),(0,$.jsxs)(`span`,{children:[`Worth tracking `,e.aspirationalCount??0]}),(0,$.jsxs)(`span`,{children:[`Skip `,e.wastedCount??0]})]})]},e.id))})]})]}),(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Run detail`}),(0,$.jsx)(`h3`,{children:g?Qg(g.id):`No run selected`})]}),g&&(0,$.jsx)(J,{tone:Jg(g.status),children:g.status})]}),g?(0,$.jsxs)(`div`,{className:`space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-4`,children:[(0,$.jsx)(qg,{label:`Questions tested`,value:g.probeCount??0}),(0,$.jsx)(qg,{label:`Cited queries`,value:g.citedCount??0,tone:`positive`}),(0,$.jsx)(qg,{label:`Worth tracking`,value:g.aspirationalCount??0,tone:`caution`}),(0,$.jsx)(qg,{label:`Skip`,value:g.wastedCount??0,tone:`negative`})]}),g.error&&(0,$.jsx)(`div`,{className:`rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:g.error}),g.warning&&(0,$.jsx)(`div`,{className:`rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-label-14 text-caution`,children:g.warning}),g.icpDescription&&(0,$.jsxs)(`div`,{className:`material-base px-3 py-2`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:`Customer profile`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-neutral`,children:g.icpDescription})]}),g.competitorMap.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-copy-14-strong text-secondary`,children:`Sites that keep getting cited`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:g.competitorMap.slice(0,8).map(e=>(0,$.jsxs)(`span`,{className:`rounded-md border border-default bg-bg px-2 py-1 text-label-12 text-neutral`,children:[e.domain,` `,(0,$.jsx)(`span`,{className:`text-muted`,children:e.hits})]},e.domain))})]})]}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Start a run above, or pick one from Recent runs to see its progress.`})]}),g?.status===`completed`&&(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Step 2`}),(0,$.jsx)(`h3`,{children:`Review a discovery question for tracking`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-3xl text-copy-14 text-secondary`,children:`Choose a Cited query or Worth tracking result below. Tracking opens with the saved discovery source, where you choose its scope and review the exact next-check change.`})]})}),(0,$.jsx)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:`Discovery remains research. This review does not add competitors or start a check.`})]}),(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`All results`}),(0,$.jsx)(`h3`,{children:`Every question we tested`})]}),p.isFetching&&(0,$.jsx)(J,{tone:`neutral`,children:`Loading`})]}),_.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:`Results show up here once the run starts testing questions.`}):(0,$.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Question`}),(0,$.jsx)(`th`,{children:`Result`}),(0,$.jsx)(`th`,{children:`Sites cited`}),(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Tracking review`})})]})}),(0,$.jsx)(`tbody`,{children:_.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.query}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:Yg(e.bucket),children:Zg(e.bucket)})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.citedDomains.length>0?e.citedDomains.slice(0,3).join(`, `):`-`}),(0,$.jsx)(`td`,{className:`whitespace-nowrap text-right`,children:!Y()&&t&&(e.bucket===`cited`||e.bucket===`aspirational`)&&(0,$.jsx)(hs,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>t(e.id),children:`Review for tracking`})})]},e.id))})]})})]})]})]})]})}function qg({label:e,value:t,tone:n=`neutral`}){return(0,$.jsxs)(`div`,{className:`material-base px-4 py-3`,children:[(0,$.jsx)(`p`,{className:`text-label-12 normal-case text-muted`,children:e}),(0,$.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 Jg(e){return e===`completed`?`positive`:e===`failed`?`negative`:og.has(e)?`caution`:`neutral`}function Yg(e){return e===`cited`?`positive`:e===`aspirational`?`caution`:e===`wasted-surface`?`negative`:`neutral`}var Xg={cited:`Cited queries`,aspirational:`Worth tracking`,"wasted-surface":`Skip`};function Zg(e){return e?Xg[e]:`Not classified`}function Qg(e){return e.length>8?e.slice(0,8):e}async function $g(e,t,n){await Promise.all([Zn(e,`discovery`),e.invalidateQueries({queryKey:xi({client:K})})])}var e_=4e3,t_={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 n_(e){return`canonry:embed-query-draft:${e}`}function r_(e){try{return window.sessionStorage.getItem(n_(e))??``}catch{return``}}function i_(e,t){try{t?window.sessionStorage.setItem(n_(e),t):window.sessionStorage.removeItem(n_(e))}catch{}}function a_(e,t){return e.trim().replace(/\s+/g,` `).toLocaleLowerCase()===t.trim().replace(/\s+/g,` `).toLocaleLowerCase()}function o_({projectName:e,limit:t}){let n=S(),r=Yr({client:K,path:{name:e}}),i=w(r),[a,o]=(0,Q.useState)(()=>r_(e)),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(null),d=(0,Q.useRef)(null),p=(0,Q.useRef)(new Map),m=(0,Q.useRef)(null),h=i.data?.tracked??[],g=i.data?.mode===`simple`,_=h.length>=t;(0,Q.useEffect)(()=>{let e=m.current;if(e===null||s!==null)return;m.current=null;let t=h[Math.min(e,h.length-1)],n=t?p.current.get(t.queryId):void 0;n?n.focus():d.current?.focus()},[s,h]);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 Dn(()=>ke({client:K,path:{name:e},body:{...t,expectedWorkspaceVersion:a}}));return n.diff.noOp?`unchanged`:(await Dn(()=>ve({client:K,path:{name:e},body:{...t,expectedWorkspaceVersion:n.workspaceVersion,previewToken:n.previewToken,reviewedAt:n.reviewedAt}})),`saved`)}catch(e){if(e instanceof ht&&e.code===`EMBED_QUERY_LIMIT`)return`limit`;if(i===0&&e instanceof ht&&e.code===`QUERY_TRACKING_PREVIEW_STALE`)continue;throw e}}throw Error(`The query list kept changing.`)}async function y(r,i){if(h.some(e=>a_(e.queryText,r)))return u({kind:`error`,text:t_.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:t_.duplicate}),!1):i===`limit`?(u({kind:`error`,text:t_.limit(t)}),!1):(await nr(n,e),u({kind:`added`,query:r}),!0)}catch{return u({kind:`error`,text:t_.failed}),!1}finally{c(null)}}async function b(t){t.preventDefault();let n=a.trim();n&&s===null&&!_&&await y(n,`add`)&&(o(``),i_(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 nr(n,e),m.current=r,u({kind:`removed`,query:t.queryText})}catch{u({kind:`error`,text:t_.failed})}finally{c(null)}}}async function C(e){s===null&&await y(e,`undo`)&&d.current?.focus()}if(i.isLoading)return(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,role:`status`,children:t_.loading});if(i.isError||!i.data)return(0,$.jsxs)(`div`,{role:`alert`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-negative`,children:t_.loadFailed}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void i.refetch(),children:t_.retry})]});let T=l?.kind===`error`?l.text:null,E=`embed-query-line`;return(0,$.jsxs)(`section`,{"aria-labelledby":`embed-queries-heading`,children:[(0,$.jsx)(`header`,{children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{id:`embed-queries-heading`,className:`text-heading-20 text-heading`,children:t_.heading}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[(0,$.jsx)(`span`,{className:`text-copy-14-strong text-strong`,children:t_.count(h.length,t)}),` · `,g?t_.nextCheck:t_.agencyManaged]})]})}),g?(0,$.jsxs)(`form`,{className:`mt-4 flex max-w-2xl gap-2`,onSubmit:e=>void b(e),"aria-busy":s===`add`,children:[(0,$.jsx)(`label`,{htmlFor:`embed-query-input`,className:`sr-only`,children:t_.inputLabel}),(0,$.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:t_.placeholder,maxLength:e_,value:a,readOnly:_||s!==null,"aria-disabled":_||void 0,"aria-invalid":T?!0:void 0,"aria-describedby":E,onChange:t=>{o(t.target.value),i_(e,t.target.value),l?.kind===`error`&&u(null)}}),(0,$.jsx)(q,{type:`submit`,className:`pointer-coarse:min-h-11`,disabled:_||s!==null||!a.trim(),children:s===`add`?t_.adding:t_.add})]}):null,(0,$.jsxs)(`div`,{id:E,className:`mt-2 min-h-5 text-label-14`,children:[T?(0,$.jsx)(`p`,{className:`text-negative`,role:`alert`,children:T}):null,(0,$.jsxs)(`p`,{className:`text-secondary`,role:`status`,children:[l?.kind===`removed`?(0,$.jsxs)($.Fragment,{children:[t_.removed(l.query),` `,(0,$.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||_,onClick:()=>void C(l.query),children:s===`undo`?t_.adding:t_.undo})]}):l?.kind===`added`?(0,$.jsx)(`span`,{className:`sr-only`,children:t_.added(l.query)}):null,g&&_&&!T?(0,$.jsx)(`span`,{className:`block`,children:t_.limit(t)}):null]})]}),h.length===0?(0,$.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:t_.empty}):(0,$.jsx)(`ul`,{className:`mt-4 divide-y divide-default border-y border-default`,"aria-label":`Tracked queries`,children:h.map((e,t)=>{let n=typeof s==`object`&&s?.removing===e.queryId;return(0,$.jsxs)(`li`,{className:`flex items-center justify-between gap-4 py-2`,children:[(0,$.jsx)(`span`,{className:`min-w-0 break-words text-label-14-strong text-heading`,children:e.queryText}),g?(0,$.jsxs)(q,{ref:t=>{t?p.current.set(e.queryId,t):p.current.delete(e.queryId)},type:`button`,variant:`ghost`,size:`sm`,className:`pointer-coarse:min-h-11`,"aria-label":`${t_.remove} ${e.queryText}`,disabled:s!==null,onClick:()=>void x(e,t),children:[(0,$.jsx)(f,{"aria-hidden":`true`,size:13}),n?t_.removing:t_.remove]}):null]},e.queryId)})})]})}function s_({projectName:e}){let[t,n]=(0,Q.useState)(`changes`),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),s=w({...Ii({client:K,path:{name:e},query:{limit:30}}),enabled:t===`health`}),c=w({...mr({client:K,path:{name:e},query:{kind:`answer-visibility`,limit:100}}),enabled:t===`compare`}),l=(c.data??[]).filter(e=>(e.status===`completed`||e.status===`partial`)&&e.trigger!==`probe`).reverse(),u=a??l[0]?.id??``,d=r??l.find(e=>e.id!==u)?.id??``,f=!!(d&&u&&d!==u),p=w({...ei({client:K,path:{name:e},query:{run1:d,run2:u}}),enabled:t===`compare`&&f}),m=s.data??[],h=p.data?.diff.filter(e=>e.changed||e.visibilityChanged)??[];return(0,$.jsxs)(`div`,{className:`mt-6`,children:[(0,$.jsx)(`div`,{className:`filter-row`,role:`tablist`,"aria-label":`Project history views`,children:[[`changes`,`Changes`],[`health`,`Coverage history`],[`compare`,`Compare runs`]].map(([e,r])=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":t===e,className:`filter-chip ${t===e?`filter-chip-active`:``}`,onClick:()=>n(e),children:r},e))}),t===`changes`?(0,$.jsx)(As,{projectName:e}):null,t===`health`?(0,$.jsxs)(`section`,{className:`mt-6`,"aria-labelledby":`coverage-history-heading`,children:[(0,$.jsxs)(`div`,{className:`section-head`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Query evidence`}),(0,$.jsx)(`h2`,{id:`coverage-history-heading`,children:`Mention and citation coverage`}),(0,$.jsx)(`p`,{className:`supporting-copy mt-1`,children:`Independent answer-text mentions and source citations across completed checks.`})]}),s.isLoading?(0,$.jsx)(`p`,{className:`supporting-copy mt-4`,role:`status`,children:`Loading coverage history…`}):null,!s.isLoading&&m.length===0?(0,$.jsxs)(Z,{className:`surface-card empty-card mt-4`,children:[(0,$.jsx)(`h3`,{children:`No coverage history yet`}),(0,$.jsx)(`p`,{children:H()?Ba:`Complete an AI Visibility check to create the first snapshot.`})]}):null,m.length>0?(0,$.jsx)(`div`,{className:`evidence-table-wrap mt-4`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Date`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Mentioned`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Mention coverage`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Cited`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Citation coverage`})]})}),(0,$.jsx)(`tbody`,{children:m.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`whitespace-nowrap tabular-nums text-secondary`,children:new Date(e.createdAt).toLocaleString()}),(0,$.jsxs)(`td`,{className:`text-right tabular-nums text-secondary`,children:[e.mentionedPairs,`/`,e.totalPairs]}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:St(e.overallMentionRate)}),(0,$.jsxs)(`td`,{className:`text-right tabular-nums text-secondary`,children:[e.citedPairs,`/`,e.totalPairs]}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:St(e.overallCitedRate)})]},e.id))})]})}):null]}):null,t===`compare`?(0,$.jsxs)(`section`,{className:`mt-6`,"aria-labelledby":`compare-runs-heading`,children:[(0,$.jsxs)(`div`,{className:`section-head`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Evidence diff`}),(0,$.jsx)(`h2`,{id:`compare-runs-heading`,children:`Compare answer visibility runs`}),(0,$.jsx)(`p`,{className:`supporting-copy mt-1`,children:`See which tracked queries changed mention or citation state between two checks.`})]}),(0,$.jsxs)(`div`,{className:`mt-4 grid gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`text-label-12 text-muted`,children:[`Earlier run`,(0,$.jsx)(`select`,{value:d,onChange:e=>i(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:l.map(e=>(0,$.jsx)(`option`,{value:e.id,children:new Date(e.createdAt).toLocaleString()},e.id))})]}),(0,$.jsxs)(`label`,{className:`text-label-12 text-muted`,children:[`Later run`,(0,$.jsx)(`select`,{value:u,onChange:e=>o(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:l.map(e=>(0,$.jsx)(`option`,{value:e.id,children:new Date(e.createdAt).toLocaleString()},e.id))})]})]}),c.isLoading||p.isLoading?(0,$.jsx)(`p`,{className:`supporting-copy mt-4`,role:`status`,children:`Comparing runs…`}):null,!c.isLoading&&l.length<2?(0,$.jsxs)(Z,{className:`surface-card empty-card mt-4`,children:[(0,$.jsx)(`h3`,{children:`Two completed checks are required`}),(0,$.jsx)(`p`,{children:H()?Ba:`Run another AI Visibility check before comparing historical evidence.`})]}):null,p.data&&h.length===0?(0,$.jsxs)(Z,{className:`surface-card empty-card mt-4`,children:[(0,$.jsx)(`h3`,{children:`No mention or citation changes`}),(0,$.jsx)(`p`,{children:`The selected checks have the same states for every comparable tracked query.`})]}):null,h.length>0?(0,$.jsx)(`div`,{className:`evidence-table-wrap mt-4`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Query`}),(0,$.jsx)(`th`,{children:`Citation`}),(0,$.jsx)(`th`,{children:`Mention`})]})}),(0,$.jsx)(`tbody`,{children:h.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-strong`,children:e.query??`Archived query`}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(J,{tone:e.changed?`caution`:`neutral`,children:[e.run1State??`none`,` → `,e.run2State??`none`]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(J,{tone:e.visibilityChanged?`caution`:`neutral`,children:[e.run1MentionState??`none`,` → `,e.run2MentionState??`none`]})})]},e.queryId??e.query??`unknown`))})]})}):null]}):null]})}var c_={state:`not-connected`,selection:null,snapshotCount:0,evidence:`No stored evidence yet.`,lastSnapshotAt:null},l_={contract:null,assessment:null,googleAds:c_,gtm:c_,snapshots:[]};function u_(e){return e.contractSelectionRequired?`contract-selection-required`:e.assessmentState===`loading`?`assessment-loading`:e.assessmentState===`unavailable`?`assessment-unavailable`:h_(e)?`static-mismatch`:e.assessment?.status??(e.contract?`configured`:`not-configured`)}function d_(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 f_(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 p_(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 m_(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`&&g_(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 h_(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome===`fail`)}function g_(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome!==`pass`)}function __(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 v_(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 y_(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 b_(e){return e.length<=12?e:`…${e.slice(-10)}`}function x_(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 S_(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 C_={"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 w_(e){return e.outcome===`pass`?{label:C_[e.code],tone:`positive`,outcome:`Pass`}:e.outcome===`fail`?{label:C_[e.code],tone:`negative`,outcome:`Fail`}:{label:C_[e.code],tone:`caution`,outcome:`Unknown`}}function T_(e){return e.runtime.productionHosts.length>0?e.runtime.productionHosts.join(`, `):`the declared production site`}function E_(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 D_(e){return e.provider===`google-ads`?`Google Ads`:`Tag Manager`}function O_({label:e,connection:t,changeSelectionLabel:n,onChangeSelection:r,actionPending:i}){let a=__(t.state),o=t.snapshotState===`loading`?`Loading stored snapshots`:t.snapshotState===`unavailable`?`Stored snapshots unavailable`:t.snapshotCount===0?`No stored snapshots`:null;return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:a.tone,children:a.label})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:t.selection??`No selection`}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(`p`,{className:`text-secondary`,children:t.evidence}),o?(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:o}):(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:[t.snapshotCount,` stored `,t.snapshotCount===1?`snapshot`:`snapshots`,t.lastSnapshotAt?`, latest ${Mn(t.lastSnapshotAt)}`:``]}),t.snapshotError?(0,$.jsx)(`p`,{role:`alert`,className:`mt-1 text-copy-14 text-negative`,children:t.snapshotError}):null]}),(0,$.jsx)(`td`,{children:n&&r?(0,$.jsx)(hs,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:r,children:n}):(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Use the next step above`})})]})}var k_=`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.`,A_=`Available once Google Ads and Tag Manager are connected.`,j_=`Check that a conversion is wired the same way in Google Ads and Tag Manager, so the numbers you optimise against are the ones your site actually sends. Canonry only reads the configuration; it never changes or publishes it.`;function M_({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=!o&&!s,p=[{title:`Google Ads`,state:e.googleAds.state,ready:o,summary:e.googleAds.selection,changeLabel:`Change Google Ads account`,onChange:n,action:c?d:f_(e)},{title:`Tag Manager`,state:e.gtm.state,ready:s,summary:e.gtm.selection,changeLabel:`Change Tag Manager container`,onChange:r,action:l?d:p_(e)}],m=o&&s&&!u?m_(e):null;return(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,$.jsx)(`div`,{className:`section-head mb-4`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-1.5`,children:[(0,$.jsx)(`h2`,{id:`conversion-integrity-title`,className:`text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,$.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.`})]}),f?(0,$.jsx)(`p`,{className:`mt-2 max-w-2xl text-copy-14 text-secondary`,children:j_}):null]})}),(0,$.jsxs)(`div`,{className:`max-w-3xl`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3 border-y border-default py-4`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{className:`text-heading-14 text-heading`,children:`Conversion to check`}),(0,$.jsx)(X,{text:k_})]}),m&&t?(0,$.jsx)(hs,{type:`button`,disabled:i,onClick:()=>t(m.id),children:i?`Working…`:m.label}):(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:A_})]}),(0,$.jsx)(`ul`,{className:`flex flex-wrap items-center gap-x-6 gap-y-2 border-b border-default py-3`,children:p.map(e=>{let n=e.ready?{label:`Ready`,tone:`positive`}:__(e.state),r=e.action;return(0,$.jsxs)(`li`,{className:`flex min-w-0 flex-wrap items-center gap-2 text-label-14`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.title}),(0,$.jsx)(J,{tone:n.tone,children:n.label}),e.summary?(0,$.jsx)(`span`,{className:`min-w-0 truncate text-secondary`,children:e.summary}):null,r&&t?r.id===`retry-connection-status`?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):(0,$.jsx)(hs,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):null,e.summary&&e.onChange?(0,$.jsx)(hs,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":e.changeLabel,disabled:i,onClick:e.onChange,children:`Change`}):null]},e.title)})}),a?(0,$.jsx)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:a}):null]})]})}function N_({workspace:e=l_,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=u_(e),m=d_(p),h=m_(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,$.jsx)(M_,{workspace:e,onPrimaryAction:t,onChangeGoogleAdsSelection:u,onChangeGtmSelection:d,actionPending:n,actionError:r}):(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,$.jsx)(`div`,{className:`section-head mb-5`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,$.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,$.jsx)(`p`,{className:`lede mt-2`,children:`Follow one declared website event through Tag Manager, Google Ads, and the evidence Canonry can verify.`})]})}),(0,$.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,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{tone:m.tone,children:m.label}),e.assessment?.evaluatedAt?(0,$.jsxs)(`span`,{className:`text-label-12 text-muted`,children:[`Assessed `,Mn(e.assessment.evaluatedAt)]}):null]}),(0,$.jsx)(`p`,{className:`supporting-copy mt-2 max-w-2xl`,children:m.detail}),e.assessmentEvidenceSnapshots?.length?(0,$.jsxs)(`details`,{className:`inline-disclosure mt-3 max-w-2xl`,children:[(0,$.jsx)(`summary`,{children:`Evidence used for this assessment`}),(0,$.jsx)(`ul`,{className:`mt-3 space-y-2 text-label-14 text-secondary`,children:e.assessmentEvidenceSnapshots.map(e=>(0,$.jsxs)(`li`,{className:`break-words`,children:[D_(e),` `,e.kind,`, captured `,Mn(e.capturedAt),(0,$.jsxs)(`span`,{className:`ml-1 text-label-12-mono text-muted`,children:[`(`,e.id,`)`]})]},e.id))})]}):null]}),(0,$.jsxs)(`div`,{className:`shrink-0 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,$.jsx)(q,{type:`button`,disabled:n||h.id===`waiting-for-integrity`,onClick:()=>t(h.id),children:n?`Working…`:h.label}):(0,$.jsx)(hs,{type:`button`,disabled:n,onClick:()=>t(h.id),children:n?`Working…`:h.label}):h.id===`review-findings`?(0,$.jsx)(q,{asChild:!0,type:`button`,children:(0,$.jsx)(`a`,{href:`#conversion-integrity-findings`,children:`Review findings`})}):p===`runtime-unverified`?(0,$.jsx)(q,{asChild:!0,type:`button`,children:(0,$.jsx)(`a`,{href:`#conversion-integrity-runtime-guidance`,children:`Review runtime verification`})}):null,(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:h.detail}),r?(0,$.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:r}):null]})]}),(0,$.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-contract-title`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Declared conversion`}),(0,$.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,$.jsx)(hs,{type:`button`,variant:`outline`,size:`sm`,disabled:n,onClick:f,children:`Add conversion`}):null]}),i.length>1?(0,$.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,$.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,$.jsx)(`option`,{value:``,children:`Choose a declared conversion`}),i.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}):null,e.contract?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dl`,{className:`grid gap-x-8 gap-y-4 sm:grid-cols-2 xl:grid-cols-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Website event`}),(0,$.jsx)(`dd`,{className:`mt-1 text-label-14-strong text-heading`,children:e.contract.eventName})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Google Ads goal`}),(0,$.jsx)(`dd`,{className:`mt-1 text-label-14 text-secondary`,children:x_(e.contract)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Tag Manager`}),(0,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-label-12-strong normal-case text-muted`,children:`Runtime event fields`}),(0,$.jsx)(`dd`,{className:`mt-1 text-label-14 text-secondary`,children:S_(e.contract)})]})]}),(0,$.jsxs)(`details`,{className:`inline-disclosure mt-5`,children:[(0,$.jsx)(`summary`,{children:`Show declared identifiers`}),(0,$.jsxs)(`dl`,{className:`mt-3 grid gap-x-6 gap-y-3 text-label-14 sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Google Ads customer`}),(0,$.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:b_(e.contract.googleAds.customerId)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Google Ads conversion action`}),(0,$.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:b_(e.contract.googleAds.conversionActionId)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Tag Manager container`}),(0,$.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:b_(e.contract.gtm.containerId)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Tag Manager tag`}),(0,$.jsx)(`dd`,{className:`mt-0.5 font-mono text-secondary`,children:b_(e.contract.gtm.tagId)})]})]})]})]}):(0,$.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,$.jsxs)(`div`,{role:`alert`,className:`mt-4 flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,$.jsx)(`span`,{children:s}),c?(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:c,children:`Retry contracts`}):null]}):null,e.assessmentError?(0,$.jsx)(`p`,{role:`alert`,className:`mt-4 text-copy-14 text-negative`,children:e.assessmentError}):null]}),_.length>0?(0,$.jsxs)(`section`,{id:`conversion-integrity-findings`,tabIndex:-1,className:`page-section-divider`,"aria-labelledby":`conversion-integrity-findings-title`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Assessment findings`}),(0,$.jsx)(`h3`,{id:`conversion-integrity-findings-title`,className:`text-heading-16 text-heading`,children:`Checks to review`})]}),(0,$.jsxs)(J,{tone:y,children:[_.length,` `,_.length===1?`check`:`checks`]})]}),(0,$.jsx)(`ul`,{className:`divide-y divide-default border-y border-default`,children:_.map(e=>{let t=w_(e);return(0,$.jsxs)(`li`,{className:`py-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(`p`,{className:`min-w-0 break-words text-copy-14-strong text-heading`,children:t.label}),(0,$.jsx)(J,{tone:t.tone,children:t.outcome})]}),(0,$.jsxs)(`p`,{className:`mt-1 break-words text-copy-14 text-secondary`,children:[`Related item: `,e.subject]}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13-mono text-muted`,children:[`Diagnostic: `,e.code]}),e.evidenceIds.length>0?(0,$.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,$.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-progression-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{id:`conversion-integrity-progression-title`,className:`text-heading-16 text-heading`,children:`Evidence progression`}),(0,$.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,$.jsx)(`ol`,{className:`divide-y divide-default border-y border-default`,children:[{key:`configured`,title:`Declared`,detail:`The event and provider identifiers are recorded in one project contract.`},{key:`static`,title:`Static configuration`,detail:`Sanitized Google Ads and Tag Manager snapshots are compared with that contract.`},{key:`runtime`,title:`Runtime observation`,detail:`A real browser event, tag firing, and recorded conversion are verified separately.`}].map(e=>{let t=v_(e.key,p);return(0,$.jsxs)(`li`,{className:`grid gap-3 py-3 sm:grid-cols-[minmax(10rem,0.7fr)_minmax(0,1fr)_auto] sm:items-center`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.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,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.title})]}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:e.detail}),(0,$.jsx)(J,{tone:t,children:y_(e.key,p)})]},e.key)})})]}),(0,$.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-connections-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Connection evidence`}),(0,$.jsx)(`h3`,{id:`conversion-integrity-connections-title`,className:`text-heading-16 text-heading`,children:`Google Ads and Tag Manager`})]})}),(0,$.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Google Ads and Tag Manager connection and stored evidence state`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Source`}),(0,$.jsx)(`th`,{scope:`col`,children:`Connection`}),(0,$.jsx)(`th`,{scope:`col`,children:`Selection`}),(0,$.jsx)(`th`,{scope:`col`,children:`Stored evidence`}),(0,$.jsx)(`th`,{scope:`col`,children:`Actions`})]})}),(0,$.jsxs)(`tbody`,{children:[O_({label:`Google Ads`,connection:e.googleAds,...e.googleAds.state===`connected`||e.googleAds.state===`stale`?{changeSelectionLabel:`Change Google Ads account`,onChangeSelection:u}:{},actionPending:n}),O_({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,$.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,$.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:l,children:`Retry evidence`}):null]}),e.snapshots.length>0?(0,$.jsxs)(`section`,{className:`page-section-divider`,"aria-labelledby":`conversion-integrity-snapshots-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Recent observations`}),(0,$.jsx)(`h3`,{id:`conversion-integrity-snapshots-title`,className:`text-heading-16 text-heading`,children:`Latest sanitized snapshots`})]})}),(0,$.jsx)(`div`,{className:`evidence-table-wrap`,children:(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Latest stored Google marketing snapshots`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Source`}),(0,$.jsx)(`th`,{scope:`col`,children:`Observation`}),(0,$.jsx)(`th`,{scope:`col`,children:`Captured`}),(0,$.jsx)(`th`,{scope:`col`,children:`Identifier`})]})}),(0,$.jsx)(`tbody`,{children:e.snapshots.slice(0,5).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.provider===`google-ads`?`Google Ads`:`Google Tag Manager`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.kind}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Mn(e.capturedAt)}),(0,$.jsx)(`td`,{className:`text-label-12-mono text-muted`,children:b_(e.id)})]},e.id))})]})})]}):null,v.length>0?(0,$.jsxs)(`details`,{className:`inline-disclosure mt-8`,children:[(0,$.jsxs)(`summary`,{children:[v.length,` `,v.length===1?`passing check`:`passing checks`,` from the latest assessment`]}),(0,$.jsx)(`div`,{className:`findings-table-wrap mt-3`,children:(0,$.jsxs)(`table`,{className:`findings-table`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Conversion integrity findings`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Check`}),(0,$.jsx)(`th`,{scope:`col`,children:`Result`}),(0,$.jsx)(`th`,{scope:`col`,children:`Subject`})]})}),(0,$.jsx)(`tbody`,{children:v.map(e=>{let t=w_(e);return(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`td`,{className:`text-secondary`,children:[(0,$.jsx)(`p`,{children:t.label}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13-mono text-muted`,children:[`Diagnostic: `,e.code]}),e.evidenceIds.length>0?(0,$.jsxs)(`p`,{className:`mt-1 break-words text-copy-13-mono text-muted`,children:[`Evidence: `,e.evidenceIds.join(`, `)]}):null]}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:t.tone,children:t.outcome})}),(0,$.jsx)(`td`,{className:`break-words text-secondary`,children:e.subject})]},`${e.code}:${e.subject}`)})})]})})]}):null,p===`runtime-unverified`?(0,$.jsxs)(`section`,{id:`conversion-integrity-runtime-guidance`,className:`page-section-divider`,"aria-labelledby":`conversion-integrity-runtime-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Runtime verification`}),(0,$.jsx)(`h3`,{id:`conversion-integrity-runtime-title`,className:`text-heading-16 text-heading`,children:`Runtime verification checklist`})]})}),(0,$.jsxs)(`ol`,{className:`max-w-2xl list-decimal space-y-2 pl-5 text-label-14 text-secondary marker:text-muted`,children:[(0,$.jsxs)(`li`,{children:[`Use a controlled browser session on `,T_(e.contract),` and complete the conversion that emits `,(0,$.jsx)(`span`,{className:`font-mono text-heading`,children:e.contract.eventName}),`.`]}),(0,$.jsxs)(`li`,{children:[`In Tag Manager preview or debugging, confirm tag `,(0,$.jsx)(`span`,{className:`font-mono text-heading`,children:b_(e.contract.gtm.tagId)}),` fires with `,E_(e.contract),`.`]}),(0,$.jsxs)(`li`,{children:[`Confirm Google Ads records the matching conversion action `,(0,$.jsx)(`span`,{className:`font-mono text-heading`,children:b_(e.contract.googleAds.conversionActionId)}),`. Do not change the account or publish a Tag Manager version just to verify it.`]})]})]}):null]})}var P_=3e4,F_={name:``,eventName:``,conversionActionId:``,conversionId:``,conversionLabel:``,campaignIds:``,tagId:``,triggerIds:``,variableIds:``,productionHosts:``,requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},I_=`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`,L_=`text-label-14-strong text-secondary`;function R_(e,t,n,r){return n?{snapshotCount:e,snapshotState:`unavailable`,snapshotError:Bs(r)}:t?{snapshotCount:e,snapshotState:`loading`}:{snapshotCount:e}}function z_(e){return[...new Set(e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function B_(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 V_(e,t,n){let r=[`Container ${e}`,`account ${t}`];return n&&r.push(`workspace ${n}`),r.join(` · `)}function H_(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:V_(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 U_(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:z_(e.campaignIds),requireBiddableGoal:e.requireBiddableGoal,requirePrimaryAction:e.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:e.tagId.trim(),triggerIds:z_(e.triggerIds),variableIds:z_(e.variableIds)},runtime:{verificationRequired:e.verificationRequired,requireTransactionId:e.requireTransactionId,requireValue:e.requireValue,requireCurrency:e.requireCurrency,productionHosts:z_(e.productionHosts)}}}function W_(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 G_(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 K_(e,t,n){return e?`no longer accessible`:n?`access not verified`:t?`not in the current result`:`checking access`}function q_({id:e,label:t,value:n,onChange:r,children:i,disabled:a=!1}){return(0,$.jsxs)(`label`,{htmlFor:e,className:L_,children:[t,(0,$.jsx)(`select`,{id:e,className:I_,value:n,onChange:e=>r(e.target.value),disabled:a,children:i})]})}function J_({id:e,checked:t,onChange:n,children:r}){return(0,$.jsxs)(`label`,{htmlFor:e,className:`flex items-start gap-2 text-label-14 text-secondary`,children:[(0,$.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,$.jsx)(`span`,{children:r})]})}function Y_({providerLabel:e,disabled:t,onDisconnect:n}){let[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(!1);(0,Q.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(Bs(e)),o(!1)}}return(0,$.jsx)(`div`,{ref:l,className:`mt-5 border-t border-subtle pt-4`,children:r?(0,$.jsxs)(`div`,{role:`group`,"aria-label":`Confirm disconnect ${e}`,className:`max-w-2xl`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`Remove Canonry's stored access and selection?`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Saved evidence and conversion contracts remain. New checks stop until you reconnect.`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap gap-2`,children:[(0,$.jsx)(q,{ref:u,type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:a,onClick:p,children:`Keep connected`}),(0,$.jsx)(hs,{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,$.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:s}):null]}):(0,$.jsxs)(hs,{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 X_({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,Q.useState)(!1),p=d||c!==``&&!u&&n.length>0,m=(0,$.jsx)(`label`,{htmlFor:e,className:L_,children:t});return i?(0,$.jsxs)(`div`,{children:[m,(0,$.jsx)(`select`,{id:e,className:I_,disabled:!0,children:(0,$.jsx)(`option`,{children:`Loading…`})})]}):a?(0,$.jsxs)(`div`,{children:[m,(0,$.jsx)(`input`,{id:e,required:!0,className:I_,value:c,onChange:e=>l(e.target.value)}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13 text-negative`,children:[`Could not load the list.`,` `,(0,$.jsx)(`button`,{type:`button`,className:`text-link underline`,onClick:o,children:`Retry`})]})]}):!r||n.length===0?(0,$.jsxs)(`div`,{children:[m,(0,$.jsx)(`input`,{id:e,required:!0,className:I_,value:c,onChange:e=>l(e.target.value)}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-13 text-muted`,children:r?`Synced, but nothing to choose from yet.`:s})]}):(0,$.jsxs)(`div`,{children:[m,p?(0,$.jsx)(`input`,{id:e,required:!0,className:I_,value:c,onChange:e=>l(e.target.value)}):(0,$.jsxs)(`select`,{id:e,required:!0,className:I_,value:c,onChange:e=>l(e.target.value),children:[(0,$.jsxs)(`option`,{value:``,children:[`Select `,t.toLowerCase()]}),n.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.name,e.detail?` (${e.detail})`:``,e.active?``:` — inactive`]},e.id))]}),(0,$.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 Z_({projectId:e,projectName:t}){let n=qn(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(``),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(F_),[N,P]=(0,Q.useState)(null),F=(0,Q.useRef)(null),I=w({...ti({client:K,path:{name:t}}),staleTime:P_}),L=w({...qi({client:K,path:{name:t}}),staleTime:P_}),R=w({...qr({client:K,path:{name:t}}),staleTime:P_}),z=w({...lr({client:K,path:{name:t}}),staleTime:P_}),ee=z.data,te=w({...sr({client:K,path:{name:t},query:{limit:5}}),staleTime:P_}),ne=w({..._i({client:K,path:{name:t},query:{limit:5}}),staleTime:P_}),re=R.data??[],B=(N?re.find(e=>e.id===N)??null:null)??(re.length===1?re[0]??null:null),ie=re.length>1&&!B,ae=w({...na({client:K,path:{name:t,contractId:B?.id??``}}),enabled:!!B,staleTime:P_}),oe=w({...Gr({client:K,path:{name:t}}),enabled:d===`google-ads`&&I.data?.connected===!0,staleTime:0}),V=w({...rr({client:K,path:{name:t}}),enabled:d===`gtm`&&L.data?.connected===!0,staleTime:0}),se=w({...Wr({client:K,path:{name:t,accountId:x}}),enabled:d===`gtm`&&!!x,staleTime:0}),H=w({...oi({client:K,path:{name:t,accountId:x,containerId:T}}),enabled:d===`gtm`&&!!x&&!!T,staleTime:0}),le=C(Jr({client:K})),ue=C(ea({client:K})),de=C(Hr({client:K})),fe=C(yr({client:K})),pe=C(ur({client:K})),me=C(Zr({client:K})),he=C(Gi({client:K})),ge=C(Fi({client:K})),_e=C(pi({client:K}));(0,Q.useEffect)(()=>{if(d!==`google-ads`||p||!I.isSuccess)return;let e=I.data.connection?.selection;v(e?.customerId??``),b(e?.loginCustomerId??``),m(!0)},[p,I.data,I.isSuccess,d]),(0,Q.useEffect)(()=>{if(d!==`gtm`||h||!L.isSuccess)return;let e=L.data.selection;S(e?.accountId??``),E(e?.containerId??``),O(e?.workspaceId??``),g(!0)},[h,L.data,L.isSuccess,d]),(0,Q.useEffect)(()=>{N&&R.data&&(R.data.some(e=>e.id===N)||P(null))},[R.data,N]);let U=(0,Q.useMemo)(()=>{let e=te.data?.snapshots??[],t=ne.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=ae.data?.googleAdsSnapshot,a=ae.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:ae.data?.assessment.contract??B,assessment:ae.data?.assessment??null,contractSelectionRequired:ie,assessmentState:B?ae.isError?`unavailable`:ae.isLoading?`loading`:void 0:void 0,assessmentError:ae.isError?Bs(ae.error):null,googleAds:B_(I.data,R_(te.data?.total??0,te.isLoading,te.isError,te.error),I.isError),gtm:H_(L.data,R_(ne.data?.total??0,ne.isLoading,ne.isError,ne.error),L.isError),snapshots:n,assessmentEvidenceSnapshots:r}},[B,ie,te.data,te.error,te.isError,te.isLoading,I.data,I.isError,ne.data,ne.error,ne.isError,ne.isLoading,L.data,L.isError,ae.data,ae.error,ae.isError,ae.isLoading]),ve=(0,Q.useSyncExternalStore)(Go,jo,jo),ye=Object.values(ve.runs).some(t=>t.projectId===e&&(t.kind===ce[`google-ads-sync`]||t.kind===ce[`gtm-sync`])),be=le.isPending||ue.isPending||de.isPending||fe.isPending||pe.isPending||me.isPending||he.isPending||ge.isPending||_e.isPending||ye;async function xe(){await Promise.all([I.refetch(),L.refetch(),R.refetch(),te.refetch(),ne.refetch(),z.refetch(),B?ae.refetch():Promise.resolve()])}async function Se(e){await xe();for(let t=0;t<10&&!e();t+=1)await new Promise(e=>setTimeout(e,1500)),await xe()}function Ce(){let e=document.activeElement;F.current=e instanceof HTMLElement?e:null}function we(e){typeof window<`u`&&typeof window.requestAnimationFrame==`function`?window.requestAnimationFrame(e):globalThis.setTimeout(e,0)}function Te(e){e&&(!e.matches(`a[href], button, input, select, textarea, [contenteditable="true"]`)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=-1),e.focus({preventScroll:!0}))}function Ee(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:Oa()?`auto`:`smooth`,block:`start`}),Te(document.getElementById(t)??n)}function De(e,t){Ce(),we(()=>Ee(e,t))}function Oe(){let e=F.current;F.current=null,e&&we(()=>{e.isConnected&&e.focus({preventScroll:!0})})}function ke(){i(null),c(!1),Oe()}function Ae(){i(null),f(null),Oe()}function je(){i(null),A(!1),Oe()}function W(){i(null),f(null),c(!0),De(`google-ads-connect-panel`,`google-ads-connect-title`)}function Me(){i(null),v(``),b(``),m(!1),f(`google-ads`),c(!1),De(`google-ads-selection-panel`,`google-ads-selection-title`)}function Ne(){i(null),S(``),E(``),O(``),g(!1),f(`gtm`),c(!1),De(`gtm-selection-panel`,`gtm-selection-title`)}function Pe(){i(null),A(!0),De(`conversion-integrity-contract-form`,`conversion-integrity-contract-form-title`)}function Fe(e,n){$o({id:e.id,projectId:e.projectId,kind:e.kind,projectLabel:t,sourceAction:n}),Xn({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 Ie(){Aa(n),i(null);try{let e=await le.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.`),W_(e.authorizationUrl,()=>{xe(),o(null),Oe()})}catch(e){i(Bs(e))}}async function Le(){Aa(n),i(null);try{let e=await ue.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.`),W_(e.authorizationUrl,()=>{xe(),o(null),Oe()})}catch(e){i(Bs(e))}}async function Re(){if(Aa(n),!_)i(`Select a Google Ads customer before saving.`);else{i(null);try{await de.mutateAsync({path:{name:t},body:{customerId:_,...y.trim()?{loginCustomerId:y.trim()}:{}}}),f(null),Oe(),await Se(()=>I.data?.selectedCustomer!=null)}catch(e){i(Bs(e))}}}async function ze(){if(Aa(n),!x||!T)i(`Select a Tag Manager account and container before saving.`);else{i(null);try{await fe.mutateAsync({path:{name:t},body:{accountId:x,containerId:T,...D?{workspaceId:D}:{}}}),f(null),Oe(),await Se(()=>L.data?.status===`connected`)}catch(e){i(Bs(e))}}}async function Be(){Aa(n),i(null),await he.mutateAsync({path:{name:t}}),f(null),c(!1),v(``),b(``),m(!1),o(null),await xe(),Xn({title:`Google Ads disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`google-ads-disconnected:${e}`,dedupeMode:`replace`}),F.current=null,we(()=>Te(document.getElementById(`conversion-integrity-title`)))}async function Ve(){Aa(n),i(null),await ge.mutateAsync({path:{name:t}}),f(null),S(``),E(``),O(``),g(!1),o(null),await xe(),Xn({title:`Tag Manager disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`gtm-disconnected:${e}`,dedupeMode:`replace`}),F.current=null,we(()=>Te(document.getElementById(`conversion-integrity-title`)))}async function He(){Aa(n),i(null);try{Fe(await pe.mutateAsync({path:{name:t}}),`google-ads-sync`)}catch(e){i(Bs(e))}}async function Ue(){Aa(n),i(null);try{Fe(await me.mutateAsync({path:{name:t}}),`gtm-sync`)}catch(e){i(Bs(e))}}async function We(){Aa(n),i(null);try{let e=await Promise.allSettled([pe.mutateAsync({path:{name:t}}),me.mutateAsync({path:{name:t}})]),[n,r]=e;n.status===`fulfilled`&&Fe(n.value,`google-ads-sync`),r.status===`fulfilled`&&Fe(r.value,`gtm-sync`);let i=e.find(e=>e.status===`rejected`);if(i?.status===`rejected`)throw i.reason}catch(e){i(Bs(e))}}async function Ge(){Aa(n);let e=I.data?.connection?.selection.customerId,r=L.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 _e.mutateAsync({path:{name:t},body:U_(j,e,{accountId:r.accountId,containerId:r.containerId})});M(F_),A(!1),Oe(),(await R.refetch()).data?.some(e=>e.id===n.id)&&P(n.id)}catch(e){i(Bs(e))}}}function Ke(e){switch(e){case`connect-google-ads`:W();return;case`connect-gtm`:Ce(),Le();return;case`select-google-ads`:Me();return;case`select-gtm`:Ne();return;case`sync-google-ads`:He();return;case`sync-gtm`:Ue();return;case`sync-static-evidence`:We();return;case`declare-contract`:Pe();return;case`review-findings`:De(`conversion-integrity-findings`,`conversion-integrity-findings`);return;case`review-runtime-verification`:De(`conversion-integrity-runtime-guidance`,`conversion-integrity-runtime-title`);return;case`retry-connection-status`:xe();return;case`select-contract`:De(`conversion-integrity-contract-select`,`conversion-integrity-contract-select`);return;case`retry-integrity`:ae.refetch();return;case`waiting-for-integrity`:return}}let qe=oe.data?.customers??[],Je=V.data?.accounts??[],Ye=se.data?.containers??[],Xe=H.data?.workspaces??[],Ze=!!_&&!qe.some(e=>e.customerId===_),Qe=!!x&&!Je.some(e=>e.id===x),$e=!!T&&!Ye.some(e=>e.id===T),et=!!D&&!Xe.some(e=>e.id===D),tt=Ze&&oe.isSuccess&&oe.data.truncated===!1,G=Qe&&V.isSuccess&&V.data.truncated===!1,nt=$e&&se.isSuccess&&se.data.truncated===!1,rt=et&&H.isSuccess&&H.data.truncated===!1,it=G||nt||rt,at=G?`The saved Tag Manager account is no longer accessible. Choose an available account before saving.`:nt?`The saved Tag Manager container is no longer accessible. Choose an available container before saving.`:rt?`The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.`:null,ot=K_(tt,oe.data,oe.isError),st=K_(G,V.data,V.isError),ct=K_(nt,se.data,se.isError),lt=K_(rt,H.data,H.isError),ut=oe.isError?Bs(oe.error):null,dt=V.isError?Bs(V.error):se.isError?Bs(se.error):H.isError?Bs(H.error):null,ft=d===`google-ads`?ut:d===`gtm`?dt:null,pt=G_(`customer`,oe.data,qe.length),mt=G_(`account`,V.data,Je.length),ht=G_(`container`,se.data,Ye.length),gt=G_(`draft workspace`,H.data,Xe.length),_t=V.isError||se.isError||H.isError&&!!D,vt=s||d!==null||k;function yt(){oe.refetch()}function bt(){V.isError?V.refetch():se.isError?se.refetch():H.isError&&H.refetch()}return I.isLoading||L.isLoading||R.isLoading?(0,$.jsxs)(`section`,{className:`page-section`,"aria-busy":`true`,"aria-labelledby":`conversion-integrity-title`,children:[(0,$.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,$.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,$.jsx)(`div`,{"aria-hidden":`true`,className:`mt-5 grid gap-4 sm:grid-cols-2`,children:[0,1].map(e=>(0,$.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,$.jsx)(`div`,{className:`skeleton-text w-28`}),(0,$.jsx)(`div`,{className:`skeleton-text-sm w-full`}),(0,$.jsx)(`div`,{className:`skeleton-text-sm w-3/4`})]},e))}),(0,$.jsx)(`p`,{role:`status`,className:`sr-only`,children:`Loading conversion setup…`})]}):R.isError&&!R.data?(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`conversion-integrity-title`,children:[(0,$.jsx)(`p`,{className:`eyebrow`,children:`Google marketing`}),(0,$.jsx)(`h2`,{id:`conversion-integrity-title`,className:`mt-1 text-heading-20 text-heading`,children:`Conversion Integrity`}),(0,$.jsxs)(`p`,{role:`alert`,className:`mt-3 text-copy-14 text-negative`,children:[`Could not load conversion contracts: `,Bs(R.error)]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void R.refetch(),children:`Retry contracts`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(N_,{workspace:U,onPrimaryAction:Ke,actionPending:be,actionError:vt?null:r,contracts:re,selectedContractId:B?.id??null,onSelectContract:e=>P(e||null),contractError:R.isError?Bs(R.error):null,onRetryContracts:()=>void R.refetch(),onRetryEvidence:()=>{Promise.all([te.refetch(),ne.refetch()])},onChangeGoogleAdsSelection:Me,onChangeGtmSelection:Ne,onAddContract:()=>Ke(`declare-contract`)}),a?(0,$.jsx)(`p`,{role:`status`,className:`page-section text-copy-14 text-secondary`,children:a}):null,s?(0,$.jsxs)(`section`,{id:`google-ads-connect-panel`,className:`page-section-divider`,"aria-labelledby":`google-ads-connect-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Ads`}),(0,$.jsx)(`h3`,{id:`google-ads-connect-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Connect read-only access`})]})}),r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,(0,$.jsxs)(`form`,{className:`max-w-xl`,onSubmit:Jn(async e=>{e.preventDefault(),await Ie()}),children:[(0,$.jsxs)(`label`,{htmlFor:`google-ads-developer-token`,className:L_,children:[`Developer token`,(0,$.jsx)(`input`,{id:`google-ads-developer-token`,type:`password`,autoComplete:`off`,value:l,onChange:e=>u(e.target.value),className:I_,placeholder:`Required only when this project has no saved token`})]}),(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Canonry stores this securely. It never appears in saved evidence.`}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,$.jsx)(hs,{type:`submit`,disabled:le.isPending,children:le.isPending?`Starting…`:`Continue to Google`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]})]})]}):null,d===`google-ads`?(0,$.jsxs)(`section`,{id:`google-ads-selection-panel`,className:`page-section-divider`,"aria-labelledby":`google-ads-selection-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Ads`}),(0,$.jsx)(`h3`,{id:`google-ads-selection-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Select customer context`})]})}),ft?(0,$.jsxs)(`div`,{role:`alert`,className:`mb-4 flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,$.jsx)(`span`,{children:ft}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:yt,children:`Retry customer list`})]}):null,r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,tt?(0,$.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,$.jsxs)(`div`,{className:`grid max-w-2xl gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(q_,{id:`google-ads-customer`,label:`Customer account`,value:_,onChange:e=>{m(!0),v(e);let t=qe.find(t=>t.customerId===e);b(t?.parentCustomerId??``)},disabled:oe.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:oe.isLoading?`Loading accessible customers…`:`Select a customer`}),Ze?(0,$.jsxs)(`option`,{value:_,disabled:tt,children:[`Saved customer `,_,` (`,ot,`)`]}):null,qe.map(e=>(0,$.jsx)(`option`,{value:e.customerId,children:e.descriptiveName??`Customer ${e.customerId}`},e.customerId))]}),(0,$.jsxs)(`label`,{htmlFor:`google-ads-login-customer`,className:L_,children:[`Manager account ID (optional)`,(0,$.jsx)(`input`,{id:`google-ads-login-customer`,className:I_,value:y,onChange:e=>{m(!0),b(e.target.value)},placeholder:`Use only when a manager context is required`})]})]}),pt?(0,$.jsx)(`p`,{role:`status`,className:`mt-3 text-copy-14 ${oe.data?.truncated?`text-caution`:`text-secondary`}`,children:pt}):null,(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,$.jsx)(hs,{type:`button`,disabled:de.isPending||oe.isLoading||oe.isError||tt||!_,onClick:Jn(Re),children:de.isPending?`Saving…`:`Save customer selection`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:Ae,children:`Cancel`})]}),I.data?.connected?(0,$.jsx)(Y_,{providerLabel:`Google Ads`,disabled:be,onDisconnect:Be}):null]}):null,d===`gtm`?(0,$.jsxs)(`section`,{id:`gtm-selection-panel`,className:`page-section-divider`,"aria-labelledby":`gtm-selection-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Google Tag Manager`}),(0,$.jsx)(`h3`,{id:`gtm-selection-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Select container context`})]})}),ft?(0,$.jsxs)(`div`,{role:`alert`,className:`mb-4 flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,$.jsx)(`span`,{children:ft}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:bt,children:V.isError?`Retry account list`:se.isError?`Retry container list`:`Retry workspace list`})]}):null,r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,at?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:at}):null,(0,$.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-3`,children:[(0,$.jsxs)(q_,{id:`gtm-account`,label:`Account`,value:x,onChange:e=>{g(!0),e!==x&&(E(``),O(``)),S(e)},disabled:V.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:V.isLoading?`Loading accounts…`:`Select an account`}),Qe?(0,$.jsxs)(`option`,{value:x,disabled:G,children:[`Saved account `,x,` (`,st,`)`]}):null,Je.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,$.jsxs)(q_,{id:`gtm-container`,label:`Container`,value:T,onChange:e=>{g(!0),e!==T&&O(``),E(e)},disabled:!x||se.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:se.isLoading?`Loading containers…`:`Select a container`}),$e?(0,$.jsxs)(`option`,{value:T,disabled:nt,children:[`Saved container `,T,` (`,ct,`)`]}):null,Ye.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,$.jsxs)(q_,{id:`gtm-workspace`,label:`Draft workspace (optional)`,value:D,onChange:e=>{g(!0),O(e)},disabled:!T||H.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:H.isLoading?`Loading workspaces…`:`No draft workspace`}),et?(0,$.jsxs)(`option`,{value:D,disabled:rt,children:[`Saved draft workspace `,D,` (`,lt,`)`]}):null,Xe.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),(0,$.jsxs)(`div`,{className:`mt-3 grid max-w-3xl gap-2 text-label-14 sm:grid-cols-3`,children:[mt?(0,$.jsx)(`p`,{role:`status`,className:V.data?.truncated?`text-caution`:`text-secondary`,children:mt}):null,ht?(0,$.jsx)(`p`,{role:`status`,className:se.data?.truncated?`text-caution`:`text-secondary`,children:ht}):null,gt?(0,$.jsx)(`p`,{role:`status`,className:H.data?.truncated?`text-caution`:`text-secondary`,children:gt}):null]}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,$.jsx)(hs,{type:`button`,disabled:fe.isPending||V.isLoading||se.isLoading||H.isLoading&&!!D||_t||it||!x||!T,onClick:Jn(ze),children:fe.isPending?`Saving…`:`Save container selection`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:Ae,children:`Cancel`})]}),L.data?.connected?(0,$.jsx)(Y_,{providerLabel:`Tag Manager`,disabled:be,onDisconnect:Ve}):null]}):null,k?(0,$.jsxs)(`section`,{id:`conversion-integrity-contract-form`,className:`page-section-divider`,"aria-labelledby":`conversion-integrity-contract-form-title`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Declared conversion`}),(0,$.jsx)(`h3`,{id:`conversion-integrity-contract-form-title`,tabIndex:-1,className:`text-heading-16 text-heading`,children:`Declare the expected path`})]})}),r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-copy-14 text-negative`,children:r}):null,(0,$.jsxs)(`form`,{onSubmit:Jn(async e=>{e.preventDefault(),await Ge()}),children:[(0,$.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{htmlFor:`contract-name`,className:L_,children:[`Conversion name`,(0,$.jsx)(`input`,{id:`contract-name`,required:!0,maxLength:120,className:I_,value:j.name,onChange:e=>M(t=>({...t,name:e.target.value})),placeholder:`Booking completed`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-event-name`,className:L_,children:[`Website event`,(0,$.jsx)(`input`,{id:`contract-event-name`,required:!0,className:I_,value:j.eventName,onChange:e=>M(t=>({...t,eventName:e.target.value})),placeholder:`booking_complete`})]}),(0,$.jsx)(X_,{id:`contract-conversion-action`,label:`Google Ads conversion action`,options:ee?.googleAds.conversionActions??[],synced:ee?.googleAds.syncedAt!=null,loading:z.isLoading,failed:z.isError,onRetry:()=>void z.refetch(),emptyHint:`Run a Google Ads sync to list conversion actions.`,value:j.conversionActionId,onChange:e=>M(t=>({...t,conversionActionId:e}))}),(0,$.jsx)(X_,{id:`contract-gtm-tag`,label:`Tag Manager tag`,options:ee?.gtm.tags??[],synced:ee?.gtm.syncedAt!=null,loading:z.isLoading,failed:z.isError,onRetry:()=>void z.refetch(),emptyHint:`Run a Tag Manager sync to list tags.`,value:j.tagId,onChange:e=>M(t=>({...t,tagId:e}))})]}),(0,$.jsxs)(`details`,{className:`inline-disclosure mt-5 max-w-3xl`,children:[(0,$.jsx)(`summary`,{children:`Additional matching rules`}),(0,$.jsxs)(`div`,{className:`mt-4 grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{htmlFor:`contract-conversion-id`,className:L_,children:[`Google conversion ID (optional)`,(0,$.jsx)(`input`,{id:`contract-conversion-id`,className:I_,value:j.conversionId,onChange:e=>M(t=>({...t,conversionId:e.target.value}))})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-conversion-label`,className:L_,children:[`Google conversion label (optional)`,(0,$.jsx)(`input`,{id:`contract-conversion-label`,className:I_,value:j.conversionLabel,onChange:e=>M(t=>({...t,conversionLabel:e.target.value}))})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-trigger-ids`,className:L_,children:[`Trigger IDs`,(0,$.jsx)(`input`,{id:`contract-trigger-ids`,className:I_,value:j.triggerIds,onChange:e=>M(t=>({...t,triggerIds:e.target.value})),placeholder:`Comma-separated, optional`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-variable-ids`,className:L_,children:[`Variable IDs`,(0,$.jsx)(`input`,{id:`contract-variable-ids`,className:I_,value:j.variableIds,onChange:e=>M(t=>({...t,variableIds:e.target.value})),placeholder:`Comma-separated, optional`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-campaign-ids`,className:L_,children:[`Campaign IDs`,(0,$.jsx)(`input`,{id:`contract-campaign-ids`,className:I_,value:j.campaignIds,onChange:e=>M(t=>({...t,campaignIds:e.target.value})),placeholder:`Optional campaign-specific goal checks`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-production-hosts`,className:L_,children:[`Production hosts`,(0,$.jsx)(`input`,{id:`contract-production-hosts`,className:I_,value:j.productionHosts,onChange:e=>M(t=>({...t,productionHosts:e.target.value})),placeholder:`example.com`})]})]}),(0,$.jsxs)(`fieldset`,{className:`mt-5 border-t border-subtle pt-4`,children:[(0,$.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Required evidence`}),(0,$.jsxs)(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,children:[(0,$.jsx)(J_,{id:`contract-primary-action`,checked:j.requirePrimaryAction,onChange:e=>M(t=>({...t,requirePrimaryAction:e})),children:`Google Ads action is primary`}),(0,$.jsx)(J_,{id:`contract-biddable-goal`,checked:j.requireBiddableGoal,onChange:e=>M(t=>({...t,requireBiddableGoal:e})),children:`Google Ads goal is biddable`}),(0,$.jsx)(J_,{id:`contract-runtime-verification`,checked:j.verificationRequired,onChange:e=>M(t=>({...t,verificationRequired:e})),children:`Runtime proof is required`}),(0,$.jsx)(J_,{id:`contract-transaction-id`,checked:j.requireTransactionId,onChange:e=>M(t=>({...t,requireTransactionId:e})),children:`Transaction ID is required`}),(0,$.jsx)(J_,{id:`contract-value`,checked:j.requireValue,onChange:e=>M(t=>({...t,requireValue:e})),children:`Conversion value is required`}),(0,$.jsx)(J_,{id:`contract-currency`,checked:j.requireCurrency,onChange:e=>M(t=>({...t,requireCurrency:e})),children:`Currency is required`})]})]})]}),(0,$.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,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,$.jsx)(hs,{type:`submit`,disabled:_e.isPending,children:_e.isPending?`Saving…`:`Save conversion contract`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:je,children:`Cancel`})]})]})]}):null]})}var Q_=6e4,$_=[`7d`,`14d`,`30d`],ev=`not available`,tv=`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%.`,nv=`No Google Ads snapshot stored yet`,rv=`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.`,iv=`No closed days yet`,av=`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.`,ov={"insufficient-history":`Period change is hidden: the stored snapshot does not cover a prior period of equal length yet.`},sv=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),cv=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),lv=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function uv(e,t){return e===null||!Number.isFinite(e)?ev:t===null?lv.format(e/1e6):Ys(e,t)}function dv(e){return e===null||!Number.isFinite(e)?ev:St(e)}function fv(e,t){return e===null||!Number.isFinite(e)?`${ev} vs prior ${t}d`:e===0?`no change vs prior ${t}d`:`${e>0?`↑`:`↓`} ${St(Math.abs(e))} vs prior ${t}d`}function pv(e){return e===`enabled`?`positive`:e===`paused`?`caution`:`neutral`}function mv(e){return e===`enabled`?`Enabled`:e===`paused`?`Paused`:e===`removed`?`Removed`:`Unknown`}function hv(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 gv({projectName:e}){let[t,n]=(0,Q.useState)(`14d`),[r,i]=(0,Q.useState)(()=>new Set([`costMicros`,`conversions`])),a=w({...sa({client:K,path:{name:e},query:{window:t}}),staleTime:Q_}),o=a.data,s=(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow`,children:`Google Ads`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h2`,{id:`google-ads-performance-title`,className:`text-heading-20 text-heading`,children:`Ad performance`}),(0,$.jsx)(X,{text:tv})]}),o?.source?(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[_a(o.startDate),` to `,_a(o.endDate),` · `,o.days,` closed `,o.days===1?`day`:`days`]}):null]}),(0,$.jsx)(tl,{windows:$_,value:t,onChange:n,label:`Google Ads time period`})]});if(a.isLoading)return(0,$.jsxs)(`section`,{className:`page-section`,"aria-busy":`true`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,$.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,$.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,$.jsx)(`div`,{className:`skeleton-text w-20`}),(0,$.jsx)(`div`,{className:`skeleton-text-sm w-28`})]},e))}),(0,$.jsx)(`p`,{role:`status`,className:`sr-only`,children:`Loading Google Ads performance…`})]});if(a.isError||!o)return(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,$.jsxs)(`p`,{role:`alert`,className:`mt-4 text-copy-14 text-negative`,children:[`Could not load Google Ads performance: `,Bs(a.error)]}),(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void a.refetch(),children:`Retry performance`})]});let{totals:c,daily:l,campaigns:u,comparison:d,comparisonUnavailableReason:f,source:p}=o;if(!p){let e=f===`insufficient-history`;return(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,$.jsxs)(`div`,{className:`mt-4 max-w-2xl material-base p-5`,children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:e?iv:nv}),(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:e?av:rv})]})]})}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:uv(c.costMicros,m),change:d?.change.costMicros??null,direction:`none`,seriesKey:`costMicros`},{key:`conversions`,comparable:!0,label:`Conversions`,value:cv.format(c.conversions),change:d?.change.conversions??null,direction:`up-good`,seriesKey:`conversions`},{key:`cost-per-conversion`,label:`Cost / conv.`,value:g?`no conversions`:uv(c.costPerConversionMicros,m),change:null,comparable:!1,direction:`down-good`,seriesKey:null},{key:`conversion-rate`,comparable:!0,label:`Conv. rate`,value:dv(c.conversionRate),change:d?.change.conversionRate??null,direction:`up-good`,seriesKey:null}],v=[{key:`clicks`,label:`Clicks`,value:sv.format(c.clicks),seriesKey:`clicks`},{key:`impressions`,label:`Impressions`,value:sv.format(c.impressions),seriesKey:`impressions`},{key:`ctr`,label:`CTR`,value:dv(c.ctr),seriesKey:`ctr`},{key:`cpc`,label:`CPC`,value:uv(c.cpcMicros,m),seriesKey:null}],y={costMicros:{label:`Spend`,color:ua[1],axisId:`spend`,formatValue:e=>uv(e,m)},conversions:{label:`Conversions`,color:ua[0],axisId:`conversions`,formatValue:e=>cv.format(e)},clicks:{label:`Clicks`,color:ua[2],axisId:`clicks`,formatValue:e=>sv.format(e)},impressions:{label:`Impressions`,color:ua[3],axisId:`impressions`,formatValue:e=>sv.format(e)},ctr:{label:`CTR`,color:ua[4],axisId:`ctr`,formatValue:e=>dv(e)}},b=[...r].map(e=>({dataKey:e,...y[e]}));return(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,h===null?null:(0,$.jsxs)(`p`,{role:`status`,className:`mt-3 text-copy-14 text-caution`,children:[`Totals cover `,sv.format(h.queried),` of`,` `,sv.format(h.inInventory),` campaigns, so they are a subset of the account.`]}),p.truncated?(0,$.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,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:ov[`insufficient-history`]}):null,(0,$.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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5 text-label-12 text-secondary`,children:[e.seriesKey?(0,$.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,$.jsx)(`span`,{className:`mt-0.5 block text-label-18 tabular-nums text-strong`,children:e.value}),d&&e.comparable?(0,$.jsx)(`span`,{className:`block text-label-12 tabular-nums ${hv(e.change,e.direction)}`,children:fv(e.change,d.days)}):(0,$.jsx)(`span`,{className:`block text-label-12 text-muted`,children:e.comparable?`no prior ${t} period stored`:`\xA0`})]});return e.seriesKey===null?(0,$.jsx)(`div`,{className:`material-base px-3 py-2`,children:o},e.key):(0,$.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,$.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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-label-12 text-secondary`,children:[e.seriesKey?(0,$.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,$.jsx)(`dd`,{className:`text-label-14 tabular-nums text-strong`,children:e.value})]});return e.seriesKey===null?(0,$.jsx)(`div`,{className:`flex items-baseline gap-1.5`,children:a},e.key):(0,$.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,$.jsxs)(`div`,{className:`mt-4`,children:[(0,$.jsx)(da,{data:l,xKey:`date`,series:b,xTickFormatter:fa,labelFormatter:_a}),(0,$.jsx)(`ul`,{className:`sr-only`,children:l.map(e=>(0,$.jsxs)(`li`,{children:[_a(e.date),`:`,` `,b.map(t=>{let n=e[t.dataKey];return`${t.label} ${n===null?ev:y[t.dataKey].formatValue(n)}`}).join(`, `),e.origin===`filled`?`, no delivery reported`:``]},e.date))})]}),(0,$.jsxs)(`div`,{className:`page-section-divider`,children:[(0,$.jsx)(`div`,{className:`section-head section-head-inline`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`By campaign`}),(0,$.jsx)(`h3`,{className:`text-heading-16 text-heading`,children:`Campaign performance`})]})}),(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-label-14`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Google Ads campaign performance for the selected window`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Campaign`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Status`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Impressions`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Clicks`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Spend`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Conversions`}),(0,$.jsx)(`th`,{className:`text-right`,children:`CTR`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Cost / conv.`})]})}),(0,$.jsx)(`tbody`,{children:u.length===0?(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:8,className:`text-secondary`,children:`No campaign delivered in this window.`})}):u.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-xs truncate text-strong`,title:e.name??e.campaignId,children:e.name??(0,$.jsx)(`span`,{className:`font-mono text-secondary`,children:e.campaignId})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:pv(e.status),children:mv(e.status)})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:sv.format(e.totals.impressions)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:sv.format(e.totals.clicks)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:uv(e.totals.costMicros,m)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:cv.format(e.totals.conversions)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:dv(e.totals.ctr)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums`,children:e.totals.costMicros>0&&e.totals.conversions===0?(0,$.jsx)(J,{tone:`caution`,children:`no conversions`}):(0,$.jsx)(`span`,{className:`text-secondary`,children:uv(e.totals.costPerConversionMicros,m)})})]},e.campaignId))})]})}),(0,$.jsxs)(`p`,{className:`mt-3 text-copy-13 text-muted`,children:[`Snapshot `,pa(ha(p.capturedAt)),` · `,`customer `,p.customerId,` · `,`latest closed day `,_a(p.asOfDate),p.openDate?(0,$.jsxs)($.Fragment,{children:[` · `,_a(p.openDate),` still open, excluded`]}):null,p.timeZone?(0,$.jsxs)($.Fragment,{children:[` · `,`days close in `,p.timeZone]}):null]})]})]})}var _v=20,vv=50,yv=50,bv=50;function xv(e){return e===`viewer`}function Sv(e){return e?.status===`unavailable`}function Cv(e,t,n){return n?e.includes(t)?[...e]:[...e,t]:e.filter(e=>e!==t)}function wv(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 Tv(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 Ev(e,t,n){if(e.kind===`all`)return`every location (${n})`;if(e.kind===`specific`)return n===1?`1 location`:`${n} locations`;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 Dv(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 Ov(e){return e===`matched`?`positive`:e===`duplicate`?`neutral`:e===`ambiguous`||e===`proposed`||e===`excluded`?`caution`:`negative`}function kv(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 Av(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 jv(e){return e.state===`missing`||e.source===`unavailable-tracked-query`||!e.source}function Mv(e){return jv(e)?`Unavailable tracked query`:e.text?.trim()||`Unavailable tracked query`}function Nv({properties:e,selectedPropertyIds:t,onSelectedPropertyIdsChange:n,legend:r,showBulkActions:i=!0}){let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),l=a.trim().toLocaleLowerCase(),u=l?e.filter(e=>e.label.toLocaleLowerCase().includes(l)):e,d=s?u:u.slice(0,yv),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,$.jsxs)(`fieldset`,{children:[(0,$.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:r}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-end justify-between gap-3`,children:[(0,$.jsxs)(`label`,{className:`block min-w-48 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search Properties`}),(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:d.length===0,onClick:p,children:`Select all shown`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:t.length===0,onClick:()=>n([]),children:`Clear selection`})]}):null]}),u.length===0?(0,$.jsx)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:`No Properties match this search.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`mt-3 text-copy-14 text-secondary`,children:[`Showing `,d.length,` of `,u.length,` Properties`]}),(0,$.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,$.jsxs)(`label`,{className:`flex min-h-11 cursor-pointer items-center justify-between gap-3 py-2 text-label-14 text-primary`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(`input`,{"aria-label":`Select ${e.label}`,checked:r,type:`checkbox`,onChange:r=>n(Cv(t,e.id,r.currentTarget.checked))}),(0,$.jsx)(`span`,{children:e.label})]}),e.urlCount===void 0?null:(0,$.jsxs)(`span`,{className:`tabular-nums text-secondary`,children:[e.urlCount,` URLs`]})]},e.id)})}),f?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 pointer-coarse:min-h-11`,onClick:()=>c(!0),children:`Show all Properties`}):null]})]})}function Pv(){return(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-label-14 text-secondary`,children:[(0,$.jsx)(J,{tone:`neutral`,children:`Viewer access`}),(0,$.jsx)(`span`,{children:`You can inspect this setup.`})]})}function Fv({message:e}){return(0,$.jsxs)(`div`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4 text-label-14 text-caution`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(J,{tone:`caution`,children:`Unavailable`}),(0,$.jsx)(`h4`,{className:`text-heading-14`,children:`Measurement setup unavailable`})]}),(0,$.jsx)(`p`,{className:`mt-2 max-w-2xl text-secondary`,children:e})]})}function Iv({value:e}){let[t,n]=(0,Q.useState)(0),[r,i]=(0,Q.useState)(0),[a,o]=(0,Q.useState)(null),s=e.preview,c=s?.counts.needsAttention??0,l=s?.rows.filter(e=>e.status===`matched`)??[],u=s?.rows??[],d=u.filter(e=>e.status!==`matched`),f=Math.max(1,Math.ceil(u.length/vv)),p=Math.min(t,f-1),m=u.slice(p*vv,(p+1)*vv),h=Math.max(1,Math.ceil(d.length/vv)),g=Math.min(r,h-1),_=d.slice(g*vv,(g+1)*vv),v=e.csv.trim().length>0&&!e.isReviewing&&!e.isApplying,y=l.length>0&&!e.isApplying,b=s!==null&&a===s.previewChecksum,x=d.length>0&&g===h-1;(0,Q.useEffect)(()=>{n(0),i(0),o(null)},[s?.previewChecksum]);async function S(t){if(t)try{e.onCsvChange(await t.text())}catch{}}return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-group-import-title`,className:`border-y border-default py-4`,children:[(0,$.jsxs)(`div`,{className:`max-w-2xl`,children:[(0,$.jsx)(`h4`,{id:`advanced-measurement-group-import-title`,className:`text-heading-14 text-heading`,children:`Import groups from CSV`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Import group membership once instead of selecting the same Properties repeatedly.`})]}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`CSV file`}),(0,$.jsx)(`input`,{"aria-label":`Group membership CSV file`,type:`file`,accept:`.csv,text/csv`,disabled:e.isReviewing||e.isApplying,onChange:e=>{S(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,$.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Or paste CSV`}),(0,$.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
|
|
6
|
-
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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:!v,onClick:()=>{e.onReview()},children:e.isReviewing?`Reviewing CSV…`:`Review CSV`}),(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Use columns named property and group. URL is optional.`})]}),e.error?(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:e.error}):null,e.notice?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:e.notice}):null]}),s?(0,$.jsxs)(`div`,{className:`mt-4 border-t border-default pt-4`,"aria-live":`polite`,children:[(0,$.jsx)(`h5`,{className:`text-heading-14 text-heading`,children:`Review group membership`}),(0,$.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,$.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Groups and memberships ready to apply`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Group`}),(0,$.jsx)(`th`,{children:`Change`}),(0,$.jsx)(`th`,{children:`Properties`}),(0,$.jsx)(`th`,{children:`New memberships`})]})}),(0,$.jsx)(`tbody`,{children:s.groupChanges.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.label}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.action===`create`?`Create group`:`Add to existing group`}),(0,$.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.targetKeys.length}),(0,$.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,$.jsxs)(`details`,{className:`mt-3 border-y border-default py-3`,children:[(0,$.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong text-heading`,children:[`Review CSV rows (`,s.counts.dataRows,`)`]}),(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`CSV group membership review`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Row`}),(0,$.jsx)(`th`,{children:`Property`}),(0,$.jsx)(`th`,{children:`Group`}),(0,$.jsx)(`th`,{children:`Status`})]})}),(0,$.jsx)(`tbody`,{children:m.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.dataRow}),(0,$.jsx)(`td`,{className:`text-heading`,children:e.property}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.group}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(J,{tone:Ov(e.status),children:kv(e.status)}),Av(e)?(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:Av(e)}):null]})]},e.dataRow))})]})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Page `,p+1,` of `,f,` · `,s.rows.length,` rows`]}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:p===0,onClick:()=>n(e=>Math.max(0,e-1)),children:`Previous 50 rows`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:p===f-1,onClick:()=>n(e=>Math.min(f-1,e+1)),children:`Next 50 rows`})]})]}):null,c>0?(0,$.jsxs)(`details`,{className:`mt-3 border-y border-caution-800/30 py-3`,children:[(0,$.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong text-heading`,children:[`Fix `,c,` row`,c===1?``:`s`,` before applying`]}),(0,$.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,$.jsx)(`div`,{className:`mt-3 overflow-x-auto border-y border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`CSV rows that need attention`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Row`}),(0,$.jsx)(`th`,{children:`Property`}),(0,$.jsx)(`th`,{children:`Group`}),(0,$.jsx)(`th`,{children:`Issue`})]})}),(0,$.jsx)(`tbody`,{children:_.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums text-secondary`,children:e.dataRow}),(0,$.jsx)(`td`,{className:`text-heading`,children:e.property}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.group}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(J,{tone:Ov(e.status),children:kv(e.status)}),Av(e)?(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:Av(e)}):null]})]},e.dataRow))})]})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Exception page `,g+1,` of `,h]}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:g===0,onClick:()=>i(e=>Math.max(0,e-1)),children:`Previous 50 exceptions`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:g===h-1,onClick:()=>i(e=>Math.min(h-1,e+1)),children:`Review next 50 exceptions`})]}),(0,$.jsxs)(`label`,{className:`mt-3 flex min-h-11 max-w-xl items-center gap-3 text-label-14 text-heading`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:b,disabled:e.isApplying||!x,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,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 pointer-coarse:min-h-11`,disabled:!y||!b,onClick:()=>{e.onApply(l.map(e=>e.dataRow))},children:e.isApplying?`Applying groups…`:`Apply ${l.length} matched row${l.length===1?``:`s`}`})]}):(0,$.jsx)(q,{type:`button`,className:`mt-3 pointer-coarse:min-h-11`,disabled:!y,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 Lv=`—`;function Rv({access:e,availability:t,properties:n,queries:r,selectedQueryIds:i,isApplying:a=!1,isBusy:o=!1,canContinue:s=!0,onSelectedQueryIdsChange:c,onApplySelectedQueries:l,onClearQueryAssignments:u,onRemoveQuery:d,onCreateQueries:f,onCreateAndPairQuestions:p,isCreatingQueries:m=!1,createQueriesError:h=null,onManageProjectQueries:g,groups:_,audience:v,onAudienceChange:y,executionOptions:b=[],executionOptionId:x=``,onExecutionOptionChange:S,markets:C=[],marketId:w=``,onMarketChange:T,marketExecutionOptionId:E=``,onMarketExecutionOptionChange:D,onRouteMarket:O,isRoutingMarket:k=!1,isPreviewingMarketRouting:A=!1,marketRoutingImpact:j=null,marketRoutingError:M=null,onRetryMarketRouting:N,marketRoutingNotice:P=null,assignmentImpact:F=null,isPreviewingAssignmentImpact:I=!1,assignmentImpactError:L=null,onRetryAssignmentImpact:R,assignmentNotice:z=null,onReplaceAssignments:ee,isReplacingAssignments:te=!1,onBack:ne,onContinue:re}){let[B,ie]=(0,Q.useState)(``),[ae,oe]=(0,Q.useState)(!1),[V,se]=(0,Q.useState)(!1),[H,ce]=(0,Q.useState)(``),[le,ue]=(0,Q.useState)(``),[de,fe]=(0,Q.useState)(null);if(Sv(t))return(0,$.jsx)(`section`,{"aria-label":`Queries`,children:(0,$.jsx)(Fv,{message:t.message})});let pe=xv(e),me=v,he=y,ge=Tv(me,n,_),_e=ge.length,U=_e>0&&i.length>0&&!a&&!o&&!I&&F!==null&&L===null,ve=u??d,ye=B.trim().toLocaleLowerCase(),be=ye?r.filter(e=>Mv(e).toLocaleLowerCase().includes(ye)):r,xe=be.filter(e=>(e.propertyIds?.length??0)===0),Se=V?xe:be,Ce=ae?Se:Se.slice(0,bv),we=Ce.filter(e=>!jv(e)),Te=[...new Set(H.split(`
|
|
7
|
-
`).map(e=>e.trim()).filter(Boolean))],Ee=[...le.matchAll(/\{([a-z][\w-]*)\}/gi)].map(e=>e[1]),De=n.filter(e=>ge.includes(e.id)),Oe=Ee.length===0||le.trim()===``?[]:De.map(e=>({propertyId:e.id,text:Ee.reduce((t,n)=>t.replaceAll(`{${n}}`,e.label),le.trim())})),ke=[...new Set(Oe.map(e=>e.text))];function Ae(){let e=new Set([...i,...we.map(e=>e.id)]);c(r.filter(t=>e.has(t.id)).map(e=>e.id))}return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-queries-title`,className:`space-y-5`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{id:`advanced-measurement-queries-title`,children:`Queries`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose queries, then apply them to locations.`})]})}),pe?(0,$.jsx)(Pv,{}):null,pe?null:(0,$.jsxs)(`fieldset`,{className:`border-y border-default py-4`,children:[(0,$.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Apply to`}),(0,$.jsxs)(`div`,{className:`mt-3 grid max-w-2xl gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Locations or group`}),(0,$.jsxs)(`select`,{"aria-label":`Apply to`,value:me.kind===`none`?``:me.kind===`all`?`all`:me.kind===`specific`?`specific`:`group:${me.groupIds[0]??``}`,onChange:e=>{let t=e.currentTarget.value;t===`all`?he({kind:`all`}):t===`specific`?he({kind:`specific`,propertyIds:[]}):t.startsWith(`group:`)&&he({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,$.jsx)(`option`,{value:``,disabled:!0,children:`Choose where to apply`}),(0,$.jsxs)(`option`,{value:`all`,children:[`Every location (`,n.length,`)`]}),_.length>0?(0,$.jsx)(`optgroup`,{label:`Groups`,children:_.map(e=>{let t=Tv({kind:`groups`,groupIds:[e.id]},n,_).length;return(0,$.jsx)(`option`,{value:`group:${e.id}`,disabled:t===0,children:Dv(e,n)},e.id)})}):null,(0,$.jsx)(`option`,{value:`specific`,children:`Specific locations…`})]})]}),b.length>0&&S?(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Answer engine`}),(0,$.jsxs)(`select`,{"aria-label":`Answer engine for these assignments`,value:x,onChange:e=>S(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,$.jsx)(`option`,{value:``,children:`Keep existing or use portfolio defaults`}),b.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]}):null]}),b.length>0?(0,$.jsx)(`p`,{className:`mt-2 max-w-2xl text-copy-14 text-secondary`,children:`The answer engine is saved on assignments for these locations or groups.`}):null,me.kind===`groups`?(0,$.jsxs)(`div`,{className:`mt-3 max-w-2xl space-y-3`,children:[(0,$.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:me.groupIds.map(e=>{let t=_.find(t=>t.id===e);return t?(0,$.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:[Dv(t,n),(0,$.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=me.groupIds.filter(e=>e!==t.id);he(e.length>0?{kind:`groups`,groupIds:e}:{kind:`none`})},children:`×`})]},t.id):null})}),_.some(e=>!me.groupIds.includes(e.id)&&Tv({kind:`groups`,groupIds:[e.id]},n,_).length>0)?(0,$.jsxs)(`label`,{className:`block max-w-sm`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Add another group`}),(0,$.jsxs)(`select`,{"aria-label":`Add another group`,value:``,onChange:e=>{e.currentTarget.value&&he({kind:`groups`,groupIds:[...me.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,$.jsx)(`option`,{value:``,children:`Choose a group`}),_.filter(e=>!me.groupIds.includes(e.id)).map(e=>{let t=Tv({kind:`groups`,groupIds:[e.id]},n,_).length;return(0,$.jsx)(`option`,{value:e.id,disabled:t===0,children:Dv(e,n)},e.id)})]})]}):null,_e===0?(0,$.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,me.kind===`specific`?(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(Nv,{legend:`Specific locations`,properties:n,selectedPropertyIds:me.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:e=>{he({kind:`specific`,propertyIds:e})}})}):null,(0,$.jsx)(`p`,{className:`mt-3 max-w-2xl text-copy-14 text-secondary`,children:`Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries.`})]}),pe||C.length===0||b.length===0||!T||!D||!O?null:(0,$.jsxs)(`fieldset`,{className:`border-b border-default pb-4`,children:[(0,$.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`Market routing`}),(0,$.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,$.jsxs)(`div`,{className:`mt-3 grid max-w-2xl gap-3 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Market`}),(0,$.jsxs)(`select`,{"aria-label":`Market to route`,value:w,onChange:e=>T(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,$.jsx)(`option`,{value:``,children:`Choose a market`}),C.map(e=>(0,$.jsxs)(`option`,{value:e.id,children:[e.label,` · `,e.measurementCount,` saved measurement`,e.measurementCount===1?``:`s`]},e.id))]})]}),(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Answer engine`}),(0,$.jsxs)(`select`,{"aria-label":`Answer engine for this market`,value:E,onChange:e=>D(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,$.jsx)(`option`,{value:``,children:`Choose an answer engine`}),b.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.label},e.id))]})]})]}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:!w||!E||o||k||A||j===null||j.changedMeasurements===0||M!==null,onClick:()=>{O()},children:k?`Saving market routing…`:`Save market routing`}),P?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:P}):null]}),(0,$.jsxs)(`div`,{className:`mt-2 min-h-5`,children:[A?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Calculating market impact…`}):null,j?(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[j.changedMeasurements,` of `,j.matchedMeasurements,` saved measurement`,j.matchedMeasurements===1?``:`s`,` will change`,` · `,j.addedProviderCalls,` new provider request`,j.addedProviderCalls===1?``:`s`,` · `,j.fullRunProviderCalls,` per full run`]}):M?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:M}),N?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:N,children:`Retry impact`}):null]}):null]})]}),pe||!f?null:(0,$.jsxs)(`details`,{open:r.length===0,className:`border-y border-default py-4`,children:[(0,$.jsx)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong text-heading`,children:`Add queries`}),(0,$.jsxs)(`div`,{className:`pt-3`,children:[(0,$.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,$.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,$.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:H,onChange:e=>ce(e.currentTarget.value),placeholder:`best apartments in dallas
|
|
8
|
-
luxury apartments atlanta
|
|
9
|
-
pet friendly apartments austin`}),h?(0,$.jsx)(`p`,{role:`alert`,className:`mt-2 text-copy-14 text-negative`,children:h}):null,(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:Te.length===0||m||o,onClick:()=>{Promise.resolve(f(Te)).then(()=>ce(``),()=>{})},children:m?`Adding…`:`Add ${Te.length||``} ${Te.length===1?`query`:`queries`}`.replace(` `,` `)}),g?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:g,children:`Manage project queries`}):null]}),(0,$.jsxs)(`div`,{className:`mt-4 border-t border-default pt-4`,children:[(0,$.jsx)(`h4`,{className:`m-0 text-heading-14 text-heading`,children:`Write one query for every Property`}),(0,$.jsxs)(`p`,{className:`mt-1 mb-2 text-copy-14 text-secondary`,children:[`Put `,(0,$.jsx)(`code`,{className:`rounded bg-bg-elevated px-1`,children:`{property}`}),` where the Property name belongs. You get one query per selected Property.`]}),(0,$.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:le,onChange:e=>ue(e.target.value),placeholder:`apartments near {property}`}),le.trim()===``?null:Ee.length===0?(0,$.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.`]}):De.length===0?(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-caution`,children:`Select at least one Property to write queries for.`}):(0,$.jsxs)(`div`,{className:`mt-2 material-base p-3`,children:[(0,$.jsxs)(`p`,{className:`m-0 text-copy-14 text-secondary`,children:[ke.length,` `,ke.length===1?`query`:`queries`,`, one per selected Property:`]}),(0,$.jsx)(`ul`,{className:`mt-1 mb-0 list-none space-y-0.5 p-0`,children:ke.slice(0,3).map(e=>(0,$.jsx)(`li`,{className:`text-label-14 text-strong`,children:e},e))}),ke.length>3?(0,$.jsxs)(`p`,{className:`mt-1 mb-0 text-copy-14 text-secondary`,children:[`and `,ke.length-3,` more`]}):null]}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`mt-2 pointer-coarse:min-h-11`,disabled:Oe.length===0||m||o||!p,onClick:()=>{p&&Promise.resolve(p(Oe)).then(()=>ue(``),()=>{})},children:m?`Adding…`:`Add ${Oe.length||``} ${Oe.length===1?`query`:`queries`}`.replace(` `,` `)}),Oe.length>0?(0,$.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`,` `,Oe.length,` assignment`,Oe.length===1?``:`s`,`.`]}):null]})]})]}),pe?null:(0,$.jsx)(`div`,{className:`space-y-3 border-y border-default py-4`,children:r.length===0?null:(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:we.length===0,onClick:Ae,children:`Select all shown queries`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:i.length===0,onClick:()=>c([]),children:`Clear query selection`}),(0,$.jsx)(q,{type:`button`,size:`sm`,className:`pointer-coarse:min-h-11`,disabled:!U,onClick:()=>{l({queryIds:i,propertyIds:ge,...me.kind===`groups`?{groupIds:me.groupIds}:{}})},children:a?`Assigning queries…`:`Assign ${i.length||``} ${i.length===1?`query`:`queries`}${me.kind===`none`?``:` to ${Ev(me,_,_e)}`}`.replace(` `,` `)}),(0,$.jsxs)(`div`,{className:`min-h-[2.75rem]`,children:[I?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Calculating assignment impact…`}):null,F?(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` → `,F.assignmentCount,` Property assignment`,F.assignmentCount===1?``:`s`,` · `,F.addedAssignments,` new, `,F.alreadyPresentAssignments,` already assigned`,` · `,F.fullRunProviderCalls,` provider request`,F.fullRunProviderCalls===1?``:`s`,` per full run`,` · `,F.addedProviderCalls,` new`,me.kind===`groups`?` · ${F.resolvedPropertyCount} unique ${F.resolvedPropertyCount===1?`Property`:`Properties`}${F.overlapCount>0?`, ${F.overlapCount} in overlapping groups`:``}`:``,`. Existing assignments stay in place.`]}):L?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:L}),R?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:R,children:`Retry impact`}):null,ne?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:ne,children:`Back to Groups`}):null]}):me.kind===`none`?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Choose where to apply first.`}):(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` × `,_e,` Properties = `,i.length*_e,` assignments`]})]}),z?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:z}):null]})}),r.length>0?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search queries`}),(0,$.jsx)(`input`,{type:`search`,value:B,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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsxs)(`p`,{className:`m-0 text-copy-14 text-secondary`,children:[`Showing `,Ce.length,` of `,Se.length,` queries,`,` `,be.length-xe.length,` of `,be.length,` applied`]}),pe||xe.length===0?null:(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>{se(e=>!e),oe(!1)},children:V?`Show all queries`:`Show the ${xe.length} not applied`})]})]}):null,Ce.length>0?(0,$.jsx)(`div`,{className:`relative overflow-x-auto border-y border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[pe?null:(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Select query`})}),(0,$.jsx)(`th`,{children:`Query`}),(0,$.jsx)(`th`,{children:`Properties`}),pe?null:(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Clear query assignments`})})]})}),(0,$.jsx)(`tbody`,{children:Ce.map(e=>{let t=jv(e),r=Mv(e),a=i.includes(e.id),s=(e.propertyIds?.length??0)>0;return(0,$.jsxs)(`tr`,{children:[pe?null:t?(0,$.jsx)(`td`,{"aria-hidden":`true`}):(0,$.jsx)(`td`,{className:`p-0`,children:(0,$.jsx)(`label`,{className:`flex min-h-11 min-w-11 cursor-pointer items-center justify-center`,children:(0,$.jsx)(`input`,{"aria-label":`Select query ${r}`,checked:a,type:`checkbox`,onChange:t=>c(Cv(i,e.id,t.currentTarget.checked)),className:`size-6 accent-accent`})})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:r})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:wv(e.propertyIds??[],n)}),pe?null:(0,$.jsx)(`td`,{className:`text-right`,children:s?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-1`,children:[ee?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o||te,onClick:()=>fe({queryId:e.id,propertyIds:[...e.propertyIds??[]]}),"aria-label":`Replace query assignments for ${r}`,children:`Replace assignments`}):null,(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:()=>{ve(e.id)},"aria-label":`Clear query assignments for ${r}`,children:`Clear assignments`})]}):null})]},e.id)})})]})}):r.length>0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No queries match this search.`}):null,pe||!de?null:(()=>{let e=r.find(e=>e.id===de.queryId),t=e?Mv(e):`this query`,i=de.propertyIds.filter(e=>n.some(t=>t.id===e));return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-replace-assignments-title`,className:`border-y border-default py-4`,children:[(0,$.jsx)(`h4`,{id:`advanced-measurement-replace-assignments-title`,className:`text-heading-14 text-heading`,children:`Replace assigned Properties`}),(0,$.jsxs)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:[`This replaces every Property assigned to “`,t,`”.`]}),(0,$.jsx)(`div`,{className:`mt-3`,children:(0,$.jsx)(Nv,{legend:`Properties for this query`,properties:n,selectedPropertyIds:i,onSelectedPropertyIdsChange:e=>fe(t=>t&&{...t,propertyIds:[...e]})})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:te||o,onClick:()=>fe(null),children:`Keep current assignments`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:i.length===0||te||o||!ee,onClick:()=>{ee&&Promise.resolve(ee({queryId:de.queryId,propertyIds:i}))},children:te?`Replacing assignments…`:`Replace with ${i.length} ${i.length===1?`Property`:`Properties`}`})]})]})})(),Ce.length<Se.length?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:()=>oe(!0),children:`Show all queries`}):null,pe?null:(0,$.jsxs)($.Fragment,{children:[s?null:(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`Apply at least one query to a Property before continuing.`}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${ne?`justify-between`:`justify-end`}`,children:[ne?(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:o,onClick:ne,children:`Back`}):null,(0,$.jsx)(q,{type:`button`,variant:U?`outline`:`default`,className:`pointer-coarse:min-h-11`,disabled:!s||o,onClick:re,children:`Continue`})]})]})]})}function zv({access:e,availability:t,properties:n,groups:r,groupDraft:i,isSaving:a=!1,onGroupDraftChange:o,onSaveGroup:s,onEditGroup:c,onRemoveGroup:l,onClearGroupDraft:u,membershipImport:d,onBack:f,onContinue:p}){if(Sv(t))return(0,$.jsx)(`section`,{"aria-label":`Groups`,children:(0,$.jsx)(Fv,{message:t.message})});let m=xv(e),h=i.name.trim().length>0&&i.propertyIds.length>0&&!a,g=n.filter(e=>i.propertyIds.includes(e.id)).length,_=i.name.trim().length>0||i.propertyIds.length>0||i.competitorDomains.trim().length>0,v=!m&&(c!==void 0||l!==void 0);function y(){u?u():o({name:``,propertyIds:[],competitorDomains:``})}return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-groups-title`,className:`space-y-5`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{id:`advanced-measurement-groups-title`,children:`Groups`}),(0,$.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.`})]})}),m?(0,$.jsx)(Pv,{}):null,m||!d?null:(0,$.jsx)(Iv,{value:d}),m?null:(0,$.jsxs)(`div`,{className:`space-y-4 border-y border-default py-4`,children:[(0,$.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Group name`}),(0,$.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:`Waterfront venues`})]}),(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong text-heading`,children:[g,` of `,n.length,` Properties selected`]}),(0,$.jsx)(`div`,{className:`pt-3`,children:(0,$.jsx)(Nv,{legend:`Properties in this group`,properties:n,selectedPropertyIds:i.propertyIds,onSelectedPropertyIdsChange:e=>o({...i,propertyIds:e})})})]}),(0,$.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Competitor domains`}),(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,disabled:!h,onClick:()=>{s(i)},children:a?`Saving group…`:`Save group`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,disabled:!_,onClick:y,children:`Clear form`}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only.`})]}),_?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`Save this group or clear the form before continuing.`}):null]}),(0,$.jsx)(`div`,{className:`overflow-x-auto border-y border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[620px]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Group`}),(0,$.jsx)(`th`,{children:`Properties`}),(0,$.jsx)(`th`,{children:`Competitors`}),v?(0,$.jsx)(`th`,{children:`Actions`}):null]})}),(0,$.jsx)(`tbody`,{children:r.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.name}),(0,$.jsx)(`td`,{className:`text-secondary`,children:wv(e.propertyIds,n)}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.competitors.length>0?e.competitors.join(`, `):`None`}),v?(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsxs)(`div`,{className:`flex justify-end gap-1`,children:[c?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`Edit ${e.name}`,onClick:()=>c(e),children:`Edit`}):null,l?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,"aria-label":`Remove ${e.name}`,onClick:()=>{l(e.id)},children:`Remove`}):null]})}):null]},e.id))})]})}),r.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No groups have been added.`}):null,m?null:(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${f?`justify-between`:`justify-end`}`,children:[f?(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:f,children:`Back`}):null,(0,$.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:_,onClick:p,children:r.length===0&&!_?`Continue without groups`:`Continue`})]})]})}function Bv({access:e,availability:t,counts:n,flaggedExceptions:r,sitemapReview:i,onBack:a,onReviewChanges:o,isReviewing:s=!1,canReviewChanges:c=!0,reviewedChanges:l,reviewChangesError:u,canPublish:d,sweepActive:f=!1,isPublishing:p=!1,onPublish:m}){let[h,g]=(0,Q.useState)(_v),[_,v]=(0,Q.useState)(_v),[y,b]=(0,Q.useState)(_v);if(Sv(t))return(0,$.jsx)(`section`,{"aria-label":`Review and publish`,children:(0,$.jsx)(Fv,{message:t.message})});let x=xv(e),S=i?.items??[],C=i?.coverageItems??[],w=S.slice(0,h),T=C.slice(0,_),E=r.slice(0,y),D=o!==void 0,O=l!=null;return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-review-title`,className:`space-y-5`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{id:`advanced-measurement-review-title`,children:`Review & publish`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Confirm the setup details before publishing.`})]})}),x?(0,$.jsx)(Pv,{}):null,i?(0,$.jsx)(`section`,{"aria-labelledby":`advanced-measurement-sitemap-review-title`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4`,children:(0,$.jsxs)(`div`,{className:`max-w-2xl space-y-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h4`,{id:`advanced-measurement-sitemap-review-title`,className:`text-heading-14 text-heading`,children:`Sitemap changes need review`}),i.exceptionCount>0?(0,$.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[i.exceptionCount,` sitemap `,i.exceptionCount===1?`entry needs`:`entries need`,` review.`]}):null,i.coverageReviewCount>0?(0,$.jsxs)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:[i.coverageReviewCount,` `,i.coverageReviewCount===1?`Property has`:`Properties have`,` URL coverage changes.`]}):null]}),i.exceptionCount>0?(0,$.jsxs)(`details`,{className:`border-y border-caution-800/30 py-3`,children:[(0,$.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong text-heading`,children:[`URLs not added to Properties (`,i.exceptionCount,`)`]}),S.length>0?(0,$.jsx)(`ul`,{className:`mt-3 space-y-3 text-label-14`,children:w.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-primary`,children:e.url}),(0,$.jsx)(`p`,{className:`mt-1 text-secondary`,children:e.reason})]},`${e.url}-${e.reason}`))}):(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Review the affected sitemap URLs before confirming.`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,w.length,` of `,S.length]}),w.length<S.length?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>g(e=>e+vv),children:`Show next 50 URLs`}):null]})]}):null,x?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`An editor must finish this review before publishing.`}):(0,$.jsxs)($.Fragment,{children:[i.coverageReviewCount>0?(0,$.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,$.jsx)(`legend`,{className:`text-label-14-strong text-heading`,children:`For changed Property URLs`}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary`,children:[`This choice applies to all `,i.coverageReviewCount,` changed `,i.coverageReviewCount===1?`Property`:`Properties`,`.`]}),(0,$.jsxs)(`details`,{className:`border-y border-caution-800/30 py-3`,children:[(0,$.jsxs)(`summary`,{className:`flex min-h-11 cursor-pointer items-center text-label-14-strong text-heading`,children:[`Review Property URL changes (`,i.coverageReviewCount,`)`]}),T.length>0?(0,$.jsxs)(`div`,{className:`mt-3 space-y-4`,children:[T.map(e=>(0,$.jsxs)(`section`,{"aria-label":`${e.property} URL changes`,children:[(0,$.jsx)(`h5`,{className:`text-heading-14 text-primary`,children:e.property}),(0,$.jsxs)(`div`,{className:`mt-2 grid gap-3 text-label-14 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Saved URLs`}),(0,$.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.savedUrls.map(e=>(0,$.jsx)(`li`,{className:`break-all text-secondary`,children:e},e))})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Current sitemap URLs`}),e.currentSitemapUrls.length>0?(0,$.jsx)(`ul`,{className:`mt-1 space-y-1`,children:e.currentSitemapUrls.map(e=>(0,$.jsx)(`li`,{className:`break-all text-secondary`,children:e},e))}):(0,$.jsx)(`p`,{className:`mt-1 text-secondary`,children:`No matching URL was found.`})]})]})]},e.property)),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,T.length,` of `,C.length]}),T.length<C.length?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>v(e=>e+vv),children:`Show next 50 URL changes`}):null]})]}):(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Review the affected Properties before confirming.`})]}),(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14 text-primary`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`advanced-measurement-coverage-resolution`,checked:i.coverageResolution===`keep-existing`,onChange:()=>i.onCoverageResolutionChange(`keep-existing`)}),`Keep existing Property URLs`]}),(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-label-14 text-primary`,children:[(0,$.jsx)(`input`,{type:`radio`,name:`advanced-measurement-coverage-resolution`,checked:i.coverageResolution===`replace-with-imported`,onChange:()=>i.onCoverageResolutionChange(`replace-with-imported`)}),`Use current sitemap URLs`]})]}):null,(0,$.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,onClick:()=>{i.onResolve()},children:`Confirm sitemap changes`})]})]})}):null,(0,$.jsx)(`div`,{className:`overflow-x-auto border-y border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[720px]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Properties`}),(0,$.jsx)(`th`,{children:`Queries`}),(0,$.jsx)(`th`,{children:`Groups`}),(0,$.jsx)(`th`,{children:`Assignments`}),(0,$.jsx)(`th`,{children:`Provider requests / run`})]})}),(0,$.jsx)(`tbody`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.properties}),(0,$.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.queries}),(0,$.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.groups}),(0,$.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.assignments??`—`}),(0,$.jsx)(`td`,{className:`tabular-nums text-heading`,children:n.providerCalls??Lv})]})})]})}),n.providerCalls===void 0?(0,$.jsx)(`p`,{className:`supporting-copy`,children:`Review changes to see how many provider requests one run will make.`}):null,n.assignments!==void 0&&n.assignments>n.queries?(0,$.jsxs)(`p`,{className:`supporting-copy`,children:[`Queries applied to groups create one assignment for every Property in each group.`,` `,n.queries,` `,n.queries===1?`query`:`queries`,` produce `,n.assignments,` assignment`,n.assignments===1?``:`s`,` here.`]}):null,l?(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-reviewed-changes-title`,className:`border-y border-default py-4`,"aria-live":`polite`,children:[(0,$.jsx)(`h4`,{id:`advanced-measurement-reviewed-changes-title`,className:`text-heading-14 text-heading`,children:l.title}),l.items.length>0?(0,$.jsx)(`ul`,{className:`mt-3 list-disc space-y-2 pl-5 text-label-14 text-secondary`,children:l.items.map((e,t)=>(0,$.jsx)(`li`,{children:e},`${e}-${t}`))}):null]}):null,(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-flagged-exceptions-title`,className:`space-y-3`,children:[(0,$.jsx)(`h4`,{id:`advanced-measurement-flagged-exceptions-title`,className:`text-heading-14 text-heading`,children:`Flagged exceptions`}),r.length===0?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No flagged exceptions.`}):(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(`div`,{className:`divide-y divide-default border-y border-default`,children:E.map(e=>(0,$.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3 py-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.title}),e.detail?(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:e.detail}):null]}),(0,$.jsx)(J,{tone:e.tone??`caution`,children:`Needs attention`})]},e.id))}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,E.length,` of `,r.length]}),E.length<r.length?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>b(e=>e+vv),children:`Show next 50 exceptions`}):null]})]})]}),x?null:(0,$.jsxs)($.Fragment,{children:[D&&u?(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:u}):null,f?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-caution`,children:`A check is queued or running. Publish after it finishes.`}):null,(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${a?`justify-between`:`justify-end`}`,children:[a?(0,$.jsx)(q,{type:`button`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:a,children:`Back`}):null,o!==void 0&&!O?(0,$.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:s||!c,onClick:()=>{o()},children:s?`Reviewing changes…`:`Review changes`}):(0,$.jsx)(q,{type:`button`,className:`pointer-coarse:min-h-11`,disabled:!d||p,onClick:()=>{m()},children:p?`Publishing setup…`:`Publish setup`})]})]})]})}var Vv={proposed:{label:`New`,tone:`caution`},confirmed:{label:`Included`,tone:`positive`},excluded:{label:`Excluded`,tone:`neutral`}};function Hv(e){return e.trim().toLocaleLowerCase()}function Uv(e,t){return!t||`${e.name} ${(e.urls??[e.url]).join(` `)}`.toLocaleLowerCase().includes(t)}function Wv({property:e}){let t=e.urls??[e.url];return t.length<=1?(0,$.jsx)(`span`,{children:t[0]??`No URL`}):(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer text-label-12-strong text-primary`,children:[t.length,` URLs`]}),(0,$.jsx)(`ul`,{className:`mt-2 space-y-1`,children:t.map(e=>(0,$.jsx)(`li`,{className:`break-all text-label-12-mono text-secondary`,children:e},e))})]})}function Gv({canEdit:e,draft:t,onDraftChange:n,onReviewSitemap:r,reviewState:i}){let a=!e||i===`reviewing`,o=a||!t.sitemapUrl.trim()||!t.examplePropertyUrl.trim()&&!t.propertyPathPattern.trim();function s(e,r){n({...t,[e]:r})}return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-import-heading`,"aria-busy":i===`reviewing`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{id:`advanced-measurement-import-heading`,className:`text-heading-20 text-heading`,children:`Import Properties`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Review sitemap entries before choosing the Properties to measure.`})]}),e?null:(0,$.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 text-label-14 text-secondary`,children:[(0,$.jsx)(J,{tone:`neutral`,children:`Viewer access`}),(0,$.jsx)(`span`,{children:`You can inspect this setup.`})]}),(0,$.jsxs)(`form`,{className:`mt-5 space-y-4`,onSubmit:e=>{e.preventDefault(),!o&&r(t)},children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-sitemap-url`,className:`text-label-14-strong text-heading`,children:`Sitemap URL`}),(0,$.jsx)(`input`,{id:`advanced-measurement-sitemap-url`,type:`url`,value:t.sitemapUrl,disabled:a,onChange:e=>s(`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,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-example-property-url`,className:`text-label-14-strong text-heading`,children:`Example Property page`}),(0,$.jsx)(`input`,{id:`advanced-measurement-example-property-url`,type:`url`,required:!t.propertyPathPattern.trim(),value:t.examplePropertyUrl,disabled:a,onChange:e=>s(`examplePropertyUrl`,e.target.value),placeholder:`https://example.com/locations/example`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-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,$.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,$.jsxs)(`details`,{className:`material-base p-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading`,children:`More import options`}),(0,$.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-preferred-host`,className:`text-label-14-strong text-heading`,children:`Use URLs from this domain`}),(0,$.jsx)(`input`,{id:`advanced-measurement-preferred-host`,value:t.preferredHost,disabled:a,onChange:e=>s(`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,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-property-path-pattern`,className:`text-label-14-strong text-heading`,children:`Property URL pattern`}),(0,$.jsx)(`input`,{id:`advanced-measurement-property-path-pattern`,value:t.propertyPathPattern,disabled:a,onChange:e=>s(`propertyPathPattern`,e.target.value),placeholder:`/locations/*`,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,$.jsxs)(`div`,{className:`grid gap-4 md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-additional-host`,className:`text-label-14-strong text-heading`,children:`Additional URL domain`}),(0,$.jsx)(`input`,{id:`advanced-measurement-additional-host`,value:t.additionalHost,disabled:a,onChange:e=>s(`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,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-additional-path-pattern`,className:`text-label-14-strong text-heading`,children:`Additional URL pattern`}),(0,$.jsx)(`input`,{id:`advanced-measurement-additional-path-pattern`,value:t.additionalPathPattern,disabled:a,onChange:e=>s(`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,$.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,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-excluded-paths`,className:`text-label-14-strong text-heading`,children:`Ignore these URL paths`}),(0,$.jsx)(`textarea`,{id:`advanced-measurement-excluded-paths`,value:t.excludedPaths,disabled:a,onChange:e=>s(`excludedPaths`,e.target.value),placeholder:`/locations/archive`,rows:3,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-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,$.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,$.jsx)(q,{type:`submit`,disabled:o,children:i===`reviewing`?`Reviewing sitemap…`:`Review sitemap`})]})]})}function Kv({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=Hv(r),m=t.filter(e=>Uv(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,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-properties-heading`,"aria-busy":n===`loading`||c,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h2`,{id:`advanced-measurement-properties-heading`,className:`text-heading-20 text-heading`,children:`Properties`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose the Properties to include, then continue.`})]}),e?null:(0,$.jsx)(`p`,{className:`mt-4 text-copy-14 text-secondary`,children:`Viewing only. Property changes are unavailable.`}),n===`loading`?(0,$.jsxs)(`div`,{className:`mt-5 material-base p-4`,children:[(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading Properties…`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`If this does not finish, refresh the list.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:l,children:`Refresh Properties`})]}):null,n===`error`?(0,$.jsxs)(`div`,{className:`mt-5 material-base p-4`,children:[(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:`Could not load Properties. Retry to request the current list.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:l,children:`Retry`})]}):null,n===`ready`&&t.length===0?(0,$.jsxs)(`div`,{className:`mt-5 material-base p-4`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Properties were found.`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Check the sitemap and review it again.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:!e,onClick:u,children:`Review sitemap`})]}):null,n===`ready`&&t.length>0?(0,$.jsxs)(`div`,{className:`mt-5`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-3`,children:[(0,$.jsxs)(`label`,{className:`block min-w-48 flex-1`,children:[(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:`Search Properties`}),(0,$.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,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:c,onClick:S,children:`Select all shown`}),(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:c||v.length===0,onClick:C,children:`Clear selection`})]}):null]}),m.length===0?(0,$.jsxs)(`div`,{className:`mt-4 material-base p-4`,children:[(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`No Properties match this search.`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Clear the search or review the sitemap again.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:!e,onClick:u,children:`Review sitemap`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap items-center justify-between gap-2 text-label-14 text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`Showing `,g.length,` of `,m.length,` Properties`]}),(0,$.jsxs)(`p`,{children:[v.length,` of `,t.length,` selected`]})]}),(0,$.jsx)(`div`,{className:`mt-2 overflow-x-auto rounded-md border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-150 text-left text-label-14`,"aria-label":`Properties to review`,children:[(0,$.jsx)(`thead`,{className:`bg-surface-subtle text-label-12-strong normal-case text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2`,children:`Property`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2`,children:`URL`}),(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2`,children:`State`}),e?(0,$.jsx)(`th`,{scope:`col`,className:`px-3 py-2 text-right`,children:`Include`}):null]})}),(0,$.jsx)(`tbody`,{children:g.map(t=>{let n=Vv[t.state];return(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-3 py-3 text-label-14-strong text-heading`,children:t.name}),(0,$.jsx)(`td`,{className:`max-w-96 px-3 py-3 text-label-12-mono text-secondary`,children:(0,$.jsx)(Wv,{property:t})}),(0,$.jsx)(`td`,{className:`px-3 py-3`,children:(0,$.jsx)(J,{tone:n.tone,children:n.label})}),e?(0,$.jsx)(`td`,{className:`p-0 text-right`,children:(0,$.jsx)(`label`,{className:`ml-auto flex min-h-11 min-w-11 cursor-pointer items-center justify-center`,children:(0,$.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,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:c,onClick:f,children:`Show all Properties`}):null]}),e?(0,$.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3`,children:[(0,$.jsx)(q,{type:`button`,variant:`ghost`,disabled:c,onClick:u,children:`Back`}),(0,$.jsx)(q,{type:`button`,disabled:c||v.length===0,onClick:w,children:c?`Saving Properties…`:`Continue`})]}):null]}):null]})}function qv(e){return e.activeStep===`import`?(0,$.jsx)(Gv,{canEdit:e.canEdit,draft:e.importDraft,onDraftChange:e.onImportDraftChange,onReviewSitemap:e.onReviewSitemap,reviewState:e.reviewState}):(0,$.jsx)(Kv,{...e})}var Jv=[{id:`import`,label:`Import`},{id:`properties`,label:`Properties`},{id:`groups`,label:`Groups`},{id:`queries`,label:`Queries`},{id:`review`,label:`Review and publish`}];function Yv({currentStep:e,hasDraft:t,canEdit:n,onDiscard:r,onStepChange:i,children:a}){let o=(0,Q.useRef)(null),s=(0,Q.useRef)(null),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(!1),[d,f]=(0,Q.useState)(!1);return(0,Q.useEffect)(()=>{t||f(!1)},[t]),(0,Q.useEffect)(()=>{let e=u.current;u.current=d,d?c.current?.focus():e&&l.current?.focus()},[d]),(0,Q.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,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex flex-col items-start gap-3 sm:flex-row sm:flex-wrap sm:justify-between`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 w-full sm:flex-1`,children:[(0,$.jsx)(`h2`,{children:`Advanced measurement setup`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-secondary`,children:`Choose the Properties and queries you want to measure.`})]}),t?(0,$.jsxs)(`div`,{className:`flex w-full flex-wrap items-center justify-between gap-3 sm:w-auto sm:justify-end`,children:[(0,$.jsx)(J,{tone:`caution`,children:`Unpublished changes`}),n&&r?d?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,role:`group`,"aria-label":`Confirm discard`,children:[(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Discard all unpublished changes?`}),(0,$.jsx)(q,{ref:c,type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>f(!1),children:`Keep editing`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:r,children:`Discard unpublished changes`})]}):(0,$.jsx)(q,{ref:l,type:`button`,size:`sm`,variant:`ghost`,className:`pointer-coarse:min-h-11`,onClick:()=>f(!0),children:`Discard changes`}):null]}):null]}),(0,$.jsx)(`div`,{role:`group`,"aria-label":`Advanced measurement setup progress`,className:`overflow-x-auto border-b border-default`,children:(0,$.jsx)(`ol`,{className:`flex min-w-max gap-6`,children:Jv.map(t=>(0,$.jsx)(`li`,{children:i?(0,$.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,$.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,$.jsx)(`div`,{ref:s,children:a})]})}function Xv(e){let t=e.canEdit?`editor`:`viewer`;return e.currentStep===`import`||e.currentStep===`properties`?(0,$.jsx)(qv,{...e.importProperties,activeStep:e.currentStep,canEdit:e.canEdit}):e.currentStep===`queries`?(0,$.jsx)(Rv,{...e.queries,access:t,onManageProjectQueries:e.onManageProjectQueries}):e.currentStep===`groups`?(0,$.jsx)(zv,{...e.groups,access:t}):`review`in e?(0,$.jsx)(Bv,{...e.review,access:t}):null}function Zv(e){return(0,$.jsx)(Yv,{currentStep:e.currentStep,hasDraft:e.hasDraft,canEdit:e.canEdit,onDiscard:e.onDiscard,onStepChange:e.onStepChange,children:Xv(e)})}var Qv={sitemapUrl:``,examplePropertyUrl:``,preferredHost:``,propertyPathPattern:``,additionalHost:``,additionalPathPattern:``,excludedPaths:``},$v={name:``,propertyIds:[],competitorDomains:``},ey=50,ty=[],ny={};function ry(e){let t=e.trim();if(!t)return null;try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLocaleLowerCase()}catch{return null}}function iy(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 ay(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 oy(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 sy(e){let t=iy(e.sitemapUrl),n=e.examplePropertyUrl.trim()?ry(e.examplePropertyUrl):null,r=ry(e.preferredHost)??n??ry(t);if(!r)throw Error(`Add a valid sitemap or Property page URL.`);let i=ry(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=oy(e.excludedPaths);return{sitemapUrl:t,rule:{primary:{host:r,pathTemplate:ay(e)},...i?{aliases:[{host:i,pathTemplate:ay({...e,examplePropertyUrl:``,propertyPathPattern:e.additionalPathPattern})}]}:{},...o.length>0?{excludedSlugPatterns:o}:{}}}}function cy(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 ly(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 uy(e){return[...new Set([...e.discoveredUrl?[e.discoveredUrl]:[],...e.urlMatchers])]}function dy(e){return e===`included`?`confirmed`:e===`excluded`?`excluded`:`proposed`}function fy(e){return e?.authoring.targets.filter(e=>e.status!==`excluded`).map(e=>e.stableKey)??[]}function py(e,t){return`${t}-${e.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,`-`).replace(/^-+|-+$/g,``)||`item`}`.slice(0,128)}function my(e){return ry(e)}function hy(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 gy(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 _y(e,t){return t[0]===`assignments`&&typeof t[1]==`number`?e?.assignments[t[1]]:void 0}function vy(e,t){return e?.targets.find(e=>e.stableKey===t)?.label??`a Property`}function yy(e,t){let n=hy(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 by(e,t){let n=gy(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=vy(e.authoring,n.targetKeys[i]);return`${n.label} — ${t}`}return n.label}function xy(e,t){let n=_y(e.authoring,t.path);if(!n)return;let r=e.queries.find(e=>e.id===n.queryId)?.query??`an unavailable query`;return`${vy(e.authoring,n.targetKey)} — ${r}`}function Sy(e,t){return t.path[0]===`identities`?`Project domain`:yy(e,t)??by(e,t)??xy(e,t)}function Cy(e,t,n){let r=_y(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 wy(e,t){let n=Sy(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,Cy(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,Cy(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 Ty(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function Ey(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 Dy(e,t,n,r){return`${(()=>{switch(e){case`execution-context-no-provider`:return`${t} ${Ty(n,`query assignment`)} need${n===1?`s`:``} a provider.`;case`target-without-aliases`:return`${t} ${Ty(n,`Property`,`Properties`)} need${n===1?`s`:``} aliases.`;case`target-without-assignments`:return`${t} ${Ty(n,`Property`,`Properties`)} need${n===1?`s`:``} queries.`;default:return n>1?`${t} ${Ty(n,`item`)} need review.`:t}})()}${Ey(r)}`}function Oy(e,t){let n=new Map;for(let r of e){let e=wy(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:Dy(e.ruleId,e.meaning.detail,e.paths.size,e.affected),tone:e.meaning.tone}))}function ky(e){if(!e)return;let t=e.discoveredUrl??e.urlMatchers[0];return t?`${e.label} — ${t}`:e.label}function Ay(e,t,n){let r=hy(n,e.path),i=gy(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=Ey(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=ky(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=ky(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=ky(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 jy(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 My(e){return[...new Set(e)]}function Ny(e){return My(e).sort()}function Py(e,t,n,r){return e.kind===`groups`?{groupKeys:Ny(e.groupIds),queryIds:Ny(n),...r?{contextOverride:r}:{}}:{targetKeys:Ny(e.kind===`all`?t:e.kind===`specific`?e.propertyIds:[]),queryIds:Ny(n),...r?{contextOverride:r}:{}}}function Fy(e,t){return t===void 0?e:JSON.stringify([e,t])}function Iy(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 Ly(e){return e.kind===`exact`?e.url??``:e.kind===`prefix`?`https://${e.host??``}${e.pathPrefix===`/`?``:e.pathPrefix??``}/*`:e.host??``}function Ry(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(Ly).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(Ly).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:py(e,`competitor`),label:e,domain:e,aliases:[]}))}))}}function zy({projectName:e,queries:t,isQueryLoading:n,isQueryError:r,onRetryQueries:i,publishedPlan:a,canEdit:o=!0,sweepActive:s=!1,executionProviders:c=ty,executionProviderModels:l=ny,onCreateQueries:u,onManageProjectQueries:d,onPublished:f,service:p=Ls}){let[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(`import`),[b,x]=(0,Q.useState)(!0),[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)([]),[O,k]=(0,Q.useState)({...Qv}),[A,j]=(0,Q.useState)(`idle`),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(ey),[I,L]=(0,Q.useState)([]),[R,z]=(0,Q.useState)([]),[ee,te]=(0,Q.useState)({kind:`none`}),[ne,re]=(0,Q.useState)(``),[B,ie]=(0,Q.useState)(``),[ae,oe]=(0,Q.useState)(``),[V,se]=(0,Q.useState)(null),[H,ce]=(0,Q.useState)(null),[le,ue]=(0,Q.useState)(!1),[de,fe]=(0,Q.useState)(null),[pe,me]=(0,Q.useState)(0),[he,ge]=(0,Q.useState)(null),[_e,U]=(0,Q.useState)(null),[ve,ye]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(null),[we,Te]=(0,Q.useState)(0),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)({...$v}),[Ae,je]=(0,Q.useState)(null),[W,Me]=(0,Q.useState)(``),[Ne,Pe]=(0,Q.useState)(null),[Fe,Ie]=(0,Q.useState)(!1),[Le,Re]=(0,Q.useState)(!1),[ze,Be]=(0,Q.useState)(null),[Ve,He]=(0,Q.useState)(null),[Ue,We]=(0,Q.useState)(null),[Ke,qe]=(0,Q.useState)(null),[Je,Ye]=(0,Q.useState)(null),Xe=(0,Q.useRef)(0),Ze=(0,Q.useRef)(0),Qe=(0,Q.useRef)(0),$e=g?.draft??null,et=g?.etag??null,tt=(0,Q.useMemo)(()=>!o&&a?{baseActiveRevision:a.revision,authoring:Ry(a)}:null,[o,a]),G=$e??tt;async function nt(t){let n=++Xe.current;x(!0),C(null);try{let[r,i]=await Promise.all([p.loadSetup(e),p.loadDraft(e)]);if(!i.draft&&t&&o&&(await p.createDraft(e,r.activeRevision),[r,i]=await Promise.all([p.loadSetup(e),p.loadDraft(e)])),n!==Xe.current)return;h(r),_(i),y(cy(i.draft));let a=fy(i.draft);L(a)}catch(e){if(n!==Xe.current)return;C(Ms(e,`Could not load advanced measurement setup.`))}finally{n===Xe.current&&x(!1)}}(0,Q.useEffect)(()=>(nt(!0),()=>{Xe.current+=1}),[e,o,p]),(0,Q.useEffect)(()=>{!b&&!$e&&tt&&y(`properties`)},[$e,b,tt]);async function rt(){let t=await p.loadDraft(e);return _(t),t}async function it(t){Ye(null);try{let[n,r]=await Promise.all([p.loadSetup(e),p.loadDraft(e)]);h(n),_(r);let i=fy(r.draft);L(i),y(e=>ly(r.draft,e)),T(t)}catch(e){T(Ms(e,t))}}async function at(e,t,n,r={}){let{preserveBusyAction:i=!1}=r;if(!o||!et||Ue&&!i)return null;i||We(e),T(null),Ye(null);try{let e=await t(et),n=await rt();return D((e.warnings??[]).map((e,t)=>Ay(e,t,n.draft?.authoring))),n}catch(e){return Is(e)?await it(`This setup changed in another session. The latest draft is loaded; review your changes again.`):T(Ms(e,n)),null}finally{i||We(null)}}let ot=(0,Q.useMemo)(()=>(G?.authoring.targets??[]).map(e=>{let t=uy(e);return{id:e.stableKey,name:e.label,url:t[0]??`No URL`,urls:t,state:dy(e.status)}}),[G]),st=(0,Q.useMemo)(()=>G?.authoring.targets.filter(e=>e.status===`included`)??[],[G]),ct=(0,Q.useMemo)(()=>st.map(e=>({id:e.stableKey,label:e.label,urlCount:uy(e).length})),[st]),lt=G?.authoring.assignments.length??0,dt=(0,Q.useMemo)(()=>{if(!G)return[];let e=new Set(t.map(e=>e.id)),n=t.map(e=>({id:e.id,text:e.query,source:`saved-project-queries`,propertyIds:My(G.authoring.assignments.filter(t=>t.queryId===e.id).map(e=>e.targetKey))})),r=My(G.authoring.assignments.map(e=>e.queryId).filter(t=>!e.has(t))).map(e=>({id:e,source:`unavailable-tracked-query`,state:`missing`,propertyIds:My(G.authoring.assignments.filter(t=>t.queryId===e).map(e=>e.targetKey))}));return[...n,...r]},[t,G]),ft=(0,Q.useMemo)(()=>(G?.authoring.groups??[]).map(e=>({id:e.stableKey,name:e.label,propertyIds:e.targetKeys,competitors:e.competitors.map(e=>e.domain)})),[G]),pt=(0,Q.useMemo)(()=>(G?.authoring.reportingScopes??[]).map(e=>({id:e.stableKey,label:e.label,measurementCount:e.usageEdges.length})),[G]),mt=(0,Q.useMemo)(()=>{let e=new Map,t=(t,n={})=>{for(let r of t){if(!Ge(r))continue;let t=ut(r)?void 0:n[r],i=Fy(r,t);e.has(i)||e.set(i,{id:i,provider:r,label:t?`${oo(r)} · ${t}`:oo(r),...t?{model:t}:{}})}};t(c,l);let n=G?.authoring.defaultContext;n&&t(n.providers,n.models);for(let e of G?.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()]},[l,c,G]),ht=(0,Q.useMemo)(()=>{if(!ne)return;let e=mt.find(e=>e.id===ne);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[ne,mt]),gt=(0,Q.useMemo)(()=>{if(!ae)return;let e=mt.find(e=>e.id===ae);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[mt,ae]),_t=(0,Q.useMemo)(()=>B&>?{marketKeys:[B],contextOverride:gt}:null,[gt,B]),vt=_t?JSON.stringify(_t):``,yt=(0,Q.useMemo)(()=>!V||H!==vt||V.draftEtag!==et?null:{matchedMeasurements:V.matchedEdges,changedMeasurements:V.changedEdges,addedProviderCalls:V.execution.addedProviderCalls,fullRunProviderCalls:V.execution.fullRunProviderCalls},[et,V,H,vt]);(0,Q.useEffect)(()=>{ne&&!mt.some(e=>e.id===ne)&&re(``)},[ne,mt]),(0,Q.useEffect)(()=>{ae&&!mt.some(e=>e.id===ae)&&oe(``)},[mt,ae]),(0,Q.useEffect)(()=>{B&&!pt.some(e=>e.id===B)&&ie(``)},[B,pt]);let bt=(0,Q.useMemo)(()=>{if(R.length===0)return null;let e=Py(ee,ct.map(e=>e.id),R,ht);return(e.groupKeys?.length??e.targetKeys?.length??0)>0?e:null},[ht,ee,ct,R]),xt=bt?JSON.stringify(bt):``;(0,Q.useEffect)(()=>{let t=bt,n=++Ze.current;if(!o||!$e||!et||!t){U(null),ye(null),Ce(null),xe(!1);return}U(null),ye(null),Ce(null),xe(!0);let r=window.setTimeout(()=>{p.previewAssignments(e,t).then(e=>{n===Ze.current&&(e.draftEtag===et?(U(e),ye(xt)):(U(null),ye(null),Ce(`The setup changed while calculating assignment impact. Refresh the draft and try again.`)))}).catch(e=>{n===Ze.current&&(U(null),ye(null),Ce(Ps(e)))}).finally(()=>{n===Ze.current&&xe(!1)})},250);return()=>{window.clearTimeout(r),Ze.current+=1}},[bt,xt,we,o,$e,et,e,p]),(0,Q.useEffect)(()=>{let t=_t,n=++Qe.current;if(!o||!$e||!et||!t){se(null),ce(null),fe(null),ue(!1);return}se(null),ce(null),fe(null),ue(!0);let r=window.setTimeout(()=>{p.previewMarketRouting(e,t).then(e=>{n===Qe.current&&(e.draftEtag===et?(se(e),ce(vt)):fe(`The setup changed while calculating market impact. Refresh the draft and try again.`))}).catch(e=>{n===Qe.current&&fe(Ms(e,`Could not calculate market routing impact.`))}).finally(()=>{n===Qe.current&&ue(!1)})},250);return()=>{window.clearTimeout(r),Qe.current+=1}},[o,$e,et,_t,pe,vt,e,p]);let St=(0,Q.useMemo)(()=>[...lt===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`}]:[],...G?.authoring.assignments.some(e=>e.queryClass===`unclassified`)&&!(tt&&a?.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`}]:[],...E],[lt,tt,a,E,G]),Ct=n?{status:`unavailable`,message:`Tracked queries are loading.`}:r?{status:`unavailable`,message:`Tracked queries could not be loaded. Retry before assigning Properties.`}:{status:`available`};async function wt(t){let n;try{n=sy(t)}catch(e){T(Ms(e,`Check the sitemap details and try again.`));return}k(t),j(`reviewing`);let r=await at(`import`,t=>p.importSitemap(e,t,n),`Could not review this sitemap.`);if(r?.draft){let e=r.draft.authoring.targets.filter(e=>e.status===`proposed`).map(e=>e.stableKey),t=r.draft.authoring.targets.filter(e=>e.status===`included`).map(e=>e.stableKey);L([...t,...e]),N(``),F(ey),y(`properties`),j(`idle`)}else j(`error`)}async function Tt(e){if(!u||e.length===0||Ue)return[];We(`create-queries`),qe(null);try{return await u(e)}catch(e){throw qe(Bs(e)),e}finally{We(null)}}async function Et(t){if(!$e||!et||Ue)return;let n=new Set(t),r=$e.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||$e.authoring.targets.some(e=>e.status!==`proposed`&&e.status===`included`!==n.has(e.stableKey));We(`properties`),T(null),Ye(null);try{if(!i){L([...n]),te({kind:`none`}),y(`groups`);return}await p.applySitemapSelection(e,et,r,[...n]);let t=fy((await rt()).draft);L(t),te({kind:`none`}),y(`groups`)}catch(e){Is(e)?await it(`This setup changed in another session. The latest Properties are loaded.`):T(Ms(e,`Could not save the selected Properties.`))}finally{We(null)}}async function Dt(t){let n=t.groupIds&&t.groupIds.length>0?{groupKeys:Ny(t.groupIds),queryIds:Ny(t.queryIds),...ht?{contextOverride:ht}:{}}:{targetKeys:Ny(t.propertyIds),queryIds:Ny(t.queryIds),...ht?{contextOverride:ht}:{}};!_e||ve!==JSON.stringify(n)||!et||_e.draftEtag!==et?T(`Review the latest assignment impact before assigning queries.`):await at(`assignments`,t=>p.applyAssignments(e,t,n),`Could not apply these queries.`)&&(z([]),De(`${_e.assignments.added} new assignment${_e.assignments.added===1?``:`s`} added. Existing assignments were kept.`))}async function Ot(t){t.propertyIds.length!==0&&await at(`replace-assignments`,n=>p.replaceAssignments(e,n,{targetKeys:My(t.propertyIds),queryIds:[t.queryId],...ht?{contextOverride:ht}:{}}),`Could not replace this query assignment.`)&&(z(e=>e.filter(e=>e!==t.queryId)),De(`Query assignments replaced.`))}async function kt(){if(!_t||!V||H!==JSON.stringify(_t)||!et||V.draftEtag!==et){T(`Review the latest market routing impact before saving.`);return}let t=pt.find(e=>e.id===B);await at(`route-markets`,t=>p.routeMarkets(e,t,_t),`Could not save this market routing.`)&&ge(`${t?.label??`Market`} routing saved. Existing locations were preserved.`)}async function At(t,n=!1){if(t.length!==0&&!await at(`paired-assignments`,n=>ht?p.applyPairedAssignments(e,n,[...t],ht):p.applyPairedAssignments(e,n,[...t]),`Could not assign these queries.`,{preserveBusyAction:n}))throw Error(`Could not assign these queries.`)}async function jt(e){if(o&&u&&e.length!==0&&!Ue){We(`create-and-pair-questions`),qe(null);try{let t;try{t=await u(My(e.map(e=>e.text)))}catch(e){throw qe(Bs(e)),e}let n=new Map(t.map(e=>[e.query,e.id])),r=e.map(e=>({targetKey:e.propertyId,queryId:n.get(e.text)})).filter(e=>e.queryId!==void 0);if(r.length!==e.length){let e=Error(`The created queries could not be matched to their Properties.`);throw qe(`The queries were added, but could not be paired with every Property. Try again to pair them.`),e}try{await At(r,!0)}catch(e){throw qe(`The queries were added, but could not be assigned to their Properties. Try again to pair them.`),e}}finally{We(null)}}}async function Mt(t){if(!$e)return;let n=My($e.authoring.assignments.filter(e=>e.queryId===t).map(e=>e.targetKey));n.length!==0&&await at(`remove-${t}`,r=>p.removeAssignment(e,r,n,t),`Could not clear this query assignment.`)&&z(e=>e.filter(e=>e!==t))}async function Nt(t){if(!$e||!et||Ue)return;let n=t.name.trim();if(!n)return;let r=Ae??py(n,`group`),i=$e.authoring.groups.find(e=>e.stableKey===r);if(i&&Ae===null){T(`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=>my(e)===null);if(o){T(`"${o}" is not a valid competitor domain.`);return}let s=My(a.map(e=>my(e)));We(`group`),T(null),Ye(null);try{let a=await p.upsertGroup(e,et,{stableKey:r,label:n,targetKeys:My(t.propertyIds),competitors:s.map(e=>i?.competitors.find(t=>t.domain===e)??{stableKey:py(e,`competitor`),label:e,domain:e,aliases:[]})}),o=await rt();D(a.warnings.map((e,t)=>Ay(e,t,o.draft?.authoring))),ke({...$v}),je(null)}catch(e){Is(e)?await it(`This setup changed in another session. The latest groups are loaded.`):T(Ms(e,`Could not save this group.`))}finally{We(null)}}function Pt(e){let t=$e?.authoring.groups.find(t=>t.stableKey===e);t&&(je(e),ke({name:t.label,propertyIds:[...t.targetKeys],competitorDomains:t.competitors.map(e=>e.domain).join(`, `)}))}async function Ft(t){await at(`remove-group`,n=>p.removeGroup(e,n,t),`Could not remove this group.`)&&(te(e=>e.kind===`groups`&&e.groupIds.includes(t)?{kind:`none`}:e),Ae===t&&(je(null),ke({...$v})))}function It(e){Me(e),Pe(null),Be(null),He(null)}async function Lt(){if(o&&W.trim()&&!Fe&&!Le){Ie(!0),Be(null),He(null);try{Pe(await p.previewGroupMembership(e,{csv:W}))}catch(e){Pe(null),Be(Ms(e,`Could not review this CSV.`))}finally{Ie(!1)}}}async function Rt(t){if(o&&et&&Ne&&t.length!==0&&!Ue){if(Ne.draftEtag!==et)Be(`The setup changed while this CSV was open. Review the latest CSV before applying it.`);else{Re(!0),We(`group-import`),Be(null),He(null),Ye(null);try{let n=await p.applyGroupMembership(e,et,{csv:W,sourceChecksum:Ne.sourceChecksum,previewChecksum:Ne.previewChecksum,acceptedRows:My(t.map(String)).map(Number)}),r=await rt();D(n.warnings.map((e,t)=>Ay(e,t,r.draft?.authoring))),Me(``),Pe(null),He(`${n.addedMemberships} membership${n.addedMemberships===1?``:`s`} added${n.unchangedMemberships>0?`; ${n.unchangedMemberships} already present`:``}.`)}catch(e){Is(e)?(await it(`This setup changed in another session. The latest draft is loaded; review the CSV again.`),Be(`The setup changed while this CSV was open. Review the latest CSV before applying it.`)):Be(Ms(e,`Could not apply this CSV.`))}finally{We(null),Re(!1)}}}}async function zt(){if($e&&et&&!Ue&<!==0){We(`review`),T(null),Ye(null);try{let[n,r]=await Promise.all([p.compilePreview(e),p.diffPreview(e)]),i=[...n.checks,...r.checks],a=i.some(e=>e.ruleId===`active-revision-schema-v1`);if(D(Oy(i.filter(e=>e.ruleId!==`active-revision-schema-v1`),{authoring:G?.authoring,queries:t})),!n.ok||!r.ok)return;if(r.diff.activeRevision!==$e.baseActiveRevision){await it(`The published setup changed while you were reviewing. The latest draft is loaded; review it again.`);return}if(n.compiledChecksum!==r.compiledChecksum){T(`The setup changed while it was being reviewed. Review the latest changes again.`);return}Ye({etag:et,baseActiveRevision:$e.baseActiveRevision,compiledChecksum:n.compiledChecksum,changes:jy(r.diff,a),providerCalls:n.plan.executionNodes.reduce((e,t)=>e+t.expectedSnapshots,0)})}catch(e){T(Ms(e,`Could not review this setup.`))}finally{We(null)}}}async function Bt(){if($e&&et&&Je&&!Ue){if(et!==Je.etag||$e.baseActiveRevision!==Je.baseActiveRevision)Ye(null),T(`The setup changed after review. Review the latest changes before publishing.`);else{We(`publish`),T(null);try{await p.publish(e,et,{expectedActiveRevision:Je.baseActiveRevision,expectedCompiledChecksum:Je.compiledChecksum}),_({draft:null,etag:null}),Ye(null),f?.()}catch(e){Is(e)?await it(`The setup changed before it could be published. Review the latest draft and publish again.`):T(Ms(e,`Could not publish this setup.`))}finally{We(null)}}}}async function Vt(){if(et&&!Ue){We(`discard`),T(null);try{await p.discard(e,et),_({draft:null,etag:null}),Ye(null),f?.()}catch(e){Is(e)?await it(`This setup changed in another session. The latest draft is loaded.`):T(Ms(e,`Could not discard these changes.`))}finally{We(null)}}}async function Ht(){if($e&&et&&m&&!Ue){We(`restart`),T(null),Ye(null);try{await p.discard(e,et),await p.createDraft(e,m.activeRevision),k({...Qv}),N(``),L([]),z([]),te({kind:`none`}),U(null),Ce(null),De(null),ke({...$v}),je(null),Me(``),Pe(null),Be(null),He(null),await nt(!1)}catch(e){Is(e)?await it(`The setup changed again. Reloaded the latest draft and published setup.`):T(Ms(e,`Could not restart this setup.`))}finally{We(null)}}}if(b)return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-loading-title`,className:`space-y-4`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsx)(`h2`,{id:`advanced-measurement-loading-title`,children:`Advanced measurement setup`})}),(0,$.jsx)(`div`,{className:`h-28 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Loading advanced measurement setup`})]});if(S)return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-error-title`,className:`space-y-4`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsx)(`h2`,{id:`advanced-measurement-error-title`,children:`Advanced measurement setup`})}),(0,$.jsxs)(`div`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,$.jsx)(`p`,{children:S}),(0,$.jsx)(q,{className:`mt-3 pointer-coarse:min-h-11`,type:`button`,size:`sm`,variant:`outline`,onClick:()=>{nt(!0)},children:`Try again`})]})]});if(!G||o&&!et)return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-empty-title`,className:`space-y-4`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsx)(`h2`,{id:`advanced-measurement-empty-title`,children:`Advanced measurement setup`})}),(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:o?`Start setup from the project Overview.`:`No advanced setup is available to review.`})]});if(o&&$e&&m&&$e.baseActiveRevision!==m.activeRevision)return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-stale-draft-title`,className:`space-y-4`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsx)(`h2`,{id:`advanced-measurement-stale-draft-title`,children:`Advanced measurement setup`})}),(0,$.jsxs)(`div`,{role:`alert`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:`This draft is based on an older published setup.`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:`Restart from the latest setup before making more changes.`}),(0,$.jsx)(q,{className:`mt-3 pointer-coarse:min-h-11`,type:`button`,size:`sm`,variant:`outline`,disabled:Ue===`restart`,onClick:()=>{Ht()},children:Ue===`restart`?`Restarting…`:`Discard draft and restart`})]}),w?(0,$.jsx)(`p`,{role:`alert`,className:`text-copy-14 text-negative`,children:w}):null]});let Ut=r&&i?(0,$.jsx)(`div`,{className:`flex justify-end`,children:(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,className:`pointer-coarse:min-h-11`,onClick:i,children:`Retry queries`})}):null;return(0,$.jsxs)(`div`,{className:`space-y-4`,children:[m?.mode===`active-v1`?(0,$.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,w?(0,$.jsx)(`p`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-3 text-copy-14 text-negative`,children:w}):null,Ut,v===`import`||v===`properties`?(0,$.jsx)(Zv,{currentStep:v,hasDraft:$e!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Vt()},importProperties:{importDraft:O,onImportDraftChange:e=>{k(e),j(`idle`),T(null)},onReviewSitemap:e=>{wt(e)},reviewState:A,properties:ot,propertiesState:`ready`,propertiesSearch:M,onPropertiesSearchChange:N,maxVisibleProperties:P,onShowAllProperties:()=>F(ot.length),selectedPropertyIds:I,onSelectedPropertyIdsChange:e=>L([...e]),onContinue:e=>{Et(e)},isContinuing:Ue===`properties`,onRetryProperties:()=>{rt()},onReturnToImport:()=>y(`import`)}}):v===`queries`?(0,$.jsx)(Zv,{currentStep:`queries`,hasDraft:$e!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Vt()},onManageProjectQueries:d,queries:{onCreateQueries:u?e=>Tt(e):void 0,isCreatingQueries:Ue===`create-queries`||Ue===`create-and-pair-questions`,isBusy:Ue!==null,createQueriesError:Ke,availability:Ct,properties:ct,queries:dt,selectedQueryIds:R,isApplying:Ue===`assignments`||Ue===`paired-assignments`,onSelectedQueryIdsChange:e=>z([...e]),onApplySelectedQueries:e=>Dt(e),groups:ft,audience:ee,onAudienceChange:e=>{te(e),De(null)},executionOptions:mt,executionOptionId:ne,onExecutionOptionChange:e=>{re(e),De(null)},markets:pt,marketId:B,onMarketChange:e=>{ie(e),ge(null)},marketExecutionOptionId:ae,onMarketExecutionOptionChange:e=>{oe(e),ge(null)},onRouteMarket:kt,isRoutingMarket:Ue===`route-markets`,isPreviewingMarketRouting:le,marketRoutingImpact:yt,marketRoutingError:de,onRetryMarketRouting:()=>me(e=>e+1),marketRoutingNotice:he,assignmentImpact:_e&&ve===xt&&_e.draftEtag===et?Iy(_e):null,isPreviewingAssignmentImpact:be,assignmentImpactError:Se,onRetryAssignmentImpact:()=>Te(e=>e+1),assignmentNotice:Ee,onReplaceAssignments:Ot,isReplacingAssignments:Ue===`replace-assignments`,onCreateAndPairQuestions:o&&u?jt:void 0,onClearQueryAssignments:Mt,onRemoveQuery:Mt,canContinue:lt>0,onBack:()=>y(`groups`),onContinue:()=>y(`review`)}}):v===`groups`?(0,$.jsx)(Zv,{currentStep:`groups`,hasDraft:$e!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Vt()},groups:{properties:ct,groups:ft,groupDraft:Oe,isSaving:Ue===`group`,onGroupDraftChange:ke,onSaveGroup:Nt,onEditGroup:e=>Pt(e.id),onRemoveGroup:Ft,onClearGroupDraft:()=>{je(null),ke({...$v})},membershipImport:{csv:W,preview:Ne,isReviewing:Fe,isApplying:Le,error:ze,notice:Ve,onCsvChange:It,onReview:Lt,onApply:Rt},onBack:()=>{y(`properties`)},onContinue:()=>y(`queries`)}}):(0,$.jsx)(Zv,{currentStep:`review`,hasDraft:$e!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Vt()},review:{counts:{properties:st.length,queries:new Set(G.authoring.assignments.map(e=>e.queryId)).size,groups:G.authoring.groups.length,assignments:G.authoring.assignments.length,providerCalls:Je?.providerCalls},flaggedExceptions:St,reviewedChanges:Je?.changes,isReviewing:Ue===`review`,canReviewChanges:lt>0&&!Ue,onReviewChanges:zt,onBack:()=>y(`queries`),canPublish:Je!==null&&!Ue&&!s,sweepActive:s,isPublishing:Ue===`publish`,onPublish:Bt}})]})}var By=`Mentioned = the property’s name in the answer. Cited = one of the property’s own pages in the sources. Neither implies the other.`,Vy=[{key:`label`,label:`Property`,numeric:!1},{key:`mentionCoverage`,label:`Mention`,numeric:!0},{key:`citationCoverage`,label:`Citation`,numeric:!0}];function Hy(e){return e.label!==`Complete`}var Uy=`__all_properties__`,Wy=50,Gy=50,Ky=20,qy=50,Jy=250,Yy=5,Xy=[{value:`all`,label:`All queries`},{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],Zy={"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`},Qy={plan_v1:`Setup update required.`,no_completed_run:`Not measured yet.`,no_population:`No matching queries.`,evidence_incomplete:`Evidence incomplete.`,identity_ambiguous:`${Gn}.`,"identity-ambiguous":`${Gn}.`,not_applicable:`Not applicable.`,incomplete:`The latest measurement is incomplete.`,"evidence-incomplete":`Some source evidence is incomplete.`,"no-population":`No measurements are available for this selection.`,unavailable:`This measurement is unavailable.`},$y={numerator:null,denominator:null,reason:`plan_v1`};function eb(e){return e.numerator!==null&&Number.isFinite(e.numerator)&&Number.isFinite(e.denominator)&&e.numerator>=0&&e.denominator>0&&e.numerator<=e.denominator}function tb(e){return eb(e)?`${e.numerator} of ${e.denominator} (${St(e.numerator/e.denominator)})`:`N/A`}function nb(e){if(eb(e))return``;let t=e.reason??`unavailable`;return Qy[t]??t}function rb(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 ib(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||e<0||t<=0||e>t?null:`${e} of ${t}`}function ab(e){let t=e.trim();return t&&!t.toLocaleLowerCase().includes(`unavailable`)?t:null}function ob(e){return e?.closest?.(`button, a, input, select, textarea, [role="button"]`)!=null}function sb({metric:e,signal:t,compact:n=!1}){let r=n?eb(e)?`text-label-14-strong text-primary`:`text-label-14-strong text-secondary`:eb(e)?`text-label-18-strong text-heading`:`text-label-18-strong text-secondary`,i=eb(e)?Fn(e,t):null;return(0,$.jsxs)(`span`,{className:`inline-flex flex-wrap items-baseline gap-x-1.5 gap-y-1 tabular-nums`,...eb(e)?{}:{title:nb(e)},children:[(0,$.jsx)(`span`,{className:r,children:tb(e)}),i?(0,$.jsx)(X,{tone:`caution`,placement:`bottom`,label:i.label,text:i.text}):null]})}function cb({shown:e,total:t,onShowAll:n,itemLabel:r}){return e>=t?null:(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,e,` of `,t]}),(0,$.jsxs)(q,{size:`sm`,variant:`outline`,onClick:n,children:[`Show all `,t,` `,r]})]})}function lb({title:e,values:t,emptyLabel:n,valueClassName:r=`text-secondary`}){let[i,a]=(0,Q.useState)(Gy),o=t.slice(0,i);return(0,$.jsxs)(`section`,{"aria-label":e,children:[(0,$.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:e}),t.length===0?(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:n}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`ul`,{className:`mt-2 space-y-1.5 text-label-14`,children:o.map((e,t)=>(0,$.jsx)(`li`,{className:r,children:e},`${e}:${t}`))}),(0,$.jsx)(cb,{shown:o.length,total:t.length,itemLabel:e.toLocaleLowerCase(),onShowAll:()=>a(2**53-1)})]})]})}function ub({evidence:e,state:t=`ready`,onRetry:n}){let[r,i]=(0,Q.useState)(Gy),a=e.slice(0,r);return(0,$.jsxs)(`section`,{"aria-label":`Evidence`,children:[(0,$.jsx)(`h4`,{className:`text-heading-14 text-heading`,children:`Evidence`}),t===`loading`?(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`Loading evidence…`}):t===`error`?(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsx)(`span`,{children:`Evidence could not be loaded.`}),n?(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:n,children:`Retry evidence`}):null]}):e.length===0?(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:`No source evidence is available.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`mt-2 overflow-x-auto rounded-md border border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[640px]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Status`}),(0,$.jsx)(`th`,{children:`Query`}),(0,$.jsx)(`th`,{children:`URL`})]})}),(0,$.jsx)(`tbody`,{children:a.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{children:(0,$.jsxs)(`span`,{className:`flex flex-wrap items-center gap-1`,children:[(0,$.jsx)(J,{tone:e.tone,children:Zy[e.kind]}),e.historical?(0,$.jsx)(J,{tone:`caution`,children:`Historical`}):null]})}),(0,$.jsxs)(`td`,{className:`text-secondary`,children:[(0,$.jsx)(`span`,{className:`block`,children:e.query}),e.provider||e.location?(0,$.jsx)(`span`,{className:`mt-1 block text-label-12 text-muted`,children:[e.provider,e.location].filter(Boolean).join(` · `)}):null]}),(0,$.jsx)(`td`,{className:`break-all text-secondary`,children:e.url})]},e.id))})]})}),(0,$.jsx)(cb,{shown:a.length,total:e.length,itemLabel:`evidence items`,onShowAll:()=>i(2**53-1)})]})]})}function db({property:e,onRetryEvidence:t}){return(0,$.jsxs)(`div`,{className:`space-y-5 py-2`,children:[(0,$.jsx)(lb,{title:`Assigned queries`,values:e.assignedQueries,emptyLabel:`No queries are assigned.`}),(0,$.jsx)(lb,{title:`URLs`,values:e.urls,emptyLabel:`No URLs are assigned.`,valueClassName:`break-all text-secondary`}),(0,$.jsx)(ub,{evidence:e.evidence,state:e.evidenceState,onRetry:t})]})}function fb({values:e}){return(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-share-of-voice`,className:`border-y border-default py-4`,children:[(0,$.jsx)(`h2`,{id:`advanced-measurement-share-of-voice`,className:`text-heading-14 text-heading`,children:`Brand share of voice`}),(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[420px]`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Name`}),(0,$.jsx)(`th`,{children:`Share of voice`})]})}),(0,$.jsx)(`tbody`,{children:e.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-label-14-strong text-heading`,children:e.name}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(sb,{metric:e.coverage,signal:`mentioned`,compact:!0})})]},e.name))})]})})]})}function pb({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,$.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,$.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 mb({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,$.jsx)(`div`,{"aria-label":`Property outcomes`,className:`flex flex-wrap gap-x-8 gap-y-3 py-3`,children:t.map(e=>(0,$.jsxs)(`div`,{className:`whitespace-nowrap`,children:[(0,$.jsx)(`p`,{className:`font-mono text-copy-20-strong tabular-nums ${e.tone}`,children:e.count}),(0,$.jsxs)(`p`,{className:`mt-1 text-copy-13 text-secondary`,children:[e.label,e.key===`not-measured`?(0,$.jsx)(X,{text:`One or both signals missing. Not the same as neither.`}):null]})]},e.key))})}function hb({report:e,canEdit:t,onRunMeasurement:n,onRepublishSetup:r,isRunningMeasurement:i=!1,isRepublishingSetup:a=!1,isViewLoading:o=!1,isLoadingMore:s=!1,isLoadMoreError:l=!1,viewSearch:u,onViewChange:d,onLoadMore:f,onPropertyExpand:p,onRetryEvidence:m,renderPropertyLink:h}){let g=e.currentView!=null,_=e.classReporting===`available`&&(g||e.classScopes!=null),[v,y]=(0,Q.useState)(e.currentView?.queryClass??`all`),[b,x]=(0,Q.useState)(e.currentView?.scope.key??Uy),[S,C]=(0,Q.useState)(u??``),[w,T]=(0,Q.useState)(Wy),[E,D]=(0,Q.useState)(Ky),[O,k]=(0,Q.useState)(e.currentView?.sort??`label-asc`),[A,j]=(0,Q.useState)(null),M=(0,Q.useRef)(u??``),N=_&&!g&&v!==`all`?v===`non-brand`?e.classScopes.nonBrand:e.classScopes.branded:e.overall,P=g?{aggregate:e.currentView.aggregate,groups:[]}:N,F=(0,Q.useCallback)(e=>{if(!g||!d)return;let t=e.scope??(b===Uy?`all`:`group`),n=e.search??S;M.current=n,d({scope:t,...t===`group`?{groupKey:e.groupKey??b}:{},queryClass:e.queryClass??v,...n?{search:n}:{},...e.sort?{sort:e.sort}:{}})},[d,S,v,b,g]);(0,Q.useEffect)(()=>{e.currentView&&!o&&(y(e.currentView.queryClass),x(e.currentView.scope.key??Uy),e.currentView.sort&&k(e.currentView.sort))},[o,e.currentView]),(0,Q.useEffect)(()=>{u!==void 0&&(M.current=u,C(e=>e.trim()===u.trim()?e:u))},[u]),(0,Q.useEffect)(()=>{if(!g||!d||S===M.current)return;let e=window.setTimeout(()=>F({search:S}),Jy);return()=>window.clearTimeout(e)},[d,F,S,g]);let I=e.availableGroups??P.groups;(0,Q.useEffect)(()=>{b===Uy||I.some(e=>e.id===b)||x(Uy)},[I,b]);let L=g?void 0:P.groups.find(e=>e.id===b),R=L?.aggregate??P.aggregate,z=e=>_?e:$y,ee=O,te=S.trim().toLocaleLowerCase(),ne=(0,Q.useMemo)(()=>!g&&te?R.properties.filter(e=>e.name.toLocaleLowerCase().includes(te)):R.properties,[R.properties,te,g]),re=g?ne:ne.slice(0,w),B=(g?e.currentView?.scope.kind===`group`:L!=null)&&v===`non-brand`&&_&&(g||L.confirmedCompetitorCount>0)&&(R.shareOfVoice?.length??0)>0,ie=_?R.unavailablePropertyCount??0:0,ae=e.flaggedResults.reduce((e,t)=>e+(t.count??1),0),oe=e.flaggedResultsTotal??ae,V=[z(R.metrics.propertiesMentioned),z(R.metrics.mentionCoverage),z(R.metrics.citationCoverage)].map(nb).find(Boolean),se=_?e.nextActionText??V??(ie>0?`${ie} ${ie===1?`property is`:`properties are`} unavailable.`:oe>0?`${oe} flagged ${oe===1?`result needs`:`results need`} review.`:null):Qy.plan_v1,H=e.latestMeasurement.status.tone!==`negative`&&e.latestMeasurement.completedSlots<e.latestMeasurement.totalSlots?ib(e.latestMeasurement.completedSlots,e.latestMeasurement.totalSlots):null,ce=ab(e.latestMeasurement.date),le=[{value:Uy,label:`All properties`},...I.map(e=>({value:e.id,label:e.label}))],ue=I.length>Yy;function de(e){x(e),F(e===Uy?{scope:`all`}:{scope:`group`,groupKey:e})}function fe(e){y(e),F({queryClass:e})}function pe(e){let t=A!==e;j(t?e:null),t&&p?.(e)}return(0,$.jsxs)(`section`,{"aria-label":`Advanced measurement overview`,"aria-busy":o,className:`space-y-5`,children:[(0,$.jsx)(`header`,{className:`border-b border-default pb-4`,children:(0,$.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,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:`Updating results…`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(J,{tone:e.latestMeasurement.status.tone,children:e.latestMeasurement.status.label}),e.latestMeasurement.includesBridgedHistory?(0,$.jsx)(J,{tone:`caution`,children:`Includes historical data`}):null,H?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary tabular-nums`,children:H}):null,ce?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:ce}):null,se?(0,$.jsx)(`span`,{className:`text-label-14 text-secondary`,children:se}):null,t&&_&&n?(0,$.jsx)(q,{className:`ml-auto`,size:`sm`,onClick:()=>{n()},disabled:i,children:i?`Starting measurement…`:`Run measurement`}):t&&!_?(0,$.jsx)(q,{className:`ml-auto`,size:`sm`,onClick:()=>{r?.()},disabled:!r||a,children:a?`Opening setup…`:`Republish setup`}):null]})})}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-end gap-4 border-b border-default pb-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`label`,{id:`advanced-measurement-group-label`,htmlFor:ue?`advanced-measurement-group`:void 0,className:`block text-label-14-strong text-heading`,children:`Group`}),ue?(0,$.jsx)(`select`,{id:`advanced-measurement-group`,value:b,onChange:e=>de(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:le.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,$.jsx)(pb,{ariaLabelledBy:`advanced-measurement-group-label`,value:b,options:le,onChange:de})]}),(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`label`,{id:`advanced-measurement-class-label`,className:`block text-label-14-strong text-heading`,children:`Query type`}),(0,$.jsx)(pb,{ariaLabelledBy:`advanced-measurement-class-label`,value:v,options:Xy,onChange:fe,disabled:!_})]}),(0,$.jsxs)(`div`,{className:`ml-auto min-w-52 max-w-xs flex-1 space-y-1`,children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-search`,className:`block text-label-14-strong text-heading`,children:`Search properties`}),(0,$.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&&B?(0,$.jsx)(fb,{values:R.shareOfVoice??[]}):null,o?(0,$.jsx)(`div`,{className:`h-44 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Updating Property results`}):(0,$.jsxs)(`section`,{"aria-labelledby":`advanced-measurement-properties-title`,children:[(0,$.jsxs)(`div`,{className:`mb-3 flex flex-wrap items-center justify-between gap-2`,children:[(0,$.jsxs)(`h2`,{id:`advanced-measurement-properties-title`,className:`text-heading-16 text-heading`,children:[`Properties`,(0,$.jsx)(X,{text:By})]}),(0,$.jsxs)(`span`,{className:`text-label-14 text-secondary`,children:[e.currentView?.propertyTotal??ne.length,` `,(e.currentView?.propertyTotal??ne.length)===1?`property`:`properties`]})]}),e.currentView?.outcomes?(0,$.jsx)(mb,{outcomes:e.currentView.outcomes}):null,(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-md border border-default`,children:(0,$.jsxs)(`table`,{className:`evidence-table min-w-[720px]`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Property measurement results`}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[Vy.map(e=>{let t=ee.startsWith(`${e.key}-`),n=t&&ee.endsWith(`-desc`)?`descending`:t?`ascending`:`none`;return(0,$.jsx)(`th`,{"aria-sort":n,className:(e.numeric,void 0),children:d?(0,$.jsxs)(`button`,{type:`button`,className:`inline-flex items-center gap-1 text-inherit hover:text-heading`,onClick:()=>{let n=`${e.key}-${t&&ee.endsWith(`-asc`)?`desc`:`asc`}`;k(n),F({sort:n})},"aria-label":`Sort by ${e.label.toLowerCase()}`,children:[e.label,(0,$.jsx)(c,{className:`h-3 w-3 transition-transform ${t?`opacity-100`:`opacity-0`} ${n===`ascending`?`rotate-180`:``}`,"aria-hidden":`true`})]}):e.label},e.key)}),(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Details`})})]})}),(0,$.jsxs)(`tbody`,{children:[re.map(e=>{let t=A===e.id;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`tr`,{className:`cursor-pointer transition-colors hover:bg-surface-subtle`,onClick:t=>{ob(t.target)||pe(e.id)},children:[(0,$.jsxs)(`td`,{className:`text-label-14-strong text-heading`,children:[h?h({id:e.id,name:e.name}):e.name,Hy(e.status)||e.historical?(0,$.jsxs)(`span`,{className:`ml-2 inline-flex flex-wrap items-center gap-1 align-middle`,children:[Hy(e.status)?(0,$.jsx)(J,{tone:e.status.tone,children:e.status.label}):null,e.historical?(0,$.jsx)(J,{tone:`caution`,children:`Historical`}):null]}):null,rb(e)?(0,$.jsx)(`div`,{className:`mt-0.5 text-label-12 text-faint`,children:rb(e)}):null]}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(sb,{metric:e.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(sb,{metric:e.citationCoverage,signal:`cited`,compact:!0})}),(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(q,{size:`icon`,variant:`ghost`,"aria-expanded":t,"aria-label":t?`Hide details for ${e.name}`:`Show details for ${e.name}`,onClick:()=>pe(e.id),children:(0,$.jsx)(c,{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,$.jsxs)(`tr`,{className:`measurement-subrow`,children:[(0,$.jsx)(`td`,{className:`measurement-subrow-name`,children:oo(t.provider)}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(sb,{metric:t.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(sb,{metric:t.citationCoverage,signal:`cited`,compact:!0})}),(0,$.jsx)(`td`,{})]},`${e.id}:${t.provider}`)):null,t?(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:4,className:`bg-surface-subtle px-4`,children:(0,$.jsx)(db,{property:e,onRetryEvidence:m})})},`${e.id}:details`):null]},e.id)}),re.length===0?(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:4,className:`py-8 text-center text-label-14 text-secondary`,children:`No properties match this search.`})}):null]})]})}),g&&e.currentView.nextCursor&&f?(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,re.length,` of `,e.currentView.propertyTotal]}),l?(0,$.jsx)(`span`,{role:`alert`,children:`Could not load more properties.`}):null,(0,$.jsx)(q,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>f(e.currentView.nextCursor),children:s?`Loading…`:l?`Retry loading more properties`:`Show 50 more`})]}):g?re.length<e.currentView.propertyTotal?(0,$.jsxs)(`p`,{className:`mt-2 text-copy-14 text-secondary`,children:[`Showing `,re.length,` of `,e.currentView.propertyTotal]}):null:(0,$.jsx)(cb,{shown:re.length,total:ne.length,itemLabel:`properties`,onShowAll:()=>T(2**53-1)})]}),!o&&!te&&oe>0?(0,$.jsx)(`section`,{"aria-label":`Flagged results`,className:`border-t border-default pt-4`,children:(0,$.jsxs)(`details`,{children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer text-label-14-strong text-heading`,children:[`Flagged results (`,oe,`)`]}),(0,$.jsx)(`ul`,{className:`mt-3 space-y-3`,children:e.flaggedResults.slice(0,E).map(e=>(0,$.jsxs)(`li`,{className:`flex flex-wrap items-start gap-2 text-label-14`,children:[(0,$.jsx)(J,{tone:e.tone,children:`Flagged`}),(0,$.jsx)(`span`,{className:`text-label-14-strong text-heading`,children:e.property}),(0,$.jsx)(`span`,{className:`text-secondary`,children:e.summary})]},e.id))}),E<e.flaggedResults.length?(0,$.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing details for `,e.flaggedResults.slice(0,E).reduce((e,t)=>e+(t.count??1),0),` of `,oe,` flagged results`]}),(0,$.jsx)(q,{size:`sm`,variant:`outline`,onClick:()=>D(t=>Math.min(e.flaggedResults.length,t+qy)),children:`Show 50 more`})]}):ae<oe?(0,$.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-label-14 text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing details for `,ae,` of `,oe,` flagged results`]}),g&&e.currentView.nextCursor&&f?(0,$.jsx)(q,{size:`sm`,variant:`outline`,disabled:s,onClick:()=>f(e.currentView.nextCursor),children:s?`Loading…`:l?`Retry loading more Properties`:`Load more Properties`}):null]}):null]})}):null]})}function gb(e){return e===`continue`?`Continue setup`:e===`edit`?`Edit setup`:e===`republish`?`Republish setup`:`Set up advanced measurement`}function _b(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 vb(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 yb({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,$.jsxs)(`div`,{className:`space-y-4`,children:[e.setupAction===`republish`&&!r&&t&&a?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:m,onClick:a,children:m?`Opening setup…`:gb(e.setupAction)}),(0,$.jsx)(`p`,{className:`supporting-copy m-0`,children:`Unpublished changes are waiting to go live.`})]}):null,i===`loading`?(0,$.jsx)(`div`,{className:`h-32 animate-pulse rounded-md bg-surface-subtle`,"aria-label":`Loading advanced measurement report`}):i===`error`&&!r?(0,$.jsxs)(`div`,{role:`alert`,className:`border-y border-negative-800/40 bg-negative-950/20 py-4 text-label-14 text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load the advanced measurement report.`}),s?(0,$.jsx)(q,{className:`mt-3`,type:`button`,size:`sm`,variant:`outline`,onClick:s,children:`Retry report`}):null]}):r?(0,$.jsx)(hb,{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,$.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 bb={numerator:null,denominator:null,reason:`plan_v1`};function xb(e){return e.kind===`exact`?e.url:e.kind===`prefix`?`https://${e.host}${e.pathPrefix}`:`https://${e.host}`}function Sb(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}}}function Cb(e){return e===`assigned`?`this-property`:e===`sibling`?`another-property`:e===`ownedUnmapped`?`owned-unassigned`:e===`external`?`external`:e===`ambiguous`?`multiple-properties`:`invalid-url`}function wb(e){return e===`assigned`?`positive`:e===`external`?`neutral`:e===`invalid`?`negative`:`caution`}function Tb(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 Eb(e){return e.usageEdgeType!==`target`||!e.usageEdgeId.startsWith(`target:`)?null:e.usageEdgeId.slice(7).split(`:`,1)[0]??null}function Db(e){let t=new Map;for(let n of e){let e=Eb(n);if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}return t}function Ob(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=Db(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:Cb(e.classification),query:e.queryText,url:e.sourceUrl,tone:wb(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:Sb(e.mentionCoverage),citationCoverage:Sb(e.citationCoverage),status:l,assignedQueries:a.get(e.id)??[],urls:n?.urls.map(xb)??[],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:Tb(t.run?.finishedAt??t.run?.createdAt??null),includesBridgedHistory:t.diagnostics.bridgedObservationIds.length>0||t.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:bb,mentionCoverage:bb,citationCoverage:bb},properties:d},groups:t.groups.map(e=>({id:e.id,label:e.label,confirmedCompetitorCount:p.get(e.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:bb,mentionCoverage:bb,citationCoverage:bb},properties:e.targetIds.map(e=>f.get(e)).filter(e=>!!e)}}))},flaggedResults:[]}}function kb({project:e,onUpdateProject:t}){let[n,r]=(0,Q.useState)(!1),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(e.displayName),[u,d]=(0,Q.useState)(e.canonicalDomain),[f,p]=(0,Q.useState)(e.country),[m,h]=(0,Q.useState)(e.language),[g,_]=(0,Q.useState)(e.ownedDomains??[]),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(e.aliases??[]),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(``),[I,L]=(0,Q.useState)(``),[R,z]=(0,Q.useState)(``),[ee,te]=(0,Q.useState)(null),[ne,re]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{n||(l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]))},[e,n]);function B(){r(!1),s(null),l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]),y(``),C(``)}function ie(){let e=v.trim();e&&(g.includes(e)||_([...g,e]),y(``))}function ae(e){_(g.filter(t=>t!==e))}function oe(){let e=S.trim();if(!e)return;let t=e.toLowerCase();b.some(e=>e.toLowerCase()===t)||x([...b,e]),C(``)}function V(e){x(b.filter(t=>t!==e))}async function se(){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),Xn({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 H(){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 tn(e.name,a),j(``),N(``),F(``),L(``),z(``),k(!1),Xn({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 We(e.name,t),Xn({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 Ae(e.name,t),Xn({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){te(t),re(null);try{await zt(e.name,t),Xn({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){re(e instanceof Error?e.message:`Could not download tracking results.`)}finally{te(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=!Y()&&!Ze(),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,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Configuration`}),(0,$.jsx)(`h2`,{children:`Project settings`})]}),fe&&!n&&(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:`Edit settings`})]}),o&&(0,$.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,$.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>s(null),children:`×`})]}),fe&&n?(0,$.jsxs)(`div`,{className:`material-base p-4 space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-4`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:me,children:`Display name`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`My Project`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:me,children:`Canonical domain`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:u,onChange:e=>d(e.target.value),placeholder:`example.com`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:me,children:`Country`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`US`,maxLength:2})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:me,children:`Language`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:m,onChange:e=>h(e.target.value),placeholder:`en`})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:me,children:`Owned domains`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:g.map(e=>(0,$.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,$.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,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`input`,{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(),ie())}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:!v.trim(),onClick:ie,children:`Add`})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:me,children:`Aliases`}),(0,$.jsx)(`p`,{className:`mb-1.5 text-copy-14 text-secondary`,children:`Other brand names that may appear in answers.`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5 mb-2`,children:b.map(e=>(0,$.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,$.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>V(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`input`,{className:`${pe} flex-1`,type:`text`,placeholder:`Facebook`,value:S,onChange:e=>C(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),oe())}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:!S.trim(),onClick:oe,children:`Add`})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 pt-2 border-t border-default`,children:[(0,$.jsx)(q,{type:`button`,disabled:i||!de||!c.trim()||!u.trim(),onClick:Jn(se),children:i?`Saving...`:`Save changes`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,disabled:i,onClick:B,children:`Cancel`})]})]}):(0,$.jsx)(`div`,{className:`material-base overflow-hidden`,children:(0,$.jsx)(`table`,{className:`w-full text-label-14`,children:(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong w-40`,children:`Display name`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.displayName||`—`})]}),(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Canonical domain`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.canonicalDomain})]}),(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Owned domains`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5`,children:(e.ownedDomains??[]).length>0?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.ownedDomains.map(e=>(0,$.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,$.jsx)(`span`,{className:`text-muted`,children:`—`})})]}),(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Aliases`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5`,children:(e.aliases??[]).length>0?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.aliases.map(e=>(0,$.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,$.jsx)(`span`,{className:`text-muted`,children:`—`})})]}),(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Country`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.country})]}),(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Language`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-strong`,children:e.language})]}),e.tags?.length?(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong`,children:`Tags`}),(0,$.jsx)(`td`,{className:`px-4 py-2.5`,children:(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:e.tags.map(e=>(0,$.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,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted text-label-14-strong align-top pt-3`,children:`Search Locations`}),(0,$.jsxs)(`td`,{className:`px-4 py-2.5`,children:[w&&(0,$.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,$.jsx)(`button`,{type:`button`,className:`ml-1 text-negative-400 hover:text-negative-200`,onClick:()=>T(null),children:`×`})]}),(e.locations??[]).length>0?(0,$.jsxs)(`table`,{className:`w-full text-label-12 mb-2`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`text-faint`,children:[(0,$.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Label`}),(0,$.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`City`}),(0,$.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Region`}),(0,$.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Country`}),(0,$.jsx)(`th`,{className:`text-left pb-1 text-label-12-strong pr-3`,children:`Timezone`}),(0,$.jsx)(`th`,{className:`pb-1`})]})}),(0,$.jsx)(`tbody`,{children:e.locations.map(t=>(0,$.jsxs)(`tr`,{className:`border-t border-mono-800/30`,children:[(0,$.jsx)(`td`,{className:`py-1.5 pr-3`,children:(0,$.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,$.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.city}),(0,$.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.region}),(0,$.jsx)(`td`,{className:`py-1.5 pr-3 text-neutral`,children:t.country}),(0,$.jsx)(`td`,{className:`py-1.5 pr-3 text-muted`,children:t.timezone??`—`}),(0,$.jsx)(`td`,{className:`py-1.5`,children:(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[fe&&t.label!==e.defaultLocation&&(0,$.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,$.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,$.jsx)(`p`,{className:`text-muted text-copy-13 mb-2`,children:`No search locations configured`}),fe?O?(0,$.jsxs)(`div`,{className:`mt-2 material-base p-3 space-y-2`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-secondary`,children:`Add search location`}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Label *`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:A,onChange:e=>j(e.target.value),placeholder:`nyc`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`City *`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:M,onChange:e=>N(e.target.value),placeholder:`New York`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Region *`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:P,onChange:e=>F(e.target.value),placeholder:`NY`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Country *`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:I,onChange:e=>L(e.target.value),placeholder:`US`,maxLength:2})]}),(0,$.jsxs)(`div`,{className:`col-span-2`,children:[(0,$.jsx)(`label`,{className:`mb-1 block text-label-14 text-secondary`,children:`Timezone (optional)`}),(0,$.jsx)(`input`,{className:pe,type:`text`,value:R,onChange:e=>z(e.target.value),placeholder:`America/New_York`})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 pt-1`,children:[(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:E||!he,onClick:Jn(H),children:E?`Adding...`:`Add search location`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,disabled:E,onClick:()=>{k(!1),T(null)},children:`Cancel`})]})]}):(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>k(!0),children:`+ Add search location`}):null]})]})]})})})]}),(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsxs)(`div`,{className:`section-head`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Data export`}),(0,$.jsx)(`h2`,{children:`Tracking results`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-copy-14 text-muted`,children:`Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs.`})]}),(0,$.jsxs)(`div`,{className:`material-base px-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between`,children:[(0,$.jsx)(`p`,{className:`max-w-xl text-copy-13 text-muted`,children:`Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included.`}),(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:ee!==null,onClick:Jn(()=>ue(`csv`)),children:ee===`csv`?`Preparing CSV...`:`Download CSV`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:ee!==null,onClick:Jn(()=>ue(`json`)),children:ee===`json`?`Preparing JSON...`:`Download JSON`})]})]}),ne&&(0,$.jsx)(`p`,{className:`mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-copy-14 text-negative`,children:ne})]})]})]})}function Ab(e,t,n){return w({..._r({client:K,path:{name:e},query:{selection:n}}),enabled:t&&!!e,staleTime:Yn,refetchOnWindowFocus:`always`,refetchInterval:e=>{let t=Object.values(e.state.data?.providers??{}).map(e=>Date.parse(e.retryAfter)).filter(Number.isFinite);if(t.length===0)return!1;let n=Math.min(...t)-Date.now();return n>0?n:Yn},retry:!1})}function jb(e){switch(e){case Bt.PROVIDER_BILLING:return{sentence:e=>`${e.name} ran out of credit`,label:`out of credit`};case Bt.PROVIDER_AUTH:return{sentence:e=>`${e.possessive} key was rejected or access was denied`,label:`key rejected or access denied`};case Bt.RATE_LIMITED:case Bt.PROVIDER_UNAVAILABLE:case Bt.NETWORK:case Bt.TIMEOUT:case Bt.PARSE_ERROR:case Bt.UNKNOWN:return{sentence:t=>`${t.name} failed with ${e}`,label:e}}}function Mb({iso:e}){return(0,$.jsx)(`time`,{dateTime:e,children:Un(e)})}function Nb({admission:e,canFix:t,selection:n}){let r=(0,Q.useId)(),i=Object.entries(e.providers),a=w({...ci({client:K}),enabled:t&&i.length>0,retry:!1}).data?.providerCatalog??[],o=Oo(a),s=e=>oo(e,a);if(i.length===0)return null;let[c,l]=i[0],u=s(c),d=i.length===1,f=l.consecutiveRuns,p=i.find(([,e])=>e.code===Bt.PROVIDER_AUTH),m=n?`${n} checks`:`checks`,h=e.refused?`${n?n===`manual`?`Manual checks`:`Scheduled checks`:`Checks`} are on hold`:d?`${u} is left out of ${m}`:`${i.length} providers are left out of ${m}`,g;if(d){let t=jb(l.code).sentence(e.refused?{name:u,possessive:`${u}'s`}:{name:`It`,possessive:`Its`}),n=e.refused?e.retryAfter??l.retryAfter:l.retryAfter,r=l.code===Bt.PROVIDER_BILLING?(0,$.jsxs)($.Fragment,{children:[`; add credit in `,u,`'s console before then.`]}):(0,$.jsx)($.Fragment,{children:`, or as soon as its key, model or endpoint is saved.`});g=e.refused?(0,$.jsxs)($.Fragment,{children:[t,` in each of its last `,f,` runs, so a check would fail the same way. The hold lifts `,(0,$.jsx)(Mb,{iso:n}),r]}):(0,$.jsxs)($.Fragment,{children:[t,` in each of its last `,f,` runs. Checks run without it until `,(0,$.jsx)(Mb,{iso:n}),r]})}else g=e.refused?(0,$.jsxs)($.Fragment,{children:[`Every provider failed on its account in each of its last `,f,` runs, so a check would fail the same way. The hold lifts`,` `,e.retryAfter?(0,$.jsx)(Mb,{iso:e.retryAfter}):`at the first time below`,`, or as soon as a provider's key, model or endpoint is saved.`]}):(0,$.jsxs)($.Fragment,{children:[`Each failed on its account in each of its last `,f,` runs. Checks run without them until the times below, or until a key, model or endpoint is saved.`]});return(0,$.jsxs)(`section`,{"aria-labelledby":r,className:`mb-5 flex flex-wrap items-start justify-between gap-3 rounded-md border px-4 py-3 text-label-14 ${e.refused?`border-negative bg-negative-soft`:`border-caution bg-caution-soft`}`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 max-w-[29rem] space-y-1`,children:[(0,$.jsx)(`h2`,{id:r,className:`text-heading-14 ${e.refused?`text-negative`:`text-caution`}`,children:h}),(0,$.jsx)(`p`,{className:`text-secondary`,children:g}),d?null:(0,$.jsx)(`ul`,{className:`text-secondary`,children:i.map(([e,t])=>(0,$.jsxs)(`li`,{children:[s(e),`: `,jb(t.code).label,`, until `,(0,$.jsx)(Mb,{iso:t.retryAfter})]},e))}),t?null:(0,$.jsxs)(`p`,{className:`text-secondary`,children:[`Ask an administrator to fix `,d?u:`these providers`,`.`]})]}),t&&p?(0,$.jsx)(q,{asChild:!0,variant:`outline`,size:`sm`,className:`h-11 md:h-8`,children:(0,$.jsx)(A,{to:`/settings`,hash:`provider-${vn(p[0],o)}`,children:d?`Update ${s(vn(c,o))} key`:`Open provider settings`})}):null]})}var Pb={edit:`Edit schedule`,pause:`Pause`,resume:`Resume`,save:`Save schedule`},Fb=[{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`}],Ib=[`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 Lb(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 Rb({projectName:e}){let t=H(),n=!Y()&&!Ze()&&!t,r=S(),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(`daily`),[c,l]=(0,Q.useState)(6),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(14),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(`00:00`),[v,y]=(0,Q.useState)(`UTC`),[b,x]=(0,Q.useState)(!1),[C,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(null),[M,N]=(0,Q.useState)(void 0),P=or({client:K,path:{name:e}}),F=w({...ji({client:K,path:{name:e}}),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`,retry:!1}),I=F.isPending||F.isFetching,L=F.isError,R=F.data?.find(e=>e.kind===`answer-visibility`)??null,z=i&&M!==void 0&&(R?.updatedAt??null)!==M,ee=e=>{r.setQueryData(P,t=>{let n=(t??[]).filter(e=>e.kind!==`answer-visibility`);return e?[...n,e]:n})},te=e=>{if(e){if(e.recurrence)s(`calendar`),p(e.recurrence.everyDays),h(e.recurrence.startDate),_(e.recurrence.time);else{let t=zn(e.preset??null,e.cronExpr);s(t.freq),l(t.hour),d(t.customCron)}let t=Ib.includes(e.timezone);y(t?e.timezone:`Other`),x(!t),T(t?``:e.timezone)}else s(`daily`),l(6),d(``),p(14),h(``),_(`00:00`),y(`UTC`),x(!1),T(``);N(e?.updatedAt??null)},ne=()=>{n&&(te(R),j(null),a(!0))},re=()=>{te(R),j(null)},B=async()=>{(await F.refetch()).isError?j(`The schedule changed, but Canonry could not load the latest version. Retry the schedule check.`):j(i?null:`This schedule changed elsewhere. The latest version is now shown; review it and try again.`)},ie=async(e,t)=>{e instanceof ht&&e.code===`SCHEDULE_VERSION_CONFLICT`?await B():j(e instanceof Error?e.message:t)};return(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Automation`}),(0,$.jsx)(`h2`,{children:`Scheduled runs`})]}),n&&!I&&!L&&!i&&(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:ne,children:R?Pb.edit:`+ Set schedule`})]}),I&&(0,$.jsx)(`p`,{className:`supporting-copy`,children:`Loading...`}),A&&!i&&(0,$.jsx)(`p`,{className:`mt-2 text-copy-14 text-negative`,role:`alert`,children:A}),!I&&L&&(0,$.jsxs)(Z,{className:`surface-card compact-card`,children:[(0,$.jsx)(`p`,{className:`supporting-copy`,children:`Canonry could not verify this schedule.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>{F.refetch()},children:`Retry`})]}),!I&&!L&&!i&&R===null&&(0,$.jsx)(Z,{className:`surface-card compact-card`,children:(0,$.jsx)(`p`,{className:`supporting-copy`,children:t?`AI Visibility checks are run by your Canonry team`:`No schedule configured. Set one to automatically trigger AI Visibility checks.`})}),!I&&!L&&!i&&R!==null&&(0,$.jsx)(Z,{className:`surface-card compact-card`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`space-y-1`,children:[t&&(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`AI Visibility checks are run by your Canonry team`}),(0,$.jsx)(`p`,{className:`text-copy-14-strong text-strong`,children:R.recurrence?Lb(R.recurrence,R.timezone):Ln(R.preset??null,R.cronExpr,R.timezone)}),!R.recurrence&&(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Cron: `,(0,$.jsx)(`span`,{className:`font-mono`,children:R.cronExpr})]}),R.enabled&&R.nextRunAt&&(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Next run: `,Tt(R.nextRunAt,R.timezone)]}),R.lastRunAt&&(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[`Last run: `,new Date(R.lastRunAt).toLocaleString()]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,$.jsx)(J,{tone:R.enabled?`positive`:`neutral`,children:R.enabled?`Active`:`Paused`}),n&&(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,disabled:E,onClick:Jn(async()=>{if(!n||!R)return;let t=R.updatedAt;D(!0),j(null);try{let n=await F.refetch();if(n.isError||n.data===void 0){j(`Canonry could not verify the latest schedule. Try again before updating it.`);return}let r=n.data.find(e=>e.kind===`answer-visibility`)??null;if(!r||r.updatedAt!==t){j(`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 be(e,i);ee(a),Xn({title:a.enabled?`Schedule resumed`:`Schedule paused`,detail:a.recurrence?Lb(a.recurrence,a.timezone):Ln(a.preset??null,a.cronExpr,a.timezone),tone:`positive`,dedupeKey:`schedule:toggle:${e}`,dedupeMode:`replace`})}catch(e){await ie(e,`Failed to update schedule`)}finally{D(!1)}}),children:R.enabled?Pb.pause:Pb.resume}),n&&(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,disabled:O,onClick:Jn(async()=>{if(!n||!R)return;let t=R.updatedAt;k(!0),j(null);try{await Me(e,t),ee(null),a(!1),N(void 0),Xn({title:`Schedule removed`,detail:`${e} will no longer run automatically.`,tone:`positive`,dedupeKey:`schedule:remove:${e}`,dedupeMode:`drop`})}catch(e){await ie(e,`Failed to remove schedule`)}finally{k(!1)}}),children:O?`Removing...`:`Remove`})]})]})}),n&&i&&(0,$.jsxs)(`div`,{className:`material-base p-4 space-y-3`,children:[z&&!E&&(0,$.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,$.jsx)(`p`,{children:`This schedule changed elsewhere. Load the latest version before saving.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:re,children:`Load latest schedule`})]}),(0,$.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Frequency`}),(0,$.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:o,onChange:e=>s(e.target.value),children:Fb.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]}),o!==`calendar`&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Time`}),(0,$.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 disabled:opacity-40`,value:c,disabled:o===`twice-daily`||o===`custom`,onChange:e=>l(parseInt(e.target.value)),children:Array.from({length:24},(e,t)=>(0,$.jsx)(`option`,{value:t,children:Vn(t)},t))})]})]}),o===`custom`&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Cron expression`}),(0,$.jsx)(`input`,{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:u,onChange:e=>d(e.target.value)})]}),o===`calendar`&&(0,$.jsxs)(`div`,{className:`grid grid-cols-3 gap-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Repeat every`}),(0,$.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:f,onChange:e=>p(Number(e.target.value))}),(0,$.jsx)(`p`,{className:`text-copy-13 text-muted`,children:`days`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Start date`}),(0,$.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:m,onChange:e=>h(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Time`}),(0,$.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:g,onChange:e=>_(e.target.value)})]})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Timezone`}),(0,$.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:b?`Other`:v,onChange:e=>{e.target.value===`Other`?(x(!0),y(`Other`)):(x(!1),y(e.target.value))},children:[Ib.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),(0,$.jsxs)(`option`,{value:`Other`,children:[`Other (enter manually)`,`…`]})]}),b&&(0,$.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:`e.g. America/New_York`,value:C,onChange:e=>T(e.target.value)})]}),A&&(0,$.jsx)(`p`,{className:`text-negative-400 text-copy-14`,role:`alert`,children:A}),(0,$.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{a(!1),N(void 0),j(null)},children:`Cancel`}),(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:E||F.isFetching||L||z||o===`custom`&&!u.trim()||o===`calendar`&&(!Number.isInteger(f)||f<1||f>3650||!m||!g),onClick:Jn(async()=>{if(n&&!(z||M===void 0)){D(!0),j(null);try{let t=await F.refetch();if(t.isError||t.data===void 0){j(`Canonry could not verify the latest schedule. Try again before saving.`);return}let n=t.data.find(e=>e.kind===`answer-visibility`)??null;if((n?.updatedAt??null)!==M)return;let r={timezone:b?C.trim()||`UTC`:v,enabled:n?.enabled??!0,providers:n?.providers??[],expectedUpdatedAt:M};o===`calendar`?r.recurrence={everyDays:f,startDate:m,time:g}:o===`custom`?r.cron=u.trim():r.preset=Bn(o,c);let i=await be(e,r);a(!1),N(void 0),ee(i),Xn({title:`Schedule saved`,detail:i.recurrence?Lb(i.recurrence,i.timezone):Ln(i.preset??null,i.cronExpr,i.timezone),tone:`positive`,dedupeKey:`schedule:${e}`,dedupeMode:`replace`})}catch(e){await ie(e,`Failed to save schedule`)}finally{D(!1)}}}),children:E?`Saving...`:Pb.save})]})]})]})}var zb=[{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 Bb({projectName:e}){let[t,n]=(0,Q.useState)(`loading`),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)([`citation.lost`,`citation.gained`]),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)({}),[h,g]=(0,Q.useState)(new Set),_=!Y()&&!Ze();(0,Q.useEffect)(()=>{ue(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 mn(e,{channel:`webhook`,url:a.trim(),events:s});n(e=>e===`loading`?[t]:[...e,t]),o(``),c([`citation.lost`,`citation.gained`]),i(!1),Xn({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 he(e,t),n(e=>e===`loading`?e:e.filter(e=>e.id!==t)),Xn({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 it(e,t);m(e=>({...e,[t]:{state:n.ok?`ok`:`fail`,status:n.status}})),n.ok&&Xn({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,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsxs)(`div`,{className:`section-head section-head-inline`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Automation`}),(0,$.jsx)(`h2`,{children:`Notifications`})]}),_&&t!==`loading`&&(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!r),f(null)},children:r?`Cancel`:`+ Add webhook`})]}),_&&r&&(0,$.jsxs)(`div`,{className:`mb-3 material-base p-4 space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Webhook URL`}),(0,$.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,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-label-12-strong text-secondary`,children:`Trigger on`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-3`,children:zb.map(e=>(0,$.jsxs)(`label`,{className:`flex items-center gap-1.5 cursor-pointer select-none`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`rounded border-mono-600 bg-mono-800`,checked:s.includes(e.value),onChange:()=>v(e.value)}),(0,$.jsx)(`span`,{className:`text-label-14 text-neutral`,children:e.label})]},e.value))})]}),d&&(0,$.jsx)(`p`,{className:`text-negative-400 text-copy-14`,children:d}),(0,$.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!1),f(null)},children:`Cancel`}),(0,$.jsx)(q,{type:`button`,size:`sm`,disabled:l||!a.trim()||s.length===0,onClick:Jn(y),children:l?`Adding...`:`Add webhook`})]})]}),t===`loading`&&(0,$.jsx)(`p`,{className:`supporting-copy`,children:`Loading...`}),t!==`loading`&&t.length===0&&!r&&(0,$.jsx)(Z,{className:`surface-card compact-card`,children:(0,$.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,$.jsxs)(`div`,{className:`evidence-table-wrap`,children:[(0,$.jsxs)(`table`,{className:`evidence-table`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{children:`Endpoint`}),(0,$.jsx)(`th`,{children:`Events`}),(0,$.jsx)(`th`,{children:`Status`}),(0,$.jsx)(`th`,{})]})}),(0,$.jsx)(`tbody`,{children:t.map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`evidence-query-cell`,children:(0,$.jsx)(`span`,{className:`text-label-12-mono text-neutral break-all`,title:e.urlHost,children:e.urlDisplay??e.url})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1`,children:e.events.map(e=>(0,$.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,$.jsx)(`td`,{children:(0,$.jsx)(J,{tone:e.enabled?`positive`:`neutral`,children:e.enabled?`Active`:`Paused`})}),(0,$.jsx)(`td`,{children:(0,$.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,$.jsx)(J,{tone:t.state===`ok`?`positive`:t.state===`fail`?`negative`:`neutral`,children:n})})(),_&&(0,$.jsx)(q,{variant:`ghost`,size:`sm`,type:`button`,disabled:p[e.id]?.state===`testing`,onClick:()=>{x(e.id)},children:`Test`}),_&&(0,$.jsx)(q,{variant:`ghost`,size:`sm`,type:`button`,disabled:h.has(e.id),onClick:()=>{b(e.id)},children:h.has(e.id)?`Removing…`:`Remove`})]})})]},e.id))})]}),d&&(0,$.jsx)(`p`,{className:`text-negative-400 text-copy-14 mt-2`,children:d})]})]})}function Vb({open:e,projectLabel:t,onOpenChange:n,onConfirm:r,onClosed:i,disabled:a,leftOut:o=[]}){return Y()||H()?null:(0,$.jsx)(Wo,{open:e,onOpenChange:n,children:(0,$.jsxs)(cs,{onCloseAutoFocus:e=>{i&&(e.preventDefault(),i())},children:[(0,$.jsxs)(Po,{children:[(0,$.jsx)(Yo,{children:`Run AI Visibility check for the whole project?`}),(0,$.jsxs)(Ao,{children:[`Runs all tracked queries for `,t,`. View filters do not limit the check. Provider charges apply.`,o.length>0?` ${o.map(e=>oo(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,$.jsxs)(`div`,{className:`mt-6 flex flex-wrap gap-3`,children:[(0,$.jsx)(q,{variant:`outline`,onClick:()=>n(!1),children:`Cancel`}),(0,$.jsx)(hs,{disabled:a,onClick:r,children:`Run project-wide check`})]})]})})}var Hb=2e3,Ub=3e5;function Wb(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function Gb(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 Kb({projectName:e}){let t=S(),[n,r]=(0,Q.useState)(`google`),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(`idle`),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(0);async function v(n=!1){n||a(!0),l(null);try{let[n,r]=await Promise.all([t.fetchQuery({...Sr({client:K,path:{name:e}}),staleTime:Qn}).catch(()=>[]),t.fetchQuery({...Zi({client:K,path:{name:e}}),staleTime:Qn}).catch(()=>null)]),i=n.find(e=>e.connectionType===`gsc`)??null;p(i),h(r)}catch(e){l(e instanceof Error?e.message:`Failed to load search engine connections`)}finally{a(!1)}}async function y(){if(o!==`idle`)return;u.current?.abort();let n=new AbortController;u.current=n;let r=n.signal;s(`syncing`),l(null),Xn({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 n(){if(!f)return;let t=await qt(e);if(!t?.id)return;let n=Date.now()+Ub;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,Hb)),r.aborted))return;let e=await we(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 Ft(e).catch(()=>null);if(!t?.id){i.push(`Bing check could not be started`);return}let n=Date.now()+Ub;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,Hb)),r.aborted))return;let e=await we(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 c(){if(!m?.connected||!m.siteUrl)return;let t=await rn(e).catch(()=>null);if(!t?.id){i.push(`Bing data sync could not be started`);return}let n=Date.now()+Ub;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,Hb)),r.aborted))return;let e=await we(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 u=await Promise.allSettled([n(),o(),c()]);for(let e of u)e.status===`rejected`&&i.push(e.reason instanceof Error?e.reason.message:`Sync failed`);if(await Promise.all([Zn(t,`gsc`),Zn(t,`bing`)]),r.aborted)return;if(s(`reloading`),await v(!0),_(e=>e+1),i.length>0){let t=`Partial refresh: ${[...i,...a].join(`; `)}`;l(t),Xn({title:`Search coverage partially refreshed`,detail:t,tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}else a.length>0?Xn({title:`Search coverage refresh incomplete`,detail:a.join(`; `),tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`}):Xn({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`;l(n),Xn({title:`Search coverage refresh failed`,detail:n,tone:`negative`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}}finally{r.aborted||s(`idle`)}}return(0,Q.useEffect)(()=>(v(),()=>{u.current?.abort()}),[e]),(0,$.jsxs)(`div`,{className:`space-y-6`,children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,role:`tablist`,"aria-label":`Search engine workspaces`,children:[[`google`,`Google`],[`bing`,`Bing`]].map(([e,t])=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":n===e,className:`project-subnav-link ${n===e?`project-subnav-link-active`:``}`,onClick:()=>r(e),children:t},e))}),!Y()&&(0,$.jsxs)(hs,{type:`button`,variant:`outline`,size:`sm`,"aria-label":`Refresh search data`,disabled:i||o!==`idle`,onClick:()=>void y(),children:[(0,$.jsx)(d,{className:`h-3.5 w-3.5 ${o===`idle`?``:`animate-spin`}`,"aria-hidden":`true`}),i?`Loading…`:o===`syncing`?`Refreshing search data…`:o===`reloading`?`Reloading workspaces…`:`Refresh search data`]})]}),c&&(0,$.jsx)(`div`,{className:`rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-label-14 text-negative`,children:c}),n===`google`&&(0,$.jsx)(Gl,{projectName:e,refreshNonce:g}),n===`bing`&&(0,$.jsx)(uu,{projectName:e,refreshNonce:g})]})}function qb({label:e,summary:t,displayValue:n,tooltip:r}){let{figure:i,sign:a}=Nn(t.value),o=t.progress===void 0?0:Math.min(Math.max(t.progress,0),100);return(0,$.jsxs)(`div`,{className:`aeo-hero-row`,children:[(0,$.jsxs)(`p`,{className:`aeo-hero-row-label`,children:[e,(r||t.tooltip)&&(0,$.jsx)(X,{text:r||t.tooltip||``})]}),(0,$.jsx)(`p`,{className:`aeo-hero-row-value ${wo[t.tone]}`,children:n??(0,$.jsxs)($.Fragment,{children:[i,a?(0,$.jsx)(`span`,{className:`text-faint`,children:a}):null]})}),(0,$.jsx)(`div`,{className:`aeo-hero-row-bar`,"aria-hidden":`true`,children:(0,$.jsx)(`div`,{className:`metric-card-bar-fill progress-fill-${t.tone}`,style:{width:`${o}%`}})})]})}function Jb({id:e,title:t,meta:n,defaultOpen:r=!1,children:i}){return(0,$.jsxs)(`details`,{id:e,className:`overview-disclosure page-section-divider scroll-mt-24`,open:r||void 0,children:[(0,$.jsxs)(`summary`,{className:`overview-disclosure-summary`,children:[(0,$.jsx)(`h2`,{className:`overview-disclosure-title`,children:t}),(0,$.jsxs)(`span`,{className:`overview-disclosure-meta`,children:[n&&(0,$.jsx)(`span`,{children:n}),(0,$.jsx)(c,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,$.jsx)(`div`,{className:`overview-disclosure-body`,children:i})]})}function Yb({insights:e,suggestedQueries:t,onManageQueries:n,siteDomain:r}){let{openEvidence:i}=io(),a=n?t.rows:[];if(e.length===0&&a.length===0)return null;let o=e=>(0,$.jsxs)(`div`,{className:`py-3`,children:[(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`text-copy-14-strong text-heading`,children:e.title}),e.detail?(0,$.jsx)(`p`,{className:`mt-1 max-w-3xl text-copy-14 text-secondary`,children:e.detail}):null]}),(0,$.jsx)(J,{tone:e.tone,children:e.actionLabel})]}),e.affectedPhrases.length>0?(0,$.jsxs)(`details`,{className:`mt-2`,children:[(0,$.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,$.jsx)(`ul`,{className:`mt-2 divide-y divide-subtle border-y border-subtle`,children:e.affectedPhrases.map((t,n)=>(0,$.jsxs)(`li`,{className:`flex flex-wrap items-center gap-2 py-2`,children:[(0,$.jsx)(rc,{state:t.citationState,...r&&t.siteCitation!==!1?{label:Pn(r,t.citationState)}:{}}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 text-label-14 text-strong`,children:t.query}),t.provider?(0,$.jsx)(Fo,{provider:t.provider}):null,!Y()&&t.evidenceId?(0,$.jsx)(q,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>{i(t.evidenceId)},children:`View evidence`}):null]},t.evidenceId||`${e.id}-${n}`))})]}):null]},e.id),s=e=>(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-4 py-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`text-label-12-strong normal-case text-muted`,children:`Suggested query`}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14-strong text-strong`,children:e.query}),(0,$.jsx)(`p`,{className:`mt-1 text-copy-14 text-secondary`,children:e.reason})]}),n?(0,$.jsx)(q,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Review in Queries`}):null]},e.query),c=e.slice(0,1),l=a.slice(0,1),u=e.slice(1),d=a.slice(1),f=u.length+d.length;return(0,$.jsxs)(`section`,{className:`visibility-disclosure-panel`,"aria-labelledby":`overview-signals-title`,children:[(0,$.jsx)(`div`,{className:`section-head`,children:(0,$.jsx)(`h2`,{id:`overview-signals-title`,children:`Latest signals`})}),(0,$.jsxs)(`div`,{className:`divide-y divide-default border-y border-default`,children:[c.map(o),l.map(s)]}),f>0?(0,$.jsxs)(`details`,{className:`mt-2`,children:[(0,$.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,$.jsxs)(`div`,{className:`mt-2 divide-y divide-default border-y border-default`,children:[u.map(o),d.map(s)]})]}):null]})}function Xb(e){let{projectName:t}=O({from:`/projects/$projectName`}),n=es()?.dashboard.projects.find(e=>e.project.name===t||e.project.id===t)?.project.name??null,r=w({...yi({client:K}),enabled:!n}),i=n??r.data?.find(e=>e.name===t||e.id===t)?.name??null,a=on(),o=No(e.tab,a),[s,c]=(0,Q.useState)(null),l=i!==null&&s===i,u=(0,Q.useCallback)(()=>{i&&c(i)},[i]),{commandCenter:d,isLoading:f,overviewLoading:p,overviewError:m,isError:h,latestVisibilityRevision:g,competitorHistoryRevision:_,refetch:v}=Mo(i,{overview:o===`overview`&&l}),y=!n&&r.isLoading||f;return!i&&!n&&r.isSuccess&&!f?(0,$.jsx)(`div`,{className:`page-container`,children:(0,$.jsxs)(Z,{className:`surface-card empty-card`,children:[(0,$.jsx)(`h1`,{children:`Project not found`}),(0,$.jsxs)(`p`,{children:[`Could not find a project named "`,t,`".`]}),(0,$.jsx)(q,{asChild:!0,children:(0,$.jsx)(A,{to:`/`,children:`Return to overview`})})]})}):!d&&(h||r.isError)?(0,$.jsxs)(`div`,{className:`page-container`,role:`alert`,children:[(0,$.jsx)(`p`,{children:`Could not load this project.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{Promise.all([r.refetch(),v()])},children:`Retry`})]}):!d||y?(0,$.jsxs)(`div`,{className:`page-skeleton`,children:[(0,$.jsxs)(`div`,{className:`page-skeleton-header`,children:[(0,$.jsx)(`div`,{className:`skeleton-text h-6 w-48`}),(0,$.jsx)(`div`,{className:`skeleton-text-sm w-32`})]}),(0,$.jsx)(`div`,{className:`grid grid-cols-3 gap-4`,children:[1,2,3].map(e=>(0,$.jsxs)(`div`,{className:`page-skeleton-card flex flex-col items-center`,children:[(0,$.jsx)(`div`,{className:`skeleton-circle size-20`}),(0,$.jsx)(`div`,{className:`skeleton-text w-16 mt-3`})]},e))}),(0,$.jsxs)(`div`,{className:`page-skeleton-card`,children:[(0,$.jsx)(`div`,{className:`skeleton-text w-28`}),(0,$.jsx)(`div`,{className:`space-y-2 mt-2`,children:[1,2,3,4].map(e=>(0,$.jsx)(`div`,{className:`skeleton-text-sm w-full`},e))})]})]}):(0,$.jsx)(tx,{model:d,refetch:v,latestVisibilityRevision:g,competitorHistoryRevision:_,overviewLoading:p,overviewError:m,overviewRequested:l,onRequestOverview:u,...e})}function Zb({items:e,overflowItems:t,settingsItem:n,activeTab:r}){let i=(0,Q.useRef)(null),a=(0,Q.useRef)(null),[o,s]=(0,Q.useState)(null);(0,Q.useLayoutEffect)(()=>{let o=i.current,c=a.current;if(!o||!c)return;let l=()=>{let i=o.getBoundingClientRect().width;if(!i)return;let a=Number.parseFloat(getComputedStyle(o).columnGap)||0,l=new Map([...c.querySelectorAll(`[data-project-tab]`)].map(e=>[e.dataset.projectTab,e.getBoundingClientRect().width])),u=e=>l.get(e)??0,d=e=>e.reduce((e,t)=>e+u(t),0)+Math.max(0,e.length-1)*a,f=[...e.map(e=>e.key),...t.length?[`more`]:[],...n?[n.key]:[]],p=e.map(e=>e.key),m=!1;if(d(f)>i){let t=e.find(e=>e.key===r),a=t?[t.key]:[];m=!!(n&&d([...a,`more`,n.key])>i);let o=[`more`,...n&&!m?[n.key]:[]];for(let n of e)if(n.key!==t?.key){if(d([...a,n.key,...o])>i)break;a.push(n.key)}p=e.filter(e=>a.includes(e.key)).map(e=>e.key)}s(e=>e?.settingsInMore===m&&e.visibleKeys.join()===p.join()?e:{visibleKeys:p,settingsInMore:m})};if(l(),typeof ResizeObserver>`u`)return window.addEventListener(`resize`,l),()=>window.removeEventListener(`resize`,l);let u=new ResizeObserver(l);return u.observe(o),u.observe(c),()=>u.disconnect()},[e,t,n,r]);let l=o?e.filter(e=>o.visibleKeys.includes(e.key)):e,u=[...e.filter(e=>!l.includes(e)),...t,...o?.settingsInMore&&n?[n]:[]];return(0,$.jsxs)(`nav`,{className:`project-subnav`,"aria-label":`Project sections`,ref:i,children:[(0,$.jsx)(`div`,{className:`project-subnav-measure`,"aria-hidden":`true`,children:(0,$.jsxs)(`div`,{className:`project-subnav-measure-row`,ref:a,children:[[...e,...n?[n]:[]].map(e=>(0,$.jsx)(`span`,{className:`project-subnav-link`,"data-project-tab":e.key,children:e.label},e.key)),(0,$.jsxs)(`span`,{className:`project-subnav-link project-subnav-more-trigger`,"data-project-tab":`more`,children:[`More`,(0,$.jsx)(c,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]})]})}),l.map(e=>(0,$.jsx)(A,{to:e.href,search:e=>({...e,onboarding:void 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,$.jsx)(`span`,{className:`project-subnav-label`,children:e.label})},e.key)),(0,$.jsxs)(`div`,{className:`project-subnav-trailing`,children:[(0,$.jsx)(Qb,{items:u,activeTab:r}),n&&!o?.settingsInMore&&(0,$.jsx)(A,{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 Qb({items:e,activeTab:t}){let[n,r]=(0,Q.useState)(!1),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null),o=(0,Q.useRef)(`first`),s=(0,Q.useId)(),l=e.map(e=>e.key).join();if((0,Q.useEffect)(()=>{r(!1)},[l]),(0,Q.useEffect)(()=>{if(!n)return;let e=i.current?.querySelectorAll(`[role="menuitem"]`);(o.current===`last`?e?.[e.length-1]:e?.[0])?.focus()},[n]),(0,Q.useEffect)(()=>{if(!n)return;let e=e=>{i.current&&!i.current.contains(e.target)&&r(!1)},t=e=>{e.key===`Escape`&&(r(!1),a.current?.focus())};return document.addEventListener(`pointerdown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`pointerdown`,e),document.removeEventListener(`keydown`,t)}},[n]),e.length===0)return null;let u=e.some(e=>e.key===t);return(0,$.jsxs)(`div`,{className:`project-subnav-more`,ref:i,children:[(0,$.jsxs)(`button`,{type:`button`,ref:a,className:`project-subnav-link project-subnav-more-trigger ${u?`project-subnav-link-active`:``}`,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?s:void 0,onClick:()=>{o.current=`first`,r(e=>!e)},onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),o.current=e.key===`ArrowUp`?`last`:`first`,r(!0))},children:[`More`,(0,$.jsx)(c,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),n?(0,$.jsx)(`div`,{className:`project-subnav-menu`,role:`menu`,id:s,"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=>{i.current?.contains(e.relatedTarget)||r(!1)},children:e.map(e=>(0,$.jsx)(A,{to:e.href,search:e=>({...e,onboarding:void 0}),role:`menuitem`,tabIndex:-1,className:`project-subnav-menu-item ${e.key===t?`project-subnav-menu-item-active`:``}`,"aria-current":e.key===t?`page`:void 0,onClick:()=>r(!1),children:e.label},e.key))}):null]})}var $b=20,ex=5;function tx({tab:e,model:t,refetch:n,latestVisibilityRevision:r,competitorHistoryRevision:i,overviewLoading:a,overviewError:o,overviewRequested:s,onRequestOverview:c}){let l=T(),u=S(),{account:d,canWrite:p,isAdmin:m}=qn(),[h,g]=(0,Q.useState)(null),_=(0,Q.useRef)(null),v=es(),y=t.project.name,b=v?.dashboard.projects.some(e=>e.project.name===y)??!1,x=E({strict:!1}),O=Wa(x),k=tc(O),M=w({...li({client:K,path:{name:y}}),enabled:!Y()&&!!y&&(p||e===`portfolio`||e===`overview`||e===`settings`||k),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`}),N=v?v.dashboard.settings.providerStatuses.filter(e=>e.state===`ready`).map(e=>Qo(e.name)):void 0,P=M.data?.answerVisibilityProviderReady,F=N,I=t.project.providers.map(Qo),L=F?.some(e=>I.length===0||I.includes(e))===!0,R=I.length===0||I.includes(`cdp:chatgpt`),z=w({...Hi({client:K}),enabled:!Y()&&p&&P===void 0&&R&&!L,staleTime:6e4,retry:!1}),ee=R?z.isSuccess?typeof z.data.browserVersion==`string`:!z.isError&&void 0:!1,te=P??Lo({projectProviders:I,configuredApiProviders:F,cdpConfigured:ee}),ne=(0,Q.useMemo)(()=>Uo(on()),[]),re=(0,Q.useMemo)(()=>ss(on()),[]),B=(0,Q.useMemo)(()=>No(e,on()),[e]),ae=(0,Q.useMemo)(()=>t.competitors.map(e=>e.domain),[t.competitors]),oe=(0,Q.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.aliases??[]])),[t.competitors]),V=(0,Q.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.autoAliases??[]])),[t.competitors]),se=(0,Q.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,[...e.aliases??[],...e.autoAliases??[]]])),[t.competitors]),[le,ue]=(0,Q.useState)(!1),[de,fe]=(0,Q.useState)(!1),me=xo(),he=(0,Q.useCallback)((e,t)=>{l({to:`.`,search:t=>_o(t,e),replace:t?.replace===!0})},[l]),ge=x.queryWorkspace===`research`||B===`discovery`&&x.queryWorkspace===void 0?`research`:`tracked`,_e=Qs(ge,Zs(d?.role,d?.role===`viewer`?Jt():null)),U=w({...Yr({client:K,path:{name:y}}),enabled:!Y()&&(B===`queries`||B===`discovery`)&&_e===`tracked`}),ve=x.manageQueries===!0,ye=(0,Q.useCallback)(()=>{l({to:`.`,replace:!0,search:e=>({...e,siteHealthRunId:void 0})})},[l]),[be,xe]=(0,Q.useState)(ve),[Se,we]=(0,Q.useState)(``),[Te,Ee]=(0,Q.useState)(!1),[De,Oe]=(0,Q.useState)(null),[ke,Ae]=(0,Q.useState)(`30d`),[je,W]=(0,Q.useState)(void 0),[Me,Ne]=(0,Q.useState)(``),[Pe,Fe]=(0,Q.useState)(!1),[Ie,Le]=(0,Q.useState)(null),[Be,Ve]=(0,Q.useState)(!1),He=Xo(x),[Ue,We]=(0,Q.useState)(void 0),[Ge,Ke]=(0,Q.useState)(void 0),qe=(0,Q.useCallback)(e=>{We(e.search),e.sort&&Ke(e.sort),l({to:`.`,search:t=>({...t,...Ka(e)}),replace:!1})},[l]),[Je,Ye]=(0,Q.useState)(!1),Qe=t?.project.displayName||t?.project.name||y,$e=ds(),et=w({...oa({client:K,path:{name:y}}),enabled:B===`portfolio`&&!!y,staleTime:0,refetchOnMount:`always`}),tt=w({...Xi({client:K,path:{name:y}}),enabled:!Y()&&!!y&&(p||Ze()||B===`portfolio`||B===`overview`||B===`settings`),staleTime:0,refetchOnMount:`always`}),G=tt.data?.active??null,nt=tt.data!==void 0,rt=new Set(G&&Number(G.plan.schemaVersion)===2?G.plan.groups?.map(e=>e.stableKey)??[]:[]),it={...He.scope===`group`&&He.groupKey&&nt&&!rt.has(He.groupKey)?{scope:`all`,queryClass:He.queryClass}:He,...Ue?{search:Ue}:{}},at=G===null?null:Number(G.plan.schemaVersion),ot=G?.revision??0,st=nt?`${y}:${ot}`:null,ct=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=ct.current;st!==null&&(ct.current=st),ho(e,st)&&(qe({scope:`all`,queryClass:`all`}),Ye(!1))},[st,qe]);let lt={client:K,path:{name:y},query:{scope:it.scope,...it.groupKey?{groupKey:it.groupKey}:{},queryClass:it.queryClass,...it.search?{search:it.search}:{},...Ge?{sort:Ge}:{},limit:50}},ut=D({...Wi(lt),enabled:!1,initialPageParam:lt,getNextPageParam:(e,t)=>{if(!e.properties.nextCursor)return;let n=t[0]?.measurement.displayedRunId;return{path:lt.path,query:{...lt.query,cursor:e.properties.nextCursor,...n?{runId:n}:{}}}},placeholderData:j,staleTime:0,refetchOnMount:`always`}),dt=ut.data?.pages[0]?.measurement.displayedRunId,pt=w({...Si({client:K,path:{name:y},query:{revision:ot,...dt?{runId:dt}:{}}}),enabled:B===`overview`&&!!y&&G!==null&&at===1,staleTime:0,refetchOnMount:`always`}),mt=tt.data!==void 0,ht=et.data!==void 0,gt=tt.isPending&&!mt,_t=tt.isError&&!mt,vt=et.isPending&&!ht,yt=et.isError&&!ht,bt=pt.data!==void 0,St=_b({activePlanSchemaVersion:M.data?.activeSchemaVersion??at,hasDraft:M.data?.draft!==null&&M.data?.draft!==void 0}),Ct=St.surface===`simple-overview`,wt=Ze()&&G?.plan.schemaVersion===2?vb(G.plan):null,Tt=M.data===void 0&&tt.data===void 0&&(tt.isLoading||M.isLoading);(0,Q.useEffect)(()=>{B===`overview`&&Ct&&!Tt&&c()},[Tt,Ct,c,B]);let Et=nc({tab:B,surface:Tt?`unresolved`:St.surface,embedded:Y(),scoped:k,queryWorkspace:_e,tracking:U.isError?{state:`error`}:U.data?{state:`ready`,mode:U.data.mode,scopeUnavailable:$s(U.data,O)}:{state:`pending`}}),Dt=eh(y,O,{enabled:Et.kind===`report-picker`}),Ot=B===`overview`&&Ct&&!Tt,kt=Mo(y,{evidence:Ot}),At=kt.commandCenter?.visibilityEvidence??t.visibilityEvidence,Mt=(0,Q.useMemo)(()=>{let e=new Map(At.map(e=>[Xe(e.query),e.queryClass??null])),n=pe(ie(t.project));return t=>{let r=e.get(Xe(t));return r===void 0?n?.classify(t)??null:r}},[At,t.project]),Nt=(0,Q.useMemo)(()=>[...new Set([...At.map(e=>e.query),...t.movementComparison.addedQueries,...t.movementComparison.removedQueries])],[At,t.movementComparison]),Pt=(0,Q.useMemo)(()=>{if(!pe(ie(t.project)))return!1;let e=new Set(At.map(e=>Mt(e.query)));return e.has(`branded`)&&e.has(`non-brand`)},[t.project,At,Mt]),Ft=(0,Q.useMemo)(()=>t.visibilitySweeps.map(e=>e.createdAt),[t.visibilitySweeps]),It=p&&!Y()&&!H()&&B!==`overview`,Lt=w({...oa({client:K,path:{name:y}}),enabled:It,staleTime:$n,refetchOnWindowFocus:`always`}),Rt=at===2&&O.measurementScope===`group`?O.measurementScopeKey:void 0,zt=at===2&&O.measurementScope===`project`,Bt=(0,Q.useMemo)(()=>{if(G?.plan.schemaVersion===2&&Rt)return G.plan.groups.find(e=>e.stableKey===Rt)},[G,Rt]),Vt={client:K,path:{name:y},query:{window:ke,queryClass:at===2&&O.queryClass!==`unknown`?O.queryClass:`non-brand`,...Rt?{groupKey:Rt}:{},...zt?{scope:`all-markets`}:{}}},Ut=B===`overview`&&!O.marketKey&&!!y&&(Ct||nt)&&!Tt&&(Ct||(O.measurementScope===`project`||at===2&&O.measurementScope===`group`)&&O.queryClass!==`unknown`&&(at===2||O.queryClass!==`branded`)),[Wt,Kt]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{Ut||Kt(null)},[Ut]),(0,Q.useEffect)(()=>{Kt(null)},[y]);let qt=Wt===y,Yt=Ut&&qt,Xt=w({...Li(Vt),enabled:Yt,staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`});as(y,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,ot,M.data?.draft?.etag??null]),Yt);let Zt=Xt.isError?Xt.data===void 0?`Could not load competitors over time. Your pinned competitors remain available.`:`Could not refresh competitors over time. Showing the last available data.`:void 0,Qt=(0,Q.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]),$t=(0,Q.useMemo)(()=>{if(G?.plan.schemaVersion!==2)return Qt;let e=Rt?Bt?.competitors??[]:G.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 Qt){let n=e.domain.trim().toLowerCase();n&&!t.has(n)&&t.set(n,e)}return[...t.values()]},[G,Rt,Qt,Bt]),en=at===2?$t:Qt,tn=C({...gr({client:K}),meta:{skipGlobalErrorToast:!0}}),nn=M.data===void 0?M.isError?`error`:`pending`:`success`,rn=(0,Q.useMemo)(()=>{let e=ut.data?.pages;return e?!Fs(e):!1},[ut.data]),an=(0,Q.useMemo)(()=>{let e=ut.data?.pages,t=e?.[0],n=e?.at(-1);if(t&&n&&!rn)return{...t,properties:{...t.properties,items:e.flatMap(e=>e.properties.items),nextCursor:n.properties.nextCursor}}},[rn,ut.data]),sn=(0,Q.useMemo)(()=>{if(G)return G.plan.schemaVersion===1?pt.data?Ob(G,pt.data):void 0:an?js({overview:an,activePlan:G,sort:Ge,report:pt.data,reportState:an.measurement.displayedRunId===void 0?`ready`:pt.isFetching&&pt.data===void 0?`loading`:pt.isError&&pt.data===void 0?`error`:pt.data?`ready`:`loading`}):void 0},[G,pt.data,pt.isError,pt.isFetching,an]),cn=at===2?rn?`error`:ut.isPending?`loading`:ut.isError&&sn===void 0?`error`:`ready`:pt.isPending&&!bt?`loading`:pt.isError&&!bt?`error`:`ready`,ln=(t?.recentRuns??[]).some(e=>e.kind===ce[`answer-visibility`]&&(e.status===ze.running||e.status===ze.queued)),un=Ab(y,!Y()&&!H(),`manual`).data,dn=Ab(y,!Y(),`scheduled`).data,fn=un&&dn&&JSON.stringify(un)!==JSON.stringify(dn),mn=un?.refused===!0,hn=un&&!un.refused?Object.keys(un.providers):[],gn=t.queryCounts.total>0,_n=(0,Q.useMemo)(()=>(t?.project.locations??[]).map(e=>e.label),[t?.project.locations]),J=(0,Q.useMemo)(()=>new Set(At.map(e=>e.location??``)),[At]),vn=J.has(``),yn=(0,Q.useMemo)(()=>[...new Set(At.map(e=>e.query))].sort((e,t)=>e.localeCompare(t)),[At]),bn=yn.length>0||t.queryCounts.total>0||(Lt.data?.length??0)>0||G!==null,Sn=p&&!bn&&(tt.data===void 0&&tt.isPending||Lt.isLoading||Ot&&kt.evidenceLoading),Cn=p&&(M.isError&&!M.isFetching||It&&Lt.isError&&!Lt.isFetching),Tn=p&&!Cn&&(Sn||te===void 0||M.isFetching),En=!Tn&&!Cn&&bn&&te===!0,Dn=p&&!Tn&&!En,On=!Y()&&B===`overview`&&Dn&&!bn,kn=w({...Ki({client:K,path:{name:y},query:{limit:$b}}),enabled:On&&!!y,retry:!1}),An=kn.isSuccess&&kn.data.scans.some(e=>e.status===`completed`||e.status===`partial`),jn=On&&kn.isSuccess&&!An,Nn=On&&An,Pn=w({...ji({client:K,path:{name:y}}),enabled:!Y()&&!H()&&!!y,retry:!1}).data?.find(e=>e.kind===ce[`answer-visibility`]),Fn=Pn?.enabled&&Pn.nextRunAt?po(Pn.nextRunAt,Pn.timezone):null,In=Fn?`Next AI Visibility check ${Fn}`:null,Ln=(0,Q.useMemo)(()=>{let e=[...J].filter(Boolean);return e.length>1?e:_n},[J,_n]);(0,Q.useEffect)(()=>{!Ot||je===void 0||je===``||!y?(Le(null),Ve(!1)):(Ve(!0),pn(y,je,20).then(e=>{Le(e),Ve(!1)}).catch(()=>{Le(null),Ve(!1)}))},[je,y,Ot]);let Rn=(0,Q.useMemo)(()=>{if(!Ie)return null;let e=new Map;for(let t of Ie){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},[Ie]),zn=(0,Q.useMemo)(()=>{let e=je===void 0?At:At.filter(e=>je===``?!e.location:e.location===je);return Rn?e.map(e=>{let t=Rn.get(`${e.query}::${e.provider}`)??Rn.get(`${e.query}::`);return t?{...e,runHistory:t}:e}):e},[At,je,Rn]);async function Bn(){if(!(h!==y||!p||Y()||H()||$e.isPending||ln||mn||!En))try{await $e.mutateAsync({projectName:y,projectLabel:Qe,sourceAction:`project-run`}),g(null)}catch{}}function Vn(){l({to:`/setup`,search:{experience:`legacy`,setupProject:y}})}function Hn(){l({to:`/projects/$projectName/technical-aeo`,params:{projectName:y}})}async function Un(){fe(!0);try{await Ht(y),Xn({title:`Project deleted`,detail:`${Qe} was removed.`,tone:`positive`,dedupeKey:`project:delete:${y}`,dedupeMode:`drop`}),await l({to:`/`})}catch(e){console.error(`Failed to delete project:`,e)}finally{fe(!1)}}async function Wn(){let e=Se.split(`
|
|
10
|
-
`).map(e=>e.trim()).filter(Boolean);if(e.length!==0){Ee(!0);try{await xn(y,e),we(``)}finally{Ee(!1)}}}async function Gn(e){Oe(e);try{await Ce(y,[e])}catch(t){Xn({title:`Could not remove query`,detail:t instanceof Error?t.message:`Failed to remove "${e}"`,tone:`negative`,dedupeKey:`query:remove`,dedupeMode:`replace`})}finally{Oe(null)}}async function Kn(e){let t=e.trim();if(!t)return!1;try{return await Gt(y,[t]),!0}catch(e){let n=e,r=xt(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 Gt(y,[t],{acknowledgeBulkAdd:!0}),!0}catch(e){n=e}}return Xn({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 Yn(e){let n=t.competitors.find(t=>t.domain===e);if(!n)return Xn({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 Re(y,n.id),!0}catch(e){return Xn({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 Zn(e){let t=e.trim();if(!t||!Rt||at!==2||!p||Y()||tn.isPending)return!1;try{let e=await tn.mutateAsync({client:K,path:{name:y},headers:{"Idempotency-Key":Wb()},body:{expectedActiveRevision:ot,groupKey:Rt,domain:t}});return Promise.allSettled([M.refetch()]),Xn({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 Xn({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 Qn(e,t){let n=await wn(e,t);return u.setQueryData(ia({client:K,path:{name:e}}),n),Gb(u,n),n}let er=`/projects/${encodeURIComponent(t.project.name)}`,tr=[{key:`overview`,label:`AI Visibility`,href:er},{key:`search-console`,label:`Search Engines`,href:`${er}/search-console`},{key:`seo-data`,label:`SEO`,href:`${er}/seo-data`},{key:`activity`,label:`Activity`,href:`${er}/activity`},...d?.role===jt.viewer?[]:[{key:`journeys`,label:`Journeys`,href:`${er}/journeys`}],{key:`technical-aeo`,label:`Site Health`,href:`${er}/technical-aeo`},{key:`conversions`,label:`Conversions`,href:`${er}/conversions`},{key:`local`,label:`Local Presence`,href:`${er}/local`},{key:`queries`,label:`Queries`,href:`${er}/queries`},{key:`backlinks`,label:`Backlinks`,href:`${er}/backlinks`}],nr=[{key:`history`,label:`Change History`,href:`${er}/history`}],rr=[...tr.filter(e=>ko(e.key,ne)),...re===void 0?[]:[{key:`client-queries`,label:`Queries`,href:`${er}/client-queries`}]],ir=nr.filter(e=>ko(e.key,ne)),ar=p||Y()||Ze(),or=ar&&ko(`settings`,ne)?{key:`settings`,label:`Settings`,href:`${er}/settings`}:null;function sr(e){let n=Ct?e:(0,$.jsx)(rh,{projectName:y,selection:O,showUnmeasuredFallback:!G&&!gn&&O.measurementScope===`project`&&O.queryClass===`all`&&!O.provider&&!O.model&&!O.location&&!O.from&&!O.to&&!O.revision&&!O.measurementRunId&&!O.queryKey&&!O.marketKey,onSelectionChange:he,onManageQueries:Y()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:y},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:Y()?void 0:({id:e,label:t})=>(0,$.jsx)(A,{to:`/projects/$projectName/properties/$targetKey`,params:{projectName:y,targetKey:e},search:Ra,"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:Y()||H()?void 0:G?.createdAt,nextSweepDate:Y()||H()||ln?void 0:Fn??void 0,fallback:e});if(Y())return n;let r=Ia(O,Ct?`simple`:`advanced`,typeof x.sentimentEvaluationDefinitionId==`string`?x.sentimentEvaluationDefinitionId:void 0);return Ct&&(r.location=je===``?`none`:je,r=no(r,zn,Me)),(0,$.jsx)(Ro,{hasSourceEvidence:!Ct||!!(r.runId||r.runIds?.length),evidenceReady:!Ct||!(kt.isLoading||kt.evidenceLoading||kt.evidenceError),waitForResolvedRun:!Ct,projectName:y,runOptions:t.visibilitySweeps.slice(0,ex).map(e=>({id:e.id,label:Mn(e.finishedAt??e.createdAt)})),selection:r,children:n})}function cr(){switch(Et.kind){case`report-picker`:{if(Dt.error)return ft(xt(Dt.error))?(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:Xs.savedScopeUnavailable}):null;let e=Dt.data;if(!e)return(0,$.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=ec(e.scopeOptions,O)??e.selection.scope;return(0,$.jsx)(Ns,{labelVisibility:`sr-only`,options:e.scopeOptions,selected:t,marketKey:O.marketKey,onSelect:(e,t)=>he({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id,measurementMarketKey:t})})}case`tracking-picker`:{let e=U.data?.scopeOptions??[],t=ec(e,O);return t?(0,$.jsx)(Ns,{labelVisibility:`sr-only`,options:e,selected:t,onSelect:e=>he({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id})}):null}case`scope-unavailable`:return(0,$.jsx)(`p`,{className:`text-copy-13 text-secondary`,children:Xs.savedScopeUnavailable});case`project-wide`:return(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`span`,{className:`text-label-13 text-secondary`,children:Xs.projectWide}),(0,$.jsx)(X,{text:Xs.projectWideHelp})]});case`none`:return null}}let lr=B===`overview`&&!Ct&&(O.from||O.to)?`${O.from?.slice(0,10)??`First measurement`} to ${O.to?.slice(0,10)??`Latest measurement`}`:null,ur=cr(),dr=Ut?(0,$.jsx)(Nc,{window:ke,landscape:Xt.data,pinnedFallback:en,competitorAliases:oe,competitorAutoAliases:V,canWrite:p,isEmbed:Y(),onWindowChange:Ae,onPin:Rt&&p&&!Y()?Zn:!zt&&p&&!Y()?Kn:void 0,onUnpin:Rt||zt||!p||Y()?void 0:Yn,onAddCompetitor:Rt&&p&&!Y()?Zn:!zt&&p&&!Y()?Kn:void 0,error:Zt,onRetry:Yt?()=>{Xt.refetch()}:void 0,isLoading:Yt&&Xt.isPending&&Xt.data===void 0,scopeLabel:Rt?`${Bt?.label??Rt} group`:zt?`All markets`:`Project-wide`,advancedPortfolio:!Ct}):null,fr=Y()?null:(0,$.jsx)($.Fragment,{children:(0,$.jsx)(hs,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>xe(!be),children:be?`Done`:`Manage queries`})}),pr=!Y()&&be?(0,$.jsxs)(`div`,{className:`mb-3 material-base p-3`,children:[yn.length>0?(0,$.jsx)(`ul`,{className:`mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto material-base`,children:yn.map(e=>(0,$.jsxs)(`li`,{className:`flex items-center justify-between gap-3 px-3 py-2`,children:[(0,$.jsx)(`span`,{className:`min-w-0 truncate text-label-14 text-strong`,title:e,children:e}),(0,$.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:De!==null,onClick:()=>{Gn(e)},children:De===e?`Removing…`:`Remove`})]},e))}):(0,$.jsx)(`p`,{className:`mb-3 text-copy-13 text-muted`,children:`No queries tracked yet. Add some below.`}),(0,$.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:Se,onChange:e=>we(e.target.value)}),(0,$.jsxs)(`div`,{className:`mt-2 flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-copy-13 text-muted`,children:[Se.split(`
|
|
11
|
-
`).filter(e=>e.trim()).length,` to add`]}),(0,$.jsx)(hs,{type:`button`,size:`sm`,disabled:!Se.trim()||Te,onClick:Jn(Wn),children:Te?`Adding...`:`Add queries`})]})]}):null;return(0,$.jsxs)(`div`,{className:`page-container`,children:[Y()?(0,$.jsxs)(`div`,{className:`page-header`,children:[(0,$.jsxs)(`div`,{className:`page-header-left`,children:[(0,$.jsx)(`h1`,{className:`page-title`,children:t.project.displayName||t.project.name}),(0,$.jsxs)(`p`,{className:`page-subtitle`,children:[t.project.canonicalDomain,` · `,t.contextLabel]})]}),(0,$.jsx)(`div`,{className:H()?`page-header-right min-w-0 flex-wrap sm:shrink sm:justify-end`:`page-header-right`,children:lr===null?null:(0,$.jsx)(`p`,{className:`text-copy-14 text-muted`,children:lr})})]}):(0,$.jsxs)(`div`,{className:`project-context-row`,children:[(0,$.jsx)(`h1`,{className:`project-context-title md:sr-only`,children:t.project.displayName||t.project.name}),ur===null?null:(0,$.jsx)(`div`,{className:`project-context-scope`,children:ur}),t.project.canonicalDomain?(0,$.jsx)(`span`,{className:`project-context-domain`,children:t.project.canonicalDomain}):null,wt===null?null:(0,$.jsxs)(`span`,{className:`project-mode-tag`,children:[(0,$.jsx)(`span`,{className:`project-mode-tag-label`,children:`Advanced`}),(0,$.jsx)(`span`,{className:`project-mode-tag-detail`,children:wt})]}),(0,$.jsx)(`div`,{className:`project-context-actions`,"data-project-actions":!0,children:H()?(0,$.jsx)(lo,{projectName:y,running:ln,portfolio:!Ct}):(0,$.jsxs)($.Fragment,{children:[In?(0,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:In}):null,jn?(0,$.jsx)(hs,{type:`button`,onClick:Hn,children:`Map site`}):Nn?(0,$.jsx)(hs,{type:`button`,onClick:Hn,children:`View Page Health`}):null,(0,$.jsx)(hs,{type:`button`,variant:`outline`,disabled:$e.isPending||ln||Tn||mn&&!Cn&&!Dn,onClick:Cn?()=>{Promise.all([M.refetch(),...It?[Lt.refetch()]:[]])}:Dn?Vn:e=>{_.current=e.currentTarget,g(y)},children:$e.isPending?`Starting…`:ln?`AI Visibility check running…`:Tn?`Checking AI readiness…`:Cn?`Retry AI readiness`:Dn?`Set up AI Visibility`:mn?`AI Visibility checks on hold`:`Run AI Visibility check`})]})})]}),!Y()&&!H()&&(0,$.jsx)(Vb,{open:h===y,projectLabel:Qe,onOpenChange:e=>g(e?y:null),onConfirm:Jn(Bn),onClosed:()=>_.current?.focus(),disabled:$e.isPending||ln||mn||!En,leftOut:hn}),(0,$.jsx)(Zb,{items:rr,overflowItems:ir,settingsItem:or,activeTab:B}),B===`portfolio`&&!Y()?(0,$.jsx)(zy,{projectName:y,canEdit:p,queries:et.data??[],isQueryLoading:vt,isQueryError:yt,onRetryQueries:()=>{et.refetch()},publishedPlan:G,sweepActive:ln,executionProviders:t.project.providers,executionProviderModels:t.project.providerModels,onCreateQueries:async e=>(await me.mutateAsync({projectName:y,queries:[...e]}),(await et.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{l({to:`/projects/$projectName`,params:{projectName:y},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([M.refetch(),tt.refetch()]).finally(()=>{l({to:`/projects/$projectName`,params:{projectName:y}})})}},y):B===`overview`?(0,$.jsxs)($.Fragment,{children:[Y()?null:(0,$.jsxs)($.Fragment,{children:[dn?(0,$.jsx)(Nb,{admission:dn,canFix:p&&m,selection:fn||!un?`scheduled`:void 0}):null,un&&(fn||!dn)?(0,$.jsx)(Nb,{admission:un,canFix:p&&m,selection:`manual`}):null]}),Tt||Ct&&!b&&(!s||a)?(0,$.jsxs)(`div`,{role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`span`,{className:`sr-only`,children:`Loading project overview`}),(0,$.jsx)(`div`,{className:`h-32 animate-pulse rounded-md bg-surface-subtle`,"aria-hidden":`true`})]}):Ct&&o?(0,$.jsxs)(`div`,{role:`alert`,className:`page-section-divider`,children:[(0,$.jsx)(`p`,{children:`Could not load AI visibility.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,$.jsxs)($.Fragment,{children:[_t?(0,$.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,$.jsx)(`span`,{children:`Could not check the advanced measurement setup. Existing project-wide results remain available.`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{tt.refetch()},children:`Retry setup check`})]}):null,sr((0,$.jsx)(yb,{mode:St,canEdit:p&&!Y()&&!gt&&!_t,simpleOverview:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`section`,{className:`page-section-divider`,children:(0,$.jsx)(Bh,{projectName:t.project.name,competitorDomains:ae,competitorAliases:se,analyticsRevision:r,queryTexts:Nt,classifyQuery:Mt,sweepTimes:Ft,queryClassSplit:Pt})}),(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsxs)(`div`,{className:`av-card-head`,children:[(0,$.jsx)(`h2`,{className:`av-card-title`,children:`Where competitors are winning`}),gn?(0,$.jsx)(`p`,{className:`av-card-meta`,children:`Latest check`}):null]}),gn?(0,$.jsxs)(`div`,{className:`competitive-summary`,children:[(0,$.jsx)(uc,{summary:t.mentionShareSummary,projectLabel:t.project.displayName||t.project.name,competitorDomains:ae},t.project.name),(0,$.jsxs)(`div`,{className:`competitive-gaps`,children:[(0,$.jsx)(`p`,{className:`competitive-gaps-scope`,children:`All queries`}),(0,$.jsxs)(`div`,{className:`aeo-hero-rows`,children:[(0,$.jsx)(qb,{label:`Mention gaps`,summary:t.mentionGaps,displayValue:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-primary`,children:t.mentionGaps.value}),(0,$.jsxs)(`span`,{className:`text-secondary`,children:[` / `,t.queryCounts.total]}),(0,$.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,$.jsx)(qb,{label:`Citation gaps`,summary:t.gapQueries,displayValue:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`text-primary`,children:t.gapQueries.value}),(0,$.jsxs)(`span`,{className:`text-secondary`,children:[` / `,t.queryCounts.total]}),(0,$.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,$.jsx)(`p`,{className:`text-copy-14 text-secondary`,children:`Competitive mention and citation gaps appear after the first AI Visibility check.`})]}),(0,$.jsx)(`div`,{className:`page-section-divider`,children:(0,$.jsx)(lm,{projectName:t.project.name,classify:Mt,hasCompetitors:ae.length>0,providerScores:t.providerScores})}),(0,$.jsxs)(Jb,{id:`evidence-section`,title:`Query evidence`,meta:`${t.queryCounts.total} ${t.queryCounts.total===1?`query`:`queries`}`,defaultOpen:!0,children:[t.project.locations.length>0&&(0,$.jsxs)(`div`,{className:`filter-row mb-3`,role:`toolbar`,"aria-label":`Location filters`,children:[(0,$.jsx)(`button`,{className:`filter-chip ${je===void 0?`filter-chip-active`:``}`,type:`button`,"aria-pressed":je===void 0,onClick:()=>{W(void 0)},children:`All locations`}),t.project.locations.map(e=>(0,$.jsx)(`button`,{className:`filter-chip ${je===e.label?`filter-chip-active`:``}`,type:`button`,"aria-pressed":je===e.label,onClick:()=>{W(e.label),Fe(!1)},children:e.label},e.label)),vn&&(0,$.jsx)(`button`,{className:`filter-chip ${je===``?`filter-chip-active`:``}`,type:`button`,"aria-pressed":je===``,onClick:()=>{W(``),Fe(!1)},children:`No location`}),Ln.length>1&&je===void 0&&(0,$.jsx)(`button`,{className:`filter-chip filter-chip-compare ${Pe?`filter-chip-active`:``}`,type:`button`,"aria-pressed":Pe,onClick:()=>Fe(e=>!e),title:`Side-by-side location comparison`,children:`Compare`})]}),kt.evidenceLoading||kt.evidenceError?(0,$.jsxs)($.Fragment,{children:[fr&&(0,$.jsx)(Yc,{actions:fr}),pr,kt.evidenceLoading?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading query evidence…`}):(0,$.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-secondary`,children:[(0,$.jsx)(`p`,{children:`Could not load query evidence.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{kt.refetch()},children:`Retry`})]})]}):(0,$.jsx)(Xc,{evidence:zn,compareLocations:Pe,providerSelection:Me,onProviderSelectionChange:Ne,addedQueries:t.movementComparison.addedQueries,actions:fr,actionPanel:pr})]}),!Y()&&(0,$.jsx)(`div`,{className:`page-section-divider`,children:(0,$.jsx)(dm,{runs:t.recentRuns,projectName:t.project.name,collapsed:!0})})]}),report:sn,reportState:cn,onOpenSetup:Y()?void 0:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:y}})},onRetryReport:()=>{at===2?Promise.all([ut.refetch(),pt.refetch()]):pt.refetch()},onViewChange:e=>{qe({scope:e.scope,...e.groupKey?{groupKey:e.groupKey}:{},queryClass:e.queryClass,...e.search?.trim()?{search:e.search.trim()}:{}})},onLoadMore:e=>{e===an?.properties.nextCursor&&ut.fetchNextPage()},onPropertyExpand:()=>{Je&&pt.isError&&pt.refetch(),Ye(!0)},onRetryEvidence:()=>{pt.refetch()},isViewLoading:ut.isPlaceholderData,isLoadingMore:ut.isFetchingNextPage,isLoadMoreError:ut.isFetchNextPageError,viewSearch:it.search??``},`${y}:${ot}`)),!Ct&&O.measurementScope===`project`?(0,$.jsxs)(`details`,{className:`visibility-disclosure`,onToggle:e=>{e.currentTarget.open&&c()},children:[(0,$.jsx)(`summary`,{className:`visibility-disclosure-summary`,children:(0,$.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Project signals`})}),!s||a?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading project signals…`}):o?(0,$.jsxs)(`div`,{role:`alert`,className:`text-label-14 text-secondary`,children:[(0,$.jsx)(`p`,{children:`Could not load project signals.`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,$.jsx)(Yb,{insights:t.insights,suggestedQueries:t.suggestedQueries,siteDomain:t.project.canonicalDomain||void 0,onManageQueries:Y()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:y},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0})})}})]},y):null,dr===null?null:(0,$.jsxs)(`details`,{className:`visibility-disclosure${Ct?` page-section-divider`:``}`,open:qt,onToggle:e=>Kt(e.currentTarget.open?y:null),children:[(0,$.jsx)(`summary`,{className:`visibility-disclosure-summary`,children:(0,$.jsx)(`span`,{className:`visibility-disclosure-label`,children:`Competitor history`})}),(0,$.jsx)(`div`,{className:`visibility-disclosure-panel`,children:dr})]})]})]}):B===`settings`?ar?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(kb,{project:{...t.project,displayName:t.project.displayName??t.project.name,defaultLocation:t.project.defaultLocation??null},onUpdateProject:async(e,t)=>{await Qn(e,t)}}),(0,$.jsx)(Co,{project:t.project,onSave:async e=>{await Qn(t.project.name,e)}}),(0,$.jsx)(Ko,{project:t.project,onSave:async e=>{await Qn(t.project.name,{siteAuditMaxPages:e})}},t.project.id),p&&!Y()?(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsx)(`h2`,{className:`text-heading-20 text-heading`,children:`Advanced measurement`}),(0,$.jsx)(`p`,{className:`supporting-copy mt-1 mb-3`,children:`Measure individual properties, locations, or site sections with separate query sets.`}),nn===`pending`?(0,$.jsx)(`p`,{role:`status`,className:`text-copy-14 text-secondary`,children:`Loading setup…`}):nn===`error`?(0,$.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 text-label-14 text-negative`,children:[(0,$.jsx)(`span`,{children:`Could not load advanced measurement setup.`}),(0,$.jsx)(q,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{M.refetch()},children:`Retry`})]}):(0,$.jsx)(q,{type:`button`,variant:`outline`,onClick:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:y}})},children:gb(St.setupAction)})]}):null,(0,$.jsx)(Rb,{projectName:t.project.name}),(0,$.jsx)(Bb,{projectName:t.project.name}),p&&!Y()?(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsx)(`h2`,{className:`text-heading-20 text-negative-400`,children:`Delete project`}),(0,$.jsx)(`p`,{className:`supporting-copy mt-1 mb-3`,children:`Permanently deletes this project and all its queries, competitors, runs, and snapshots.`}),le?(0,$.jsxs)(Z,{className:`surface-card p-6 bg-negative-soft`,children:[(0,$.jsx)(`h3`,{className:`text-heading-16 text-negative-400 mb-2`,children:`Delete project?`}),(0,$.jsxs)(`p`,{className:`text-copy-14 text-secondary mb-4`,children:[`This will permanently delete `,(0,$.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,$.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,$.jsx)(q,{type:`button`,variant:`destructive`,disabled:de,onClick:Jn(Un),children:de?`Deleting...`:`Yes, delete project`}),(0,$.jsx)(q,{type:`button`,variant:`outline`,disabled:de,onClick:()=>ue(!1),children:`Cancel`})]})]}):(0,$.jsxs)(hs,{type:`button`,variant:`outline`,onClick:()=>ue(!0),children:[(0,$.jsx)(f,{className:`h-4 w-4 text-secondary`}),`Delete project`]})]}):null]}):(0,$.jsxs)(Z,{className:`surface-card empty-card`,children:[(0,$.jsx)(`h2`,{children:`Project settings unavailable`}),(0,$.jsx)(`p`,{children:`Your account has view-only access to this project.`}),(0,$.jsx)(q,{asChild:!0,children:(0,$.jsx)(A,{to:`/projects/$projectName`,params:{projectName:y},children:`Return to overview`})})]}):B===`client-queries`&&re!==void 0?(0,$.jsx)(o_,{projectName:y,limit:re}):B===`queries`||B===`discovery`?(0,$.jsx)(sg,{projectName:y,queryWorkspace:ge,onQueryWorkspaceChange:e=>he({queryWorkspace:e,trackingQueryId:void 0}),researchMode:x.researchMode===`test`?`test`:`find`,onResearchModeChange:e=>he({researchMode:e}),selection:O,onSelectionChange:he,trackingQueryId:typeof x.trackingQueryId==`string`?x.trackingQueryId:void 0,onTrackingQueryIdChange:e=>he({trackingQueryId:e}),publishGuard:{sweepActive:ln}}):B===`technical-aeo`?(0,$.jsx)(Ds,{projectName:t.project.name,projectId:t.project.id,initialRunId:x.siteHealthRunId,onReleaseInitialRun:ye}):B===`conversions`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(gv,{projectName:t.project.name},`${t.project.id}:performance`),(0,$.jsx)(Z_,{projectId:t.project.id,projectName:t.project.name},t.project.id)]}):B===`history`?(0,$.jsx)(s_,{projectName:t.project.name}):B===`activity`?(0,$.jsx)(qu,{projectName:t.project.name}):B===`backlinks`?(0,$.jsx)(Xd,{projectName:t.project.name}):B===`seo-data`?(0,$.jsx)(Df,{projectName:t.project.name},t.project.id):B===`journeys`?(0,$.jsx)(Pp,{projectName:t.project.name},t.project.id):B===`local`?(0,$.jsx)(_d,{projectName:t.project.name,projectId:t.project.id}):B===`search-console`?(0,$.jsx)(Kb,{projectName:t.project.name}):null]})}export{Xb as ProjectPage,Zb as ProjectSubnav,Vb as ProjectSweepConfirmation,Gb as patchProjectDashboardCache};
|