@canonry/canonry 7.68.2 → 7.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/assets/assets/{AgentSetupPage-8oLO0OyH.js → AgentSetupPage-CKRlDQZp.js} +1 -1
  2. package/assets/assets/MeasurementPropertyPage-DWwuFP2S.js +4 -0
  3. package/assets/assets/ProjectPage-D7jNMDzn.js +9 -0
  4. package/assets/assets/{RunsPage-BAs6sABy.js → RunsPage-vVs_xnqi.js} +1 -1
  5. package/assets/assets/{SettingsPage-DcSDIWnl.js → SettingsPage-wY4KTSfr.js} +1 -1
  6. package/assets/assets/SiteHealthSection-DEwB7O4i.js +2 -0
  7. package/assets/assets/{TrafficPage-CxFJj1rx.js → TrafficPage-DDpApkaw.js} +4 -4
  8. package/assets/assets/{index-CqNwsqjm.css → index-CIGmRg9U.css} +1 -1
  9. package/assets/assets/index-DPFsoLdC.js +60 -0
  10. package/assets/assets/{react-sigma_core.esm.min-Cd5EDtIB.js → react-sigma_core.esm.min-D2CArzQ5.js} +1 -1
  11. package/assets/assets/{service-CREaLXip.js → service-D57MOMmG.js} +1 -1
  12. package/assets/index.html +2 -2
  13. package/dist/{ads-4NQ5BO2A.js → ads-UTME46NF.js} +3 -3
  14. package/dist/{agent-SR7IUYLK.js → agent-PYDTNLR4.js} +7 -7
  15. package/dist/{agent-ask-F3T4GB33.js → agent-ask-NA4QFFM6.js} +3 -3
  16. package/dist/{agent-conversations-D54I2N5I.js → agent-conversations-3S56EX4U.js} +3 -3
  17. package/dist/{agent-memory-BWUJGV3E.js → agent-memory-D2RT5TVJ.js} +3 -3
  18. package/dist/{agent-providers-WNKOKIZY.js → agent-providers-5C2DRUR3.js} +3 -3
  19. package/dist/{agent-transcript-GM22FSJK.js → agent-transcript-SY5BZPO3.js} +3 -3
  20. package/dist/{analytics-RLLQBQOK.js → analytics-GUENANBB.js} +3 -3
  21. package/dist/{apply-RGJKLQKC.js → apply-R5K6RGEH.js} +3 -3
  22. package/dist/{backfill-GRVBAKFQ.js → backfill-B2EXGQCW.js} +9 -9
  23. package/dist/{backlinks-VE2JOWKE.js → backlinks-X55GUIQL.js} +3 -3
  24. package/dist/{bing-BUSRXSSR.js → bing-5NTEC247.js} +3 -3
  25. package/dist/{bootstrap-5KXIZP4O.js → bootstrap-UDEEVI4Z.js} +10 -10
  26. package/dist/{cdp-RR5HU43T.js → cdp-WWVZ6IBS.js} +7 -7
  27. package/dist/{chunk-4Q64QWKU.js → chunk-3LTLLHCD.js} +4 -4
  28. package/dist/{chunk-535S4WXN.js → chunk-3ZF3T3OG.js} +1 -1
  29. package/dist/{chunk-KXJDLN64.js → chunk-42JQQZZQ.js} +5 -5
  30. package/dist/{chunk-6R76X2XV.js → chunk-6JGQT4OH.js} +25 -2
  31. package/dist/{chunk-D33TZL7S.js → chunk-6RI7JFFI.js} +1 -1
  32. package/dist/{chunk-34GYS64G.js → chunk-7W4KNDAW.js} +2 -2
  33. package/dist/{chunk-CUR2SI66.js → chunk-BGTJTKOJ.js} +2 -2
  34. package/dist/{chunk-JZRCF3IX.js → chunk-BRT5GE3Z.js} +5 -5
  35. package/dist/{chunk-ROCSYWLF.js → chunk-CNSLBHFP.js} +1 -1
  36. package/dist/{chunk-TPZ6RLGX.js → chunk-CSDDKEL6.js} +1 -1
  37. package/dist/{chunk-LX5IQZHL.js → chunk-DW3KF33I.js} +4 -4
  38. package/dist/{chunk-35XANOXF.js → chunk-EIRIZPR6.js} +2 -2
  39. package/dist/{chunk-7PPEX3GD.js → chunk-G6VOLODK.js} +4 -4
  40. package/dist/{chunk-D4TXUHVA.js → chunk-JGO7LGVN.js} +60 -10
  41. package/dist/{chunk-MDJG5NPR.js → chunk-JNRMODJS.js} +1 -1
  42. package/dist/{chunk-YTYOUQQ7.js → chunk-JZ2A55L5.js} +31 -23
  43. package/dist/{chunk-FLCTZSLI.js → chunk-KDV5NQZH.js} +1 -1
  44. package/dist/{chunk-BVEACCUM.js → chunk-MBNXKKOD.js} +2 -2
  45. package/dist/{chunk-T742QYXD.js → chunk-NHF3OGZN.js} +3 -3
  46. package/dist/{chunk-UHDLVX3T.js → chunk-OQR4F7WF.js} +2 -2
  47. package/dist/{chunk-AGHKWDUB.js → chunk-PHHQVV3G.js} +3 -3
  48. package/dist/{chunk-4PDSDRB2.js → chunk-PJYXLC3D.js} +1 -1
  49. package/dist/{chunk-CQVK5RLO.js → chunk-QBR7BWO6.js} +8 -8
  50. package/dist/{chunk-4KVUUBKF.js → chunk-QNSMMQJY.js} +3 -3
  51. package/dist/{chunk-R5YKG2YP.js → chunk-R7RTWOOV.js} +1 -1
  52. package/dist/{chunk-4U3HIUCW.js → chunk-RJSJNR76.js} +3 -3
  53. package/dist/{chunk-XU7GZ544.js → chunk-RPYSCFFA.js} +1 -1
  54. package/dist/{chunk-2M27P4W5.js → chunk-RSK7E53V.js} +1 -1
  55. package/dist/{chunk-HF7ONR3Z.js → chunk-RVEXUQHP.js} +2 -2
  56. package/dist/{chunk-ON2RUGPD.js → chunk-SFMCFMJR.js} +1 -1
  57. package/dist/{chunk-VXBAMLKH.js → chunk-SSNKQTRX.js} +3 -3
  58. package/dist/{chunk-5TCY7FYS.js → chunk-ULUKHNE4.js} +1 -1
  59. package/dist/{chunk-JQGH3D7W.js → chunk-WZZIA3LD.js} +334 -334
  60. package/dist/{chunk-QZUEQP5G.js → chunk-XOCF2U54.js} +1 -1
  61. package/dist/{citations-IYQAT5QA.js → citations-ILU2CNT2.js} +3 -3
  62. package/dist/{cli-catalog-U5ZXWV7J.js → cli-catalog-ZBTUYNJA.js} +3 -3
  63. package/dist/{cli-commands-MMMD7K74.js → cli-commands-YXL7KV5B.js} +7 -7
  64. package/dist/cli.js +13 -13
  65. package/dist/{competitor-RRISAXMS.js → competitor-NXSL3AWD.js} +3 -3
  66. package/dist/{content-NBEVQ7CZ.js → content-TGWYXNBI.js} +3 -3
  67. package/dist/{dashboard-EMHIZOZ4.js → dashboard-IDCQTIYG.js} +6 -6
  68. package/dist/{demo-57LZOEH6.js → demo-6X6IDMPT.js} +1 -1
  69. package/dist/{demo-server-EGKJKILE.js → demo-server-HKJWIYPQ.js} +11 -11
  70. package/dist/{discover-L5EFJ6AD.js → discover-NW7NKL2Z.js} +3 -3
  71. package/dist/{discover-eval-6JJZLKRJ.js → discover-eval-2BVYL62I.js} +3 -3
  72. package/dist/{doctor-QBTFEURQ.js → doctor-6I3LPYM7.js} +3 -3
  73. package/dist/{evidence-I5MK557J.js → evidence-ZTAMPBEP.js} +3 -3
  74. package/dist/{export-cmd-36EZW5ZP.js → export-cmd-4CXUQVYT.js} +3 -3
  75. package/dist/{ga-7GUXDQ3L.js → ga-2YXMDGHQ.js} +3 -3
  76. package/dist/{gbp-W7YHYMB7.js → gbp-LTPPWTUR.js} +3 -3
  77. package/dist/{google-OXQFPJ76.js → google-KTUJ4D3T.js} +4 -4
  78. package/dist/{google-marketing-TKCACXPQ.js → google-marketing-FAKTAI5S.js} +1 -1
  79. package/dist/{health-cmd-PG3ST3S6.js → health-cmd-C75E3NPQ.js} +3 -3
  80. package/dist/{history-NWLOV4HF.js → history-HE734BPT.js} +3 -3
  81. package/dist/index.d.ts +71 -71
  82. package/dist/index.js +24 -24
  83. package/dist/{init-3I6WH2FY.js → init-QWTQCLAK.js} +11 -11
  84. package/dist/{insights-2XU6EXSV.js → insights-4GUVXY2V.js} +3 -3
  85. package/dist/intelligence-service-PAMFRLPE.js +15 -0
  86. package/dist/{journeys-LIZVLLV5.js → journeys-BZCKKFG7.js} +3 -3
  87. package/dist/{keys-M4WPOLHC.js → keys-CMN3FUDW.js} +3 -3
  88. package/dist/{keyword-TETX5PQP.js → keyword-QUM65R7C.js} +3 -3
  89. package/dist/{logs-BI4265UF.js → logs-HH7EP7YK.js} +3 -3
  90. package/dist/{mcp-RA6NUGQM.js → mcp-76T6WX4K.js} +2 -2
  91. package/dist/mcp.js +9 -9
  92. package/dist/{measurement-plan-LM5GXYNS.js → measurement-plan-2D2KQLTW.js} +5 -5
  93. package/dist/{notify-BFKYHACB.js → notify-VP5YYBJO.js} +3 -3
  94. package/dist/{organic-evidence-RUBPJCQ4.js → organic-evidence-EAUZJVET.js} +3 -3
  95. package/dist/{overview-6WOQ7K7F.js → overview-MCX3OHXK.js} +4 -4
  96. package/dist/{project-2DMAPH2U.js → project-HMELPKXT.js} +3 -3
  97. package/dist/{query-SAWKYRSY.js → query-J7UTKCY5.js} +3 -3
  98. package/dist/{research-J4J527SF.js → research-O4FYADRL.js} +3 -3
  99. package/dist/{results-export-SESXZCWZ.js → results-export-4JHIHSWW.js} +3 -3
  100. package/dist/{run-XTG3RSBA.js → run-YJ3Y7FIE.js} +4 -4
  101. package/dist/{schedule-WQUD7BAI.js → schedule-6SXEB245.js} +3 -3
  102. package/dist/{search-QNYEHVCA.js → search-MVL346VH.js} +3 -3
  103. package/dist/{serve-7SCK3TEE.js → serve-4E6LBEHL.js} +25 -25
  104. package/dist/{session-KB3HFDGB.js → session-KFFTQBJU.js} +12 -12
  105. package/dist/{settings-P5E7KIOV.js → settings-UKVP6TDD.js} +3 -3
  106. package/dist/{skills-YQDZ6EOW.js → skills-DF336KFJ.js} +2 -2
  107. package/dist/{snapshot-LMBEQKXR.js → snapshot-YKWGIRTM.js} +3 -3
  108. package/dist/{src-X4GNC6AB.js → src-WDWTA7ON.js} +2 -2
  109. package/dist/{status-4G7OU4RY.js → status-4PDQOFYS.js} +4 -4
  110. package/dist/{technical-aeo-TBCA6DF2.js → technical-aeo-XJRWNW24.js} +3 -3
  111. package/dist/{telemetry-JGUQ6S45.js → telemetry-TXB7NGPP.js} +4 -4
  112. package/dist/{tools-FB7DZH74.js → tools-5DBHZB4K.js} +11 -11
  113. package/dist/{traffic-U6MUCCBI.js → traffic-AP22ENAC.js} +5 -5
  114. package/dist/{users-P7BMJH2I.js → users-44XJB4ZN.js} +3 -3
  115. package/dist/{visibility-stats-3BJR34GR.js → visibility-stats-5DMILJO6.js} +3 -3
  116. package/dist/{wordpress-X5FQOR5K.js → wordpress-P6J44TMN.js} +3 -3
  117. package/package.json +1 -1
  118. package/assets/assets/MeasurementPropertyPage--nWpGvGH.js +0 -4
  119. package/assets/assets/ProjectPage-of9Q7JDS.js +0 -9
  120. package/assets/assets/SiteHealthSection-DS4icWI5.js +0 -2
  121. package/assets/assets/index-XtskVqLa.js +0 -60
  122. package/dist/intelligence-service-VUOMVRAD.js +0 -15
@@ -1,9 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-XKyaHtl9.js";import{C as t,E as n,G as r,H as i,K as a,L as o,M as s,Q as c,S as l,U as u,i as d,j as f,nt as p,r as m,rt as h,s as g,t as _,v,x as y}from"./vendor-lucide-4KkDquAu.js";import{r as b}from"./vendor-markdown-9SSeLNHZ.js";import{E as x,_ as S,b as C,d as w,f as T,g as E,p as D,u as O,w as k}from"./vendor-tanstack-pEsPGDvT.js";import{c as A,f as j,i as M,l as N,m as P,o as F,p as I,r as L,s as R,t as z,u as ee}from"./vendor-recharts-qIim36Mt.js";import{$n as B,A as V,B as H,Br as te,Bt as ne,Ci as re,Cr as ie,Ct as U,Dn as ae,Ei as oe,Et as se,F as ce,Fi as le,Fr as ue,Ft as de,G as fe,Gn as pe,Gr as me,Gt as he,Hn as ge,Hr as _e,Ht as ve,Ii as ye,Ir as be,It as xe,J as Se,Jn as Ce,Jr as W,Kn as we,Kr as Te,Li as G,Lr as Ee,Lt as De,M as Oe,Mi as ke,Mt as Ae,N as je,Ni as Me,Nt as Ne,O as Pe,Oi as Fe,P as Ie,Pt as Le,Qn as Re,Rr as ze,Si as Be,Sr as Ve,St as He,Tr as Ue,U as We,Un as K,Ur as Ge,Ut as Ke,V as qe,Vn as Je,Vt as Ye,Wn as Xe,Wr as Ze,Xn as Qe,Xr as $e,Yn as et,Yr as tt,Zn as nt,_i as rt,_r as it,a as at,an as ot,ar as st,at as ct,b as lt,bi as ut,br as dt,c as ft,cr as pt,ct as mt,di as ht,er as gt,f as _t,fi as vt,fr as yt,gi as bt,gn as xt,gr as St,gt as Ct,h as wt,hi as Tt,hr as Et,ht as Dt,in as Ot,ir as kt,ji as At,k as jt,ki as Mt,l as Nt,lt as Pt,m as Ft,mi as It,mr as Lt,mt as Rt,nr as zt,nt as Bt,o as Vt,on as Ht,or as Ut,p as Wt,pt as q,qn as Gt,qr as Kt,r as J,rt as qt,s as Jt,sn as Yt,sr as Xt,t as Y,tn as Zt,tr as Qt,u as $t,ui as en,ut as tn,vr as nn,wr as rn,wt as an,xi as on,xr as sn,yi as cn,yr as ln,zi as un}from"./ToneBadge-B8lm5z8O.js";import{_ as dn,a as fn,b as pn,c as mn,d as hn,f as gn,g as _n,h as vn,i as yn,m as bn,n as xn,o as Sn,r as Cn,t as wn,v as Tn,x as En,y as Dn}from"./format-helpers-C2il_710.js";import{r as On}from"./account-context-VRNXJv_l.js";import{t as kn}from"./async-handler-Bj3TnIRw.js";import{a as An,d as jn,l as Mn,n as Nn,o as Pn,s as Fn,t as In,u as Ln}from"./query-client-DyFmy9AJ.js";import{$ as Rn,A as zn,At as Bn,B as Vn,C as Hn,Ct as Un,D as Wn,Dt as Gn,E as Kn,Et as qn,F as Jn,G as Yn,H as Xn,Ht as Zn,I as Qn,J as $n,K as er,L as tr,M as nr,N as rr,O as ir,Ot as ar,P as or,R as sr,S as cr,St as lr,T as ur,Tt as dr,U as fr,V as pr,W as mr,X as hr,Xt as gr,Yt as _r,_ as vr,_n as yr,_t as br,an as xr,at as Sr,b as Cr,bn as wr,bt as Tr,c as Er,cn as Dr,ct as Or,d as kr,dn as Ar,dt as jr,en as Mr,f as Nr,fn as Pr,ft as Fr,g as Ir,gn as Lr,gt as Rr,h as zr,hn as Br,ht as Vr,in as Hr,j as Ur,k as Wr,kt as Gr,l as Kr,ln as qr,m as Jr,mn as Yr,mt as Xr,n as Zr,nt as Qr,o as $r,on as ei,ot as ti,p as ni,pn as ri,pt as ii,q as ai,r as oi,rt as si,s as ci,sn as li,st as ui,t as di,tn as fi,u as pi,un as mi,ut as hi,v as gi,vn as _i,vt as vi,w as yi,wt as bi,x as xi,xn as Si,xt as Ci,y as wi,yn as Ti,yt as Ei,z as Di}from"./react-query-BcEtnzKt.js";import{_ as Oi,a as ki,c as Ai,d as ji,f as Mi,g as Ni,h as Pi,i as Fi,l as Ii,m as Li,n as Ri,o as zi,p as Bi,r as Vi,s as Hi,t as Ui,u as Wi}from"./ChartPrimitives-CksxPvHn.js";import{t as X}from"./InfoTooltip-BbdxCAup.js";import{t as Z}from"./card-CPDjkZ38.js";import{$t as Gi,A as Ki,At as qi,B as Ji,Bt as Yi,C as Xi,Ct as Zi,D as Qi,Dt as $i,E as ea,Et as ta,F as na,Ft as ra,G as ia,Gt as aa,H as oa,Ht as sa,It as ca,J as la,Jt as ua,K as da,Kt as fa,L as pa,Lt as ma,M as ha,Mt as ga,N as _a,Nt as va,O as ya,Ot as ba,P as xa,Pt as Sa,Q as Ca,Qt as wa,Rt as Ta,St as Ea,Tt as Da,U as Oa,Ut as ka,V as Aa,Vt as ja,W as Ma,Wt as Na,Xt as Pa,Y as Fa,Yt as Ia,Z as La,Zt as Ra,_ as za,_t as Ba,a as Va,at as Ha,b as Ua,bt as Wa,c as Ga,cn as Ka,ct as qa,dt as Ja,en as Ya,et as Xa,gt as Za,ht as Qa,i as $a,in as eo,it as to,j as no,jt as ro,k as io,kt as ao,l as oo,lt as so,mt as co,nn as lo,nt as uo,o as fo,on as po,pt as mo,q as ho,qt as go,r as _o,rn as vo,s as yo,sn as bo,st as xo,u as So,ut as Co,vt as wo,wt as To,x as Eo,xt as Do,y as Oo,yt as ko,z as Ao,zt as jo}from"./index-XtskVqLa.js";import{a as Mo,i as No,o as Po,r as Fo,s as Io,t as Lo}from"./SiteHealthSection-DS4icWI5.js";import{t as Ro}from"./Hint-C0TmIzHX.js";import{t as zo}from"./AuditHistoryPanel-DXXGdrLo.js";import{a as Bo,d as Vo,i as Ho,l as Uo,n as Wo,o as Go,r as Ko,t as qo,u as Jo}from"./service-CREaLXip.js";import{l as Yo,n as Xo,r as Zo,s as Qo,t as $o,u as es}from"./extract-error-message-Ba5pz5dQ.js";var ts=1e6;function ns(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/ts);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(h(),1),rs={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 is(e,t){return e!==`viewer`||t!==null}function as(e,t){return e===`research`&&!t?`tracked`:e}function os(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 ss(e,t){return e.find(e=>e.kind===t.measurementScope&&(e.kind===`project`||e.id===t.measurementScopeKey))}function cs(e){return e.measurementScope!==`project`||e.marketKey!==void 0}function ls(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`settings`:case`portfolio`:case`seo-data`:return{kind:`none`};default:return t}}var $=b();function us({state:e,label:t,className:n}){return(0,$.jsx)(Y,{tone:eo(e),className:n,children:t??Dn(e)})}var ds=[{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],fs={"non-brand":`Non-brand`,branded:`Branded`,pooled:`All queries`},ps={"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.`},ms=`Mentioned = brand in the answer. Cited = domain in the sources. Neither implies the other.`;function hs(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:W(e.score,oe.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 gs({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:ms})]}),(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 font-medium`:`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:W(e.share)})]},e.label))})]})}function _s({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=hs(u,{hasCompetitors:n.length>0,unavailable:e.unavailable===!0,noRun:e.breakdown.snapshotsTotal===0&&e.branded.snapshotsTotal===0,otherClassHasData:d.snapshotsTotal>0}),p=dn(f.headline),m=l===`non-brand`?lo[e.tone]:`text-secondary`;function h(e){let t=ds.findIndex(e=>e.value===c),n=null;e.key===`ArrowRight`||e.key===`ArrowDown`?n=(t+1)%ds.length:e.key===`ArrowLeft`||e.key===`ArrowUp`?n=(t-1+ds.length)%ds.length:e.key===`Home`?n=0:e.key===`End`&&(n=ds.length-1),n!==null&&(e.preventDefault(),i(ds[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:ps[l]})]}),s?(0,$.jsx)(`div`,{role:`radiogroup`,"aria-labelledby":a,className:`segmented flex-wrap`,onKeyDown:h,children:ds.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:fs[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:fs[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)(gs,{breakdown:u,projectLabel:t})]})}function vs({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))})]})}function ys({options:e,value:t,onChange:n,label:r,className:i=``}){let a=(0,Q.useId)();function o(r){let i=e.findIndex(e=>e.value===t),a=null;r.key===`ArrowRight`||r.key===`ArrowDown`?a=(i+1)%e.length:r.key===`ArrowLeft`||r.key===`ArrowUp`?a=(i-1+e.length)%e.length:r.key===`Home`?a=0:r.key===`End`&&(a=e.length-1),a!==null&&(r.preventDefault(),n(e[a].value),r.currentTarget.querySelectorAll(`[role="radio"]`)[a].focus())}return(0,$.jsx)(`div`,{role:`radiogroup`,"aria-label":r,className:`segmented ${i}`.trim(),onKeyDown:o,children:e.map(e=>{let r=e.value===t,i=e.description?`${a}-${e.value}`:void 0;return(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":r,"aria-describedby":i,tabIndex:r?0:-1,onClick:()=>n(e.value),className:`segmented-option pointer-coarse:min-h-11 ${r?`segmented-option-active`:``}`,children:e.label}),e.description?(0,$.jsx)(`span`,{id:i,className:`sr-only`,children:e.description}):null]},e.value)})})}var bs=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],xs={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,all:`all checks`},Ss={"non-brand":`Non-brand`,branded:`Branded`,all:`All queries`},Cs={"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.`},ws={"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`},Ts=`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.`,Es=100;function Ds(e){return e?e.evidence.answeredResults>0||e.evidence.sourceResults>0?`measured`:`not-measured`:`unavailable`}function Os(e){return e===`unavailable`?`Unavailable`:`Not measured`}function ks(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 As(e,t,n){return e===1?t:n}function js(e){let t=e.label.trim(),n=Fe(e.domain);return t&&t.toLowerCase()!==e.domain.toLowerCase()&&t.toLowerCase()!==n.toLowerCase()?t:null}function Ms({row:e,aliases:t=[],autoAliases:n=[]}){let r=js(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 Ns(e){let t=js(e);return t?`${t} (${e.domain})`:e.domain}function Ps(e,t){return t&&e>=Es?(0,$.jsxs)($.Fragment,{children:[`top `,(0,$.jsx)(`strong`,{children:e})]}):(0,$.jsx)(`strong`,{children:e})}function Fs({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)(J,{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 Is({urls:e}){return(0,$.jsxs)(`details`,{className:`inline-disclosure text-left text-xs text-secondary`,children:[(0,$.jsx)(`summary`,{children:`Source URLs`}),(0,$.jsx)(`ul`,{className:`mt-2 max-w-72 space-y-1 font-mono text-[11px] font-normal`,children:e.map(e=>(0,$.jsx)(`li`,{className:`break-all`,children:e},e))})]})}function Ls({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-[13px] text-secondary`,children:Os(n)})}function Rs({percent:e,state:t,toneClass:n}){if(t!==`measured`||e===null)return(0,$.jsx)(`span`,{className:`text-[13px] text-secondary`,children:t===`measured`?`Not measured`:Os(t)});let{figure:r,sign:i}=dn(W(e,oe.percent));return(0,$.jsxs)(`span`,{className:`av-n-sm ${n}`,children:[r,i?(0,$.jsx)(`span`,{className:`text-faint`,children:i}):null]})}function zs({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)(Ms,{row:e})}),(0,$.jsx)(`td`,{className:`text-[13px] text-secondary`,children:ks(e.surfaceClass)}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ls,{count:e.mentionCount,of:n,state:t,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ls,{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)(Is,{urls:e.sampleUrls}):null,i?(0,$.jsx)(Fs,{action:`pin`,domain:e.domain,mutation:i}):null]})})]},e.domain))})]})})}function Bs({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-sm font-medium 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-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400`})]}),(0,$.jsx)(J,{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-sm text-negative`,children:o}):null]})]})}function Vs({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=Ds(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?lo[vo(t.project.shareOfVoice)]:`text-primary`,M=e=>_?e.pinned?l?(0,$.jsx)(Fs,{action:`unpin`,domain:e.domain,mutation:l}):null:c?(0,$.jsx)(Fs,{action:`pin`,domain:e.domain,mutation:c}):null:null,N=w.some(e=>M(e)!==null),P=[m,E?Ss[E]:null,xs[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: ${ws[t.reason]}`}),t&&T.length>0){let e=T.length;F.push({key:`others`,text:O&&e>=Es?`${Es} or more other competitors seen`:`${e} other ${As(e,`competitor`,`competitors`)} seen`})}D>0&&F.push({key:`pending`,text:`${t?.scope.kind===`all-markets`?`Pending publication across markets`:`Pending publication`}: ${D} ${As(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:lo.caution});let L=[];if(t&&x){L.push(t.runCount===void 0?(0,$.jsxs)($.Fragment,{children:[`Base: `,(0,$.jsx)(`strong`,{children:x.answeredResults}),` `,As(x.answeredResults,`answer`,`answers`)]}):(0,$.jsxs)($.Fragment,{children:[`Base: `,(0,$.jsx)(`strong`,{children:t.runCount}),` `,As(t.runCount,`check`,`checks`),`, `,(0,$.jsx)(`strong`,{children:x.answeredResults}),` `,As(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}),` `,As(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}),` `,As(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}),` `,As(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 font-mono text-[11px] 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: `,Ps(T.length,O)]}),(0,$.jsx)(`div`,{className:`av-subdetails-body`,children:(0,$.jsx)(zs,{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,` `,As(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: `,Ps(b.length,O)]}),(0,$.jsx)(`ul`,{className:`av-subdetails-body`,children:b.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsxs)(`span`,{children:[Ns(e),` · `,ks(e.surfaceClass),` · `,e.citationCount,` `,As(e.citationCount,`citation`,`citations`)]}),e.sampleUrls.length>0?(0,$.jsx)(`ul`,{className:`mt-1 space-y-1 font-mono text-[11px] 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?`${Cs[E]} ${Ts}`:Ts})]}),(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)(ys,{label:`Competitors over time window`,className:`flex-wrap`,options:bs,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-sm text-negative`,children:[(0,$.jsx)(`span`,{children:d}),f?(0,$.jsx)(J,{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-[13px] text-secondary`,children:`Your brand`}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Rs,{percent:t.project.shareOfVoice,state:S,toneClass:j})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ls,{count:t.project.mentionCount,of:k,state:S,toneClass:j})}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(Ls,{count:t.project.citationCount,of:A,state:S,toneClass:j}),h&&S===`measured`?(0,$.jsx)(`span`,{className:`block text-[13px] text-secondary`,children:_n(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)(Ms,{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-[13px] text-secondary`,children:ks(e.surfaceClass)}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Rs,{percent:e.shareOfVoice,state:S,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ls,{count:e.mentionCount,of:k,state:S,toneClass:`text-primary`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ls,{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-[13px] text-secondary`,children:F.map(e=>(0,$.jsx)(`p`,{className:e.className,children:e.text},e.key))}):null]}),(0,$.jsx)(vs,{items:L}),_&&u?(0,$.jsx)(`div`,{className:`border-t border-subtle px-5 py-3`,children:(0,$.jsx)(Bs,{onAddCompetitor:u})}):null]})}function Hs({history:e,maxDots:t=12,signal:n=`citations`}){let r=e.slice(-t);if(r.length===0)return(0,$.jsx)(`span`,{className:`text-[13px] 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-[11px] 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-[11px] shrink-0 text-secondary`,"aria-hidden":`true`,children:[u,` `,(0,$.jsx)(`span`,{children:`latest`})]})]})}function Us(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 Ws=320;function Gs(e){return e===`branded`?`Branded`:e===`non-brand`?`Non-brand`:`Unclassified`}function Ks(e){return e===`non-brand`?0:e===`branded`?1:2}function qs(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 Js(e){return e.phrase}function Ys(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 Xs(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 Zs(e,t){return e.map(e=>Qs(e,t))}function Qs(e,t){return t===`citations`?e:{...e,citationState:Ys(e,t),runHistory:e.runHistory.map(e=>({...e,citationState:Ys(e,t)}))}}function $s(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 ec(e){let t=Us(Zs(e,`mentions`)),n=Us(e);return[$s(t,`mentions`),$s(n,`citations`)]}function tc({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 nc({items:e}){return(0,$.jsx)(`div`,{className:`query-evidence-signals`,"aria-label":`Latest run mention and citation signals`,children:ec(e).map(e=>(0,$.jsx)(tc,{signal:e},e.key))})}function rc({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)(ya,{}),t]})}):null,e?(0,$.jsx)(io,{queryClass:e,manage:!!t}):null]})}function ic({evidence:e,compareLocations:t=!1,defaultDensity:n=`detailed`,providerSelection:r,onProviderSelectionChange:i,addedQueries:a=[],actions:o,actionPanel:s}){let{openEvidence:c}=Fa(),l=(0,Q.useId)(),[d,f]=(0,Q.useState)(new Set),p=ha(),[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(Qs(r,m)),s.rawItems.push(r),n.set(o,s)}return[...n.values()].sort((e,t)=>Ks(e.queryClass)-Ks(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=Io({rows:E,getSearchText:Js}),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(yt)),[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)(rc,{queryClass:v,actions:o}),s,(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:`${l}-${e}`,type:`button`,role:`tab`,"aria-controls":l,"aria-selected":m===e,tabIndex:m===e?0:-1,onClick:()=>h(e),onKeyDown:t=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t.key))return;t.preventDefault();let n=t.key===`Home`?`mentions`:t.key===`End`||e===`mentions`?`citations`:`mentions`;h(n),document.getElementById(`${l}-${n}`)?.focus()},children:e===`mentions`?`Mentions`:`Citations`},e))}),(0,$.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)(J,{type:`button`,variant:`ghost`,className:`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)(No,{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:ra(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:l,role:`tabpanel`,"aria-labelledby":`${l}-${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`})})]})}),qs(D.rows).map(e=>(0,$.jsxs)(`tbody`,{children:[(0,$.jsx)(`tr`,{className:`query-evidence-group`,children:(0,$.jsxs)(`th`,{scope:`rowgroup`,colSpan:A,children:[Gs(e.queryClass),` (`,O.get(e.queryClass)?.size??0,`)`]})}),e.rows.map(({key:e,phrase:n,queryClass:r,location:i,items:a,rawItems:o})=>{let s=d.has(e),f=j.indexOf(e),h=`${l}-query-${f}`,_=k.has(yt(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(o.map(e=>e.queryId).filter(e=>!!e))],x=o.map(e=>e.sourceSnapshotId).filter(e=>!!e),S=Us(a),C=a.filter(e=>e.citationState===en.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":s,onClick:t=>{t.stopPropagation(),N(e)},children:[(0,$.jsx)(u,{size:16,"aria-hidden":`true`,className:s?`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:Gs(r)}),t&&(0,$.jsx)(`span`,{children:i??`No location`}),a.filter(e=>e.provider).map(e=>(0,$.jsx)(`span`,{children:ra(e.provider)},e.id))]})]})]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(us,{state:y,label:Xs(y,m),className:`rounded-none border-0 bg-transparent p-0 text-sm tracking-normal`}),(0,$.jsxs)(`span`,{className:`text-sm 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)(Ki,{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)(Hs,{history:S,signal:m})}),(0,$.jsx)(`td`,{className:`evidence-change-cell`,children:_?(0,$.jsx)(`span`,{className:`query-evidence-new`,children:`new query`}):(0,$.jsx)(nc,{items:o})}),(0,$.jsx)(`td`,{})]}),s&&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-sm text-secondary`,children:e.provider?ra(e.provider):`Awaiting engine`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(us,{state:e.citationState,className:`rounded-none border-0 bg-transparent p-0 text-sm tracking-normal`,label:Xs(e.citationState,m)})}),p&&(0,$.jsx)(`td`,{children:(0,$.jsx)(Qi,{queryId:e.queryId,sourceSnapshotIds:e.sourceSnapshotId?[e.sourceSnapshotId]:[],queryClass:e.queryClass,provider:e.provider,location:e.location??null})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Hs,{history:e.runHistory,signal:m})}),(0,$.jsx)(`td`,{className:`evidence-change-cell`,children:_?null:(0,$.jsx)(nc,{items:[o[t]??e]})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(J,{variant:`ghost`,className:`min-h-11`,type:`button`,title:`View ${e.provider?ra(e.provider):`saved`} answer for ${e.query}`,onClick:t=>{t.stopPropagation(),c(e.id)},children:`View`})})]}),g===`detailed`&&(0,$.jsx)(`tr`,{className:`query-evidence-preview-row`,children:(0,$.jsx)(`td`,{colSpan:A,children:(0,$.jsx)(sc,{item:e,mode:m,onViewFull:()=>c(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)(Fo,{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 ac(e){let t=(e.matchedTerms??[]).filter(e=>e.trim().length>2),n=uo(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 oc(e,t){let n=t.toLowerCase().replace(/^www\./,``);return(e.citedCompetitorDomains??[]).some(e=>e.toLowerCase().replace(/^www\./,``)===n)}function sc({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)(cc,{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-[13px] font-medium 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)(to,{url:t.uri,title:t.title}),oc(e,Mt(t.uri)??``)&&(0,$.jsx)(`p`,{className:`mt-1 text-[13px] text-secondary`,children:`Competitor source`})]},`${n}-${t.uri}`))}):e.citedDomains.length>0?(0,$.jsx)(`ul`,{className:`space-y-1 text-sm text-secondary`,children:e.citedDomains.slice(0,a?void 0:6).map(t=>(0,$.jsxs)(`li`,{className:`[overflow-wrap:anywhere]`,children:[t,oc(e,t)?` · competitor source`:``]},t))}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No cited sources captured for this run.`}),(s.length>6||s.length===0&&e.citedDomains.length>6)&&(0,$.jsx)(J,{type:`button`,variant:`ghost`,className:`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-sm 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)(cc,{item:e,onViewFull:n,contextOnly:!0})]}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No answer text captured for this run.`})]})}function cc({item:e,onViewFull:t,contextOnly:n=!1}){let{matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}=e,s=(0,Q.useMemo)(()=>ac({matchedTerms:r,mentionedCompetitorDomains:i,mentionedCompetitorTerms:a,recommendedCompetitors:o}),[r,i,a,o]);if(!(e.answerSnippet.trim().length>0))return(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No answer text captured for this run.`});let c=e.answerSnippet.length>Ws;return(0,$.jsxs)(`div`,{className:`query-evidence-preview space-y-3`,children:[!n&&(0,$.jsx)(`p`,{className:`text-[13px] font-medium text-secondary`,children:`Answer text`}),(0,$.jsx)(Vo,{headingLevel:4,highlightGroups:s,previewLength:Ws,children:e.answerSnippet}),(!n&&e.citedDomains.length>0||(e.mentionedCompetitorDomains?.length??0)>0)&&(0,$.jsxs)(`dl`,{className:`space-y-2 text-[13px] leading-6 text-secondary`,children:[!n&&e.citedDomains.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-medium`,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,oc(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:`font-medium`,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)(J,{type:`button`,variant:`ghost`,className:`min-h-11`,onClick:e=>{e.stopPropagation(),t()},children:`View full answer`})]})}function lc({label:e,value:t,tone:n}){return(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:e}),(0,$.jsx)(`p`,{className:`mt-2 text-2xl font-semibold ${n===`positive`?`text-positive-400`:n===`negative`?`text-negative-400`:`text-strong`}`,children:t})]})}function uc({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&&ae(`window`),n(e)},children:i?i(e):e},e))})}var dc=`baseline`;function fc(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,[dc]:i.get(e)??null};for(let e of n)a[e.dataKey]=t?.[e.key]??0;return a}),series:n}}var pc=`text-[11px] font-medium uppercase tracking-wider text-muted`;function mc({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-base font-semibold text-primary`,children:t}),n&&(0,$.jsx)(X,{text:n})]}),r&&(0,$.jsx)(`p`,{className:`mt-1 text-xs text-secondary`,children:r})]}),i]})}function hc({children:e}){return(0,$.jsx)(`div`,{className:`[&>details:first-child]:border-t-0`,children:e})}function gc({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 _c={3:`lg:grid-cols-3`,4:`lg:grid-cols-4`,5:`lg:grid-cols-5`};function vc({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 ${_c[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-[13px] text-secondary`,children:[e.label,e.tooltip&&(0,$.jsx)(X,{text:e.tooltip})]}),(0,$.jsx)(`dd`,{className:`mt-1 truncate text-xl font-semibold text-primary tabular-nums`,title:e.value,children:e.value}),e.detail&&(0,$.jsx)(`dd`,{className:`mt-0.5 text-[13px] text-secondary tabular-nums`,children:e.detail})]},e.label))})})}function yc({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:`${pc} 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 bc({label:e,align:t}){return(0,$.jsx)(`th`,{className:`py-2 ${t===`right`?`pl-4 text-right`:`text-left`}`,children:(0,$.jsx)(`span`,{className:pc,children:e})})}function xc(e,t,n=`desc`){return e.key===t?{key:t,dir:e.dir===`desc`?`asc`:`desc`}:{key:t,dir:n}}function Sc(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 Cc({groups:e,groupLabel:t,caption:n,childColumns:i,childRowKey:a,renderChildCells:o,pinLast:s}){let c=(0,Q.useId)(),[l,d]=(0,Q.useState)(new Set),[f,p]=(0,Q.useState)({key:`sessions`,dir:`desc`}),m=(0,Q.useMemo)(()=>{let t=Sc(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=>xc(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-sm`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:n}),(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(yc,{label:t,sortKey:`label`,current:f.key,dir:f.dir,onSort:h,align:`left`}),(0,$.jsx)(yc,{label:`Sessions`,sortKey:`sessions`,current:f.key,dir:f.dir,onSort:h,align:`right`}),(0,$.jsx)(yc,{label:`Organic`,sortKey:`organicSessions`,current:f.key,dir:f.dir,onSort:h,align:`right`}),(0,$.jsx)(yc,{label:`Paid`,sortKey:`paidSessions`,current:f.key,dir:f.dir,onSort:h,align:`right`}),(0,$.jsx)(bc,{label:`Share`,align:`right`})]})}),(0,$.jsx)(`tbody`,{children:m.map((e,t)=>{let n=l.has(e.label),s=`${c}-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)(r,{"aria-hidden":`true`,className:`size-3.5 shrink-0 text-secondary`}):(0,$.jsx)(u,{"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-xs 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:W(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 rounded-md border border-subtle bg-bg/40 px-3 pb-1`,children:(0,$.jsxs)(`table`,{className:`w-full min-w-[32rem] text-[13px]`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`${e.label} sources`}),(0,$.jsx)(`thead`,{children:(0,$.jsx)(`tr`,{children:i.map(e=>(0,$.jsx)(bc,{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:o(e)},a(e)))})]})})})})]},e.label)})})]})})}function wc(e,t){return e===`other`?Fi.textDim:ki[t%ki.length]}function Tc({input:e,baseline:t,baselineLabel:n,label:r,height:i=224}){let{rows:a,series:o}=(0,Q.useMemo)(()=>fc(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)(P,{width:`100%`,height:`100%`,children:(0,$.jsxs)(z,{data:a,margin:{top:4,right:4,bottom:0,left:0},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`date`,tick:Ri,tickLine:!1,axisLine:{stroke:Ui},tickFormatter:ji,minTickGap:24}),(0,$.jsx)(L,{tick:Ri,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,$.jsx)(j,{...Hi,labelFormatter:Ii,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=wc(e.key,o.indexOf(e));return(0,$.jsx)(F,{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)(R,{type:`monotone`,dataKey:`baseline`,name:`baseline`,stroke:Fi.textFaint,strokeWidth:1.5,strokeDasharray:`5 4`,dot:!1,connectNulls:!1})]})})}),(0,$.jsxs)(`fieldset`,{className:`mt-2 flex flex-wrap gap-x-5 text-[13px] 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:wc(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:Fi.textFaint,strokeWidth:`2`,strokeDasharray:`5 3`})}),n]})]})]})}var Ec=[`sessions`,`activeUsers`,`organicSessions`,`engagementRate`,`keyEvents`],Dc=`canonry.siteTraffic.slots`,Oc=ki[1],kc={current:`current`,previous:`previous`};function Ac(e){return typeof e==`string`&&Et.some(t=>t===e)}function jc(){try{let e=JSON.parse(window.localStorage.getItem(Dc)??`null`);if(Array.isArray(e)&&e.length===Ec.length&&e.every(Ac))return[...e]}catch{}return[...Ec]}function Mc(e){try{window.localStorage.setItem(Dc,JSON.stringify(e))}catch{}}function Nc(){return typeof window<`u`&&typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}function Pc(e){return e===null?`no earlier data`:e===0?`no change on the previous period`:`${e>0?`up`:`down`} ${W(Math.abs(e),oe.percent)} on the previous period`}function Fc({metric:e,change:t}){let n=Ve(e,t);if(n===null||t===null)return(0,$.jsx)(`span`,{className:`block text-[13px] text-secondary`,children:`No earlier data`});let r=n===ln.better?`text-positive`:n===ln.worse?`text-negative`:`text-secondary`,i=t>0?c:t<0?p:null;return(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-0.5 text-[13px] font-medium tabular-nums ${r}`,children:[i&&(0,$.jsx)(i,{"aria-hidden":`true`,className:`size-3.5`,strokeWidth:2.5}),W(Math.abs(t),oe.percent)]})}function Ic({active:e,payload:t,metric:n}){let r=t?.[0]?.payload;return!e||!r?null:(0,$.jsxs)(`div`,{className:`min-w-48 rounded-md border border-default bg-bg-elevated px-3 py-2 text-[13px] shadow-lg`,children:[(0,$.jsx)(`p`,{className:`mb-1 font-medium text-heading`,children:Lt[n].label}),(0,$.jsxs)(`p`,{className:`flex items-center justify-between gap-6`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-secondary`,children:[(0,$.jsx)(`svg`,{"aria-hidden":`true`,width:`14`,height:`6`,className:`shrink-0`,children:(0,$.jsx)(`line`,{x1:`0`,y1:`3`,x2:`14`,y2:`3`,stroke:Oc,strokeWidth:`2.5`})}),Ii(r.date)]}),(0,$.jsx)(`span`,{className:`tabular-nums text-primary`,children:sn(n,r.current)})]}),(0,$.jsxs)(`p`,{className:`flex items-center justify-between gap-6`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-2 text-secondary`,children:[(0,$.jsx)(`svg`,{"aria-hidden":`true`,width:`14`,height:`6`,className:`shrink-0`,children:(0,$.jsx)(`line`,{x1:`0`,y1:`3`,x2:`14`,y2:`3`,stroke:Oc,strokeWidth:`1.5`,strokeDasharray:`3 2`})}),Ii(r.previousDate)]}),(0,$.jsx)(`span`,{className:`tabular-nums text-secondary`,children:sn(n,r.previous)})]})]})}function Lc({overview:e,refreshing:t=!1}){let n=(0,Q.useId)(),[i,a]=(0,Q.useState)(jc),[o,s]=(0,Q.useState)(0),[c,l]=(0,Q.useState)(new Set),u=!Nc(),d=i[o]??Ec[0],f=(0,Q.useMemo)(()=>e.days.map(e=>({date:e.date,previousDate:e.previousDate,current:e.values[d],previous:e.previousValues[d]})),[e.days,d]),p=f.some(e=>e.current!==null||e.previous!==null),m=Ue(e.window)?St[e.window]:null,h=m===null?`This period`:`Last ${m} days`,g=(e,t)=>a(n=>{let r=[...n],i=r.indexOf(t);return i!==-1&&i!==e&&(r[i]=r[e]),r[e]=t,Mc(r),r}),_=e=>{s(e),document.getElementById(`${n}-tab-${e}`)?.focus()},v=(e,t)=>{let n=i.length-1,r=e.key===`ArrowRight`?t===n?0:t+1:e.key===`ArrowLeft`?t===0?n:t-1:e.key===`Home`?0:e.key===`End`?n:null;r!==null&&(e.preventDefault(),_(r))},y=e=>l(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n});return(0,$.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-default transition-opacity duration-200 ${t?`opacity-60`:``}`,children:[(0,$.jsx)(`div`,{role:`tablist`,"aria-label":`Site traffic figures`,className:`grid grid-cols-2 border-b border-default sm:grid-cols-3 lg:grid-cols-5`,children:i.map((t,i)=>{let a=i===o,c=sn(t,e.totals[t],{compact:!0});return(0,$.jsxs)(`div`,{className:`relative min-w-0 px-4 pb-4 pt-4`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-x-4 top-0 h-[3px] rounded-b-sm bg-link transition-opacity duration-200 ${a?`opacity-100`:`opacity-0`}`}),(0,$.jsxs)(`div`,{className:`relative inline-flex max-w-full items-center`,children:[(0,$.jsx)(`select`,{"aria-label":`Figure ${i+1}`,value:t,onChange:e=>{Ac(e.target.value)&&g(i,e.target.value)},className:`max-w-full cursor-pointer appearance-none truncate rounded-sm bg-transparent py-0.5 pr-5 text-sm font-medium [field-sizing:content] transition-colors duration-150 hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${a?`text-link`:`text-secondary`}`,children:Et.map(e=>(0,$.jsx)(`option`,{value:e,children:Lt[e].label},e))}),(0,$.jsx)(r,{"aria-hidden":`true`,className:`pointer-events-none absolute right-0 size-3.5 ${a?`text-link`:`text-muted`}`})]}),(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`${n}-tab-${i}`,"aria-selected":a,"aria-controls":`${n}-panel`,"aria-label":`${Lt[t].label} ${c}, ${Pc(e.changePct[t])}`,tabIndex:a?0:-1,onClick:()=>s(i),onKeyDown:e=>v(e,i),className:`mt-1 block w-full rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[(0,$.jsx)(`span`,{className:`block truncate text-[26px] font-semibold leading-tight tabular-nums transition-colors duration-150 ${a?`text-primary`:`text-strong`}`,title:sn(t,e.totals[t]),children:c}),(0,$.jsx)(Fc,{metric:t,change:e.changePct[t]})]})]},i)})}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`${n}-panel`,"aria-labelledby":`${n}-tab-${o}`,className:`px-4 pb-3 pt-4`,children:[e.syncedAt===null&&(0,$.jsx)(`p`,{className:`mb-3 text-sm text-secondary`,children:`These figures fill in after the next GA4 sync.`}),p?(0,$.jsx)(`div`,{role:`img`,"aria-label":`${Lt[d].label} per day, ${h.toLowerCase()} and the previous period`,style:{height:240},children:(0,$.jsx)(P,{width:`100%`,height:`100%`,children:(0,$.jsxs)(z,{data:f,margin:{top:8,right:0,bottom:0,left:4},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`date`,tick:Ri,tickLine:!1,axisLine:{stroke:Ui},tickFormatter:ji,minTickGap:32}),(0,$.jsx)(L,{orientation:`right`,tick:Ri,tickLine:!1,axisLine:!1,width:52,allowDecimals:Lt[d].unit!==dt.count,tickFormatter:e=>sn(d,e,{compact:!0})}),(0,$.jsx)(j,{cursor:{stroke:Fi.textFaint,strokeWidth:1},wrapperStyle:{outline:`none`},content:(0,$.jsx)(Ic,{metric:d})}),!c.has(kc.previous)&&(0,$.jsx)(R,{type:`monotone`,dataKey:kc.previous,stroke:Oc,strokeOpacity:.65,strokeWidth:1.5,strokeDasharray:`4 4`,dot:!1,activeDot:{r:3,strokeWidth:0,fill:Oc},connectNulls:!1,isAnimationActive:u,animationDuration:320,animationEasing:`ease-out`}),!c.has(kc.current)&&(0,$.jsx)(R,{type:`monotone`,dataKey:kc.current,stroke:Oc,strokeWidth:2.25,dot:!1,activeDot:{r:5,strokeWidth:2,stroke:Oc,fill:`var(--color-bg)`},connectNulls:!1,isAnimationActive:u,animationDuration:320,animationEasing:`ease-out`})]})})}):(0,$.jsxs)(`p`,{className:`py-8 text-sm text-secondary`,children:[`No daily `,Lt[d].label.toLowerCase(),` yet.`]}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center justify-between gap-x-6 gap-y-1`,children:[(0,$.jsxs)(`fieldset`,{className:`flex flex-wrap gap-x-5 text-[13px] text-secondary`,children:[(0,$.jsx)(`legend`,{className:`sr-only`,children:`${Lt[d].label} series`}),[[kc.current,h,``],[kc.previous,`Previous period`,`4 3`]].map(([e,t,n])=>{let r=!c.has(e),i=r&&c.size===1;return(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:r,disabled:i,onChange:()=>y(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:Oc,strokeWidth:e===kc.current?2.5:1.5,strokeDasharray:n||void 0})}),t]},e)})]}),e.current.startDate&&e.current.endDate&&e.previous.startDate&&e.previous.endDate&&(0,$.jsxs)(`p`,{className:`text-[13px] text-secondary`,children:[Rc(e.current.startDate,e.current.endDate,!0),` vs `,Rc(e.previous.startDate,e.previous.endDate,!1)]})]})]})]})}function Rc(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)}`}var zc=ki[0],Bc=ki[1],Vc=ki[2],Hc=ki[3],Uc=[`both`,`server`,`ga4`],Wc={fontSize:12,paddingTop:6},Gc=e=>typeof e==`number`?Kt(Math.round(e)):String(e),Kc=e=>typeof e==`number`&&Number.isFinite(e)?e:0;function qc(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 Jc(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 Yc({projectName:e,sinceMinutes:t}){let[n,r]=(0,Q.useState)(!0),[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(`both`),c=Qo(e,{sinceMinutes:t,granularity:`day`,limit:1}),l=Yo(e),u=C({...cr({client:q,path:{name:e}}),enabled:!!e,staleTime:Fn}).data?.connected===!0,d=C({...gi({client:q,path:{name:e},query:{window:t>=129600?`90d`:t>=43200?`30d`:`7d`}}),enabled:!!e&&u,staleTime:Fn}),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=qc(g?.crawlerContentHits,f.length),t=qc(g?.aiUserFetchHits,f.length),n=qc(g?.aiReferralLandedHits,f.length);return f.map((r,i)=>({...r,crawlerContentHits:r.measured===!1?null:Kc(r.crawlerContentHits),aiUserFetchHits:r.measured===!1?null:Kc(r.aiUserFetchHits),aiReferralLandedHits:r.measured===!1?null:Kc(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:Kc(v.crawlerContentHits),fetches:Kc(v.aiUserFetchHits),visits:Kc(v.aiReferralLandedHits)},b=(0,Q.useMemo)(()=>f.reduce((e,t)=>({crawlers:e.crawlers+Kc(t.crawlerContentHits),fetches:e.fetches+Kc(t.aiUserFetchHits),visits:e.visits+Kc(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-sm 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-sm 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-sm 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)(vc,{label:`AI traffic totals`,items:[{label:`AI crawlers`,value:Kt(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:Kt(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:Kt(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-xs text-muted`,children:[(0,$.jsx)(`span`,{className:`text-secondary font-semibold`,children:`Latest day (UTC)`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading font-semibold tabular-nums mr-1`,children:Kc(f[f.length-1].crawlerContentHits).toLocaleString()}),`pages crawled`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading font-semibold tabular-nums mr-1`,children:Kc(f[f.length-1].aiUserFetchHits).toLocaleString()}),`page fetches`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading font-semibold tabular-nums mr-1`,children:Kc(f[f.length-1].aiReferralLandedHits).toLocaleString()}),`visits, server`]}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`span`,{className:`text-heading font-semibold 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-sm font-semibold 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-xs 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-xs 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)(P,{width:`100%`,height:206,children:(0,$.jsxs)(z,{data:_,margin:{top:4,right:8,left:-18,bottom:0},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`bucket`,tick:Ri,stroke:Ui,tickFormatter:ji,minTickGap:28}),(0,$.jsx)(L,{tick:Ri,stroke:Ui,width:48,allowDecimals:!1}),(0,$.jsx)(j,{contentStyle:Hi.contentStyle,labelStyle:Hi.labelStyle,itemStyle:Hi.itemStyle,labelFormatter:Ii,formatter:Gc}),m&&(0,$.jsx)(N,{x1:m.from,x2:m.to,fill:`var(--color-overlay-hover)`,fillOpacity:.5,stroke:`none`,label:{value:`not measured`,position:`insideTop`,fontSize:10,fill:`var(--chart-neutral-text-dim, #71717a)`}}),(0,$.jsx)(I,{wrapperStyle:Wc,iconType:`plainline`,iconSize:14}),(0,$.jsx)(F,{type:`monotone`,dataKey:`crawlerContentHits`,name:`Pages crawled`,stroke:zc,fill:zc,fillOpacity:.22,strokeWidth:1.8}),n&&(0,$.jsx)(F,{type:`monotone`,dataKey:`aiUserFetchHits`,name:`Page fetches`,stroke:Bc,fill:Bc,fillOpacity:.18,strokeWidth:1.6}),i&&(0,$.jsx)(R,{type:`linear`,dataKey:`crawlTrend`,legendType:`none`,name:`Pages crawled trend`,dot:!1,tooltipType:`none`,stroke:zc,strokeWidth:1.4,strokeDasharray:`5 4`,connectNulls:!0}),i&&n&&(0,$.jsx)(R,{type:`linear`,dataKey:`fetchTrend`,legendType:`none`,name:`Page fetches trend`,dot:!1,tooltipType:`none`,stroke:Bc,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-sm font-semibold 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)(uc,{windows:Uc,value:o,onChange:s,label:`Visit measurement source`,formatOption:e=>e===`ga4`?`GA4`:e===`both`?`Both`:`Server`})]}),(0,$.jsx)(P,{width:`100%`,height:176,children:(0,$.jsxs)(z,{data:_,margin:{top:4,right:8,left:-18,bottom:0},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`bucket`,tick:Ri,stroke:Ui,tickFormatter:ji,minTickGap:28}),(0,$.jsx)(L,{tick:Ri,stroke:Ui,width:48,allowDecimals:!1}),(0,$.jsx)(j,{contentStyle:Hi.contentStyle,labelStyle:Hi.labelStyle,itemStyle:Hi.itemStyle,labelFormatter:Ii,formatter:Gc}),m&&(0,$.jsx)(N,{x1:m.from,x2:m.to,fill:`var(--color-overlay-hover)`,fillOpacity:.5,stroke:`none`,label:{value:`not measured`,position:`insideTop`,fontSize:10,fill:`var(--chart-neutral-text-dim, #71717a)`}}),(0,$.jsx)(I,{wrapperStyle:Wc,iconType:`plainline`,iconSize:14}),o!==`ga4`&&(0,$.jsx)(R,{type:`monotone`,dataKey:`aiReferralLandedHits`,name:`Visits, server`,stroke:Vc,strokeWidth:2,dot:!1}),o!==`server`&&(0,$.jsx)(R,{type:`monotone`,dataKey:`ga4Visits`,name:`Visits, GA4`,connectNulls:!1,stroke:Hc,strokeWidth:1.8,strokeDasharray:`5 3`,dot:Jc(_.map(e=>e.ga4Visits),Hc)}),i&&o!==`ga4`&&(0,$.jsx)(R,{type:`linear`,dataKey:`visitTrend`,legendType:`none`,name:`Visits trend`,dot:!1,tooltipType:`none`,stroke:Vc,strokeWidth:1.3,strokeDasharray:`5 4`,connectNulls:!0})]})})]})}function Xc(e){return e.replace(/\+/g,` `)}var Zc=[`7d`,`30d`,`90d`],Qc={"7d":10080,"30d":43200,"90d":129600,all:129600};function $c(e){return Po(e.landingPage)}var el=25,tl=10,nl={days:[],sources:[],totalSessions:0,totalPaidSessions:0,totalOrganicSessions:0,byEngine:{series:[],otherCount:0,days:[]}},rl={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 il(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 al(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function ol(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 sl({projectName:e}){let{data:t,isLoading:n,isError:r}=es(e),i=t?.sources??[];return(0,$.jsxs)(`section`,{"aria-labelledby":`server-activity-heading`,children:[(0,$.jsx)(mc,{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:!U()&&i.length>0?(0,$.jsx)(O,{to:`/traffic`,className:`text-sm text-link hover:underline`,children:`Manage sources`}):void 0}),n?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`Loading server activity…`}):r?(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-negative`,children:`Could not load server activity.`}):i.length===0?(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[`No traffic source connected.`,` `,!U()&&(0,$.jsx)(O,{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-sm`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(bc,{label:`Source`,align:`left`}),(0,$.jsx)(bc,{label:`Status`,align:`left`}),(0,$.jsx)(bc,{label:`Crawler hits`,align:`right`}),(0,$.jsx)(bc,{label:`AI hits`,align:`right`}),(0,$.jsx)(bc,{label:`AI sessions`,align:`right`}),(0,$.jsx)(bc,{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)(Y,{tone:Zo(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:t.totals24h.aiUserFetchHits.toLocaleString(`en-US`)}),(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?il(t.lastSyncedAt):`never`}),(0,$.jsx)(`td`,{className:`py-2 pl-3 text-right`,children:!U()&&(0,$.jsx)(O,{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 cl({projectName:e}){let[t,n]=(0,Q.useState)(`30d`);return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(sl,{projectName:e}),(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsx)(_l,{projectName:e,window:t,periodControl:(0,$.jsx)(uc,{windows:Zc,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)(mc,{id:`ai-traffic-history-heading`,title:`AI traffic history`,tooltip:rl.aiHistoryTooltip}),(0,$.jsx)(Yc,{projectName:e,sinceMinutes:Qc[t]})]})]})})]})}var ll={session:`Session`,first_user:`First visit`,manual_utm:`UTM`},ul={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)`},dl=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Class`,align:`left`},{label:`Attribution`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}],fl=[{label:`Source`,align:`left`},{label:`Medium`,align:`left`},{label:`Channel`,align:`left`},{label:`Sessions`,align:`right`},{label:`Share`,align:`right`}];function pl(e){return e.engine===null}function ml({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:ul[e.sourceDimension]??``,children:ll[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:W(e.share)})]})}function hl({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:Xc(e.source)}),(0,$.jsx)(`td`,{className:`max-w-[160px] truncate py-1.5 pr-3 text-secondary`,title:e.medium,children:Xc(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:W(e.share)})]})}function gl(e,t){let n=x(),[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)(nl),[y,b]=(0,Q.useState)([]),[S,C]=(0,Q.useState)(null);async function w(r){c(!0),m(null);try{let a=await n.fetchQuery({...cr({client:q,path:{name:e}}),staleTime:Fn});if(r.current)return;if(i(a),!a.connected){o(null),v(nl),b([]),C(null),c(!1);return}let s=t===`all`?void 0:t,[l,u,d,f]=await Promise.all([n.fetchQuery({...Hn({client:q,path:{name:e},query:s?{window:s}:void 0}),staleTime:Fn}),n.fetchQuery({...gi({client:q,path:{name:e},query:s?{window:s}:void 0}),staleTime:Fn}).catch(()=>nl),n.fetchQuery({...xi({client:q,path:{name:e},query:s?{window:s}:void 0}),staleTime:Fn}).catch(()=>[]),n.fetchQuery({...wi({client:q,path:{name:e},query:{window:Ue(t)?t:`30d`}}),staleTime:Fn}).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 Ht(e);g(`Synced ${t.rowCount.toLocaleString()} page rows, ${t.aiReferralCount.toLocaleString()} AI and ${t.socialReferralCount.toLocaleString()} social referral rows (${t.days} days)`),await Mn(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 jt(e),await Mn(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 Mn(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:S,handleSync:T,handleDisconnect:E,handleConnected:D}}function _l({projectName:e,window:t,periodControl:n,between:r}){let i=gl(e,t??`30d`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(vl,{ga:i,projectName:e,periodControl:n}),r,(0,$.jsx)(yl,{ga:i,projectName:e})]})}function vl({ga:e,projectName:t,periodControl:n}){let{status:r,traffic:i,syncing:a,disconnecting:o,handleSync:s,handleDisconnect:c}=e,l=r?.connected===!0,u=l&&!U()&&!an(),f=i?ol(i.windowStart,i.windowEnd):null,p;return p=e.loading&&!r?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`Loading traffic data…`}):l?i&&e.overview?(0,$.jsx)(Lc,{overview:e.overview,refreshing:e.loading}):i?(0,$.jsx)($.Fragment,{children:(0,$.jsx)(vc,{label:`Site traffic`,items:[{label:`Total sessions`,value:al(i.totalSessions),detail:i.totalSessions.toLocaleString()},{label:`Organic sessions`,value:al(i.totalOrganicSessions),detail:`${i.organicSharePctDisplay} of total`},{label:`Total users`,value:i.totalUsers===null?`n/a`:al(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-sm text-secondary`,children:`No traffic data yet.`}),!U()&&!an()&&(0,$.jsxs)(J,{variant:`outline`,size:`sm`,disabled:a,onClick:kn(s),children:[(0,$.jsx)(v,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),`Sync from GA4`]})]}):U()||an()?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No Google Analytics 4 property connected.`}):(0,$.jsx)(Ol,{projectName:t,onConnected:()=>{e.handleConnected()}}),(0,$.jsxs)(`section`,{"aria-labelledby":`site-traffic-heading`,children:[(0,$.jsx)(mc,{id:`site-traffic-heading`,title:`Site traffic`,tooltip:e.overview?rl.siteTrafficTooltip:f?`${rl.siteTrafficFallbackTooltip} Data covers ${f}.`:rl.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||u?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n,u&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(J,{variant:`outline`,size:`sm`,disabled:a,onClick:kn(s),children:[(0,$.jsx)(v,{className:`mr-1.5 size-3.5 ${a?`animate-spin`:``}`}),a?`Syncing…`:`Sync`]}),(0,$.jsxs)(J,{variant:`ghost`,size:`sm`,className:`text-negative-400 hover:text-negative`,disabled:o,onClick:kn(c),children:[(0,$.jsx)(d,{className:`mr-1.5 size-3.5`}),`Disconnect`]})]})]}):void 0}),e.error&&(0,$.jsx)(`div`,{role:`alert`,className:`mb-4 rounded-lg border border-negative-800/60 bg-negative-900/20 px-4 py-2 text-sm text-negative`,children:e.error}),e.notice&&(0,$.jsx)(`div`,{role:`status`,className:`mb-4 rounded-lg border border-positive-800/60 bg-positive-900/20 px-4 py-2 text-sm text-positive`,children:e.notice}),p]})}function yl({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=Io({rows:l,getSearchText:e=>Po(e.landingPage),pageSize:tl}),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=Io({rows:d,getSearchText:$c,pageSize:el}),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?ol(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)(mc,{id:`traffic-by-channel-heading`,title:`Traffic by channel`,tooltip:rl.channelTooltip,meta:g}),(0,$.jsx)(vc,{label:`Sessions by channel`,items:[{label:`Organic search`,value:_.organic.sharePctDisplay,detail:`${_.organic.sessions.toLocaleString()} sessions`,tooltip:rl.organicTooltip},{label:`Social`,value:_.social.sharePctDisplay,detail:`${_.social.sessions.toLocaleString()} sessions`,tooltip:rl.socialTooltip},{label:`Direct`,value:_.direct.sharePctDisplay,detail:`${_.direct.sessions.toLocaleString()} sessions`,tooltip:rl.directTooltip},{label:`AI (at least)`,value:_.ai.sharePctDisplay,detail:v>0?`${_.ai.sessions.toLocaleString()} sessions · ${v.toLocaleString()} paid`:`${_.ai.sessions.toLocaleString()} sessions`,tooltip:rl.aiTooltip},{label:`Other channels`,value:_.other.sharePctDisplay,detail:`${_.other.sessions.toLocaleString()} sessions`,tooltip:rl.otherTooltip}]}),(0,$.jsxs)(hc,{children:[(0,$.jsx)(gc,{label:rl.aiChartLabel,meta:r.days.length>0?bl(r.totalSessions,`session`):rl.noneInPeriod,children:r.days.length>0?(0,$.jsx)(Tc,{input:r.byEngine,baseline:p,baselineLabel:`Total sessions`,label:rl.aiChartLabel}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:rl.noAiReferrals})}),(0,$.jsx)(gc,{label:`Where AI visitors came from`,meta:y.length>0?`${bl(y.filter(e=>e.engine!==null).length,`engine`)} · ${bl(n.aiReferrals.length,`source`)}`:rl.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)(Cc,{groups:y,groupLabel:`Engine`,caption:`AI referral sessions by engine`,childColumns:dl,childRowKey:e=>`${e.source}:${e.medium}:${e.sourceDimension}:${e.trafficClass}`,renderChildCells:e=>(0,$.jsx)(ml,{row:e}),pinLast:pl})}),(0,$.jsx)(X,{text:rl.aiEnginesTooltip})]}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:rl.noAiReferrals})}),(0,$.jsx)(gc,{label:`Pages AI visitors landed on`,meta:S??rl.noneInPeriod,children:n.aiReferralLandingPages.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(No,{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-sm`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(yc,{label:`Landing page`,sortKey:`landingPage`,current:s.key,dir:s.dir,onSort:h,align:`left`}),(0,$.jsx)(yc,{label:`Source`,sortKey:`source`,current:s.key,dir:s.dir,onSort:h,align:`left`}),(0,$.jsx)(bc,{label:`Attribution`,align:`left`}),(0,$.jsx)(yc,{label:`Sessions`,sortKey:`sessions`,current:s.key,dir:s.dir,onSort:h,align:`right`})]})}),(0,$.jsx)(`tbody`,{children:f.rows.map(e=>(0,$.jsx)(Al,{row:e},`${e.landingPage}:${e.source}:${e.medium}:${e.sourceDimension}`))})]})}),(0,$.jsx)(Fo,{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-sm text-secondary`,children:`No landing pages match this filter`}),(0,$.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>f.setQuery(``),children:`Clear filter`})]})]}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:rl.noAiLandingPages})})]})]}),(0,$.jsx)(`div`,{className:`page-section-divider`}),(0,$.jsxs)(`section`,{"aria-labelledby":`social-heading`,children:[(0,$.jsx)(mc,{id:`social-heading`,title:`Social`,tooltip:rl.socialTooltip2,meta:g}),(0,$.jsx)(vc,{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:rl.platformsTooltip},{label:`Paid social`,value:(n.paidSocialSessions??0).toLocaleString(),detail:`${W(n.paidSocialShare??0)} of social`,tooltip:rl.paidSocialTooltip},{label:`Top platform`,value:x?.label??`None`,detail:x?`${x.sessions.toLocaleString()} sessions`:void 0}]}),(0,$.jsxs)(hc,{children:[(0,$.jsx)(gc,{label:rl.socialChartLabel,meta:b.length>0?bl(n.socialSessions,`session`):rl.noneInPeriod,children:b.length>0?(0,$.jsx)(Tc,{input:n.socialPlatformDaily,label:rl.socialChartLabel}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:rl.noSocial})}),(0,$.jsx)(gc,{label:`Social platforms`,meta:b.length>0?`${bl(b.length,`platform`)} · ${bl(n.socialReferrals.length,`source`)}`:rl.noneInPeriod,children:b.length>0?(0,$.jsx)(Cc,{groups:b,groupLabel:`Platform`,caption:`Social sessions by platform`,childColumns:fl,childRowKey:e=>`${e.source}:${e.medium}:${e.channelGroup}`,renderChildCells:e=>(0,$.jsx)(hl,{row:e})}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:rl.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)(mc,{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)(No,{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-sm`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(yc,{label:`Landing page`,sortKey:`landingPage`,current:a.key,dir:a.dir,onSort:m,align:`left`}),(0,$.jsx)(yc,{label:`Sessions`,sortKey:`sessions`,current:a.key,dir:a.dir,onSort:m,align:`right`}),(0,$.jsx)(yc,{label:`Organic`,sortKey:`organicSessions`,current:a.key,dir:a.dir,onSort:m,align:`right`}),(0,$.jsx)(bc,{label:`Organic share`,align:`right`})]})}),(0,$.jsx)(`tbody`,{children:u.rows.map(e=>(0,$.jsx)(kl,{page:e},e.landingPage))})]})}),u.totalRows===0&&u.hasQuery&&(0,$.jsx)(`p`,{className:`mt-3 text-sm text-secondary`,children:`No landing pages match this filter`}),(0,$.jsx)(Fo,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,onPageChange:u.setPage,itemLabel:u.hasQuery?`matches`:`pages`})]})]}),(0,$.jsx)(Dl,{projectName:t}),(0,$.jsx)(`p`,{className:`mt-6 text-xs text-secondary`,children:n?.lastSyncedAt?`Last synced ${il(n.lastSyncedAt)}`:`Never synced`})]})}function bl(e,t){return`${e.toLocaleString()} ${e===1?t:`${t}s`}`}var xl=25,Sl=`n/a`,Cl={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 wl(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 Tl(e){return e===null?Sl:e.toFixed(1)}function El(e){return e===null?Sl:W(e)}function Dl({projectName:e}){let[t,n]=(0,Q.useState)(`28d`),[r,i]=(0,Q.useState)(`clicks`),[a,o]=(0,Q.useState)(`desc`),s=C({...Cr({client:q,path:{name:e},query:{window:t,limit:it}}),staleTime:Fn}),c=s.data,l=(0,Q.useMemo)(()=>[...c?.rows??[]].sort((e,t)=>{let n=wl(e,r),i=wl(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=Io({rows:l,getSearchText:e=>Po(rn(e.landingPage)),pageSize:xl});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=!U()&&!an();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-base font-semibold text-primary`,children:Cl.heading}),(0,$.jsx)(X,{text:Cl.tooltip})]}),c?.windowStart&&c.windowEnd&&(0,$.jsxs)(`p`,{className:`text-sm text-secondary mt-1`,children:[me(c.windowStart),` to `,me(c.windowEnd),c.timeZone?` (${c.timeZone})`:``]})]}),(0,$.jsx)(uc,{windows:nn,value:t,onChange:e=>{u.setPage(1),n(e)},label:Cl.windowLabel})]}),s.isPending?(0,$.jsx)(`p`,{className:`text-sm text-secondary py-6 text-center`,children:Cl.loading}):s.isError||!c?(0,$.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative`,children:[(0,$.jsx)(`span`,{children:Cl.loadError}),(0,$.jsx)(J,{variant:`outline`,size:`sm`,onClick:()=>{s.refetch()},children:Cl.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)(Y,{tone:`caution`,children:Cl.notLinkedBadge}),(0,$.jsx)(X,{text:Cl.notLinked(c.searchConsoleLink?.searchConsoleImpressions??0)})]}),c.status===`error`&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsx)(Y,{tone:`negative`,children:Cl.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)(Y,{tone:`caution`,children:Cl.unavailableBadge}),c.error&&(0,$.jsx)(X,{text:c.error})]}),c.subjectToThresholding&&(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-1`,children:[(0,$.jsx)(Y,{tone:`caution`,children:Cl.thresholdedBadge}),(0,$.jsx)(X,{text:Cl.thresholded})]}),c.status!==`ready`&&f&&c.syncedAt&&(0,$.jsxs)(`span`,{className:`text-sm text-secondary`,children:[Cl.previousSnapshot,` `,il(c.syncedAt),`.`]}),c.status===`unavailable`&&f&&(0,$.jsx)(`p`,{className:`w-full text-sm text-secondary`,children:Cl.unavailableAction})]}),f?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(No,{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-sm`,"aria-labelledby":`ga-search-landing-heading`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-default`,children:[(0,$.jsx)(yc,{label:`Landing page`,sortKey:`landingPage`,current:r,dir:a,onSort:d,align:`left`}),(0,$.jsx)(yc,{label:`Clicks`,sortKey:`clicks`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(yc,{label:`Impressions`,sortKey:`impressions`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(yc,{label:`CTR`,sortKey:`ctr`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(yc,{label:`Avg. position`,sortKey:`position`,current:r,dir:a,onSort:d,align:`right`}),(0,$.jsx)(yc,{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 font-semibold`,"data-testid":`ga-search-landing-total`,children:[(0,$.jsxs)(`td`,{className:`py-1.5 text-primary`,children:[Cl.totalLabel,` `,(0,$.jsx)(`span`,{className:`font-normal text-secondary`,children:Cl.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:El(f.organicGoogleSearchClickThroughRate)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:Tl(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:rn(e.landingPage),children:rn(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:El(e.organicGoogleSearchClickThroughRate)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:Tl(e.organicGoogleSearchAveragePosition)}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-secondary tabular-nums`,children:e.activeUsers.toLocaleString()})]},e.landingPage))]})]})}),!ie(f)&&!p&&(0,$.jsxs)(`div`,{className:`text-sm text-secondary mt-3 space-y-1`,children:[(0,$.jsx)(`p`,{children:Cl.noSearchTraffic}),(0,$.jsx)(`p`,{children:c.searchConsoleLink?.state===`no-search-data`?Cl.noSearchTrafficConfirmed:Cl.noSearchTrafficAction})]}),u.totalRows===0&&u.hasQuery&&(0,$.jsx)(`p`,{className:`text-sm text-secondary mt-3`,children:c.totalRows>c.rows.length?Cl.noFilterMatchInLoaded(c.rows.length):Cl.noFilterMatch}),(0,$.jsx)(Fo,{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-sm 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-xs text-muted`,children:[`Synced `,il(c.syncedAt)]})]}):(0,$.jsx)(Z,{className:`p-5`,children:c.status===`unavailable`?(0,$.jsxs)(`div`,{className:`text-sm text-secondary space-y-1`,children:[(0,$.jsx)(`p`,{className:`text-neutral`,children:Cl.unavailable}),(0,$.jsx)(`p`,{children:Cl.unavailableAction})]}):c.status===`error`?(0,$.jsxs)(`div`,{className:`text-sm text-secondary space-y-1`,children:[(0,$.jsx)(`p`,{className:`text-neutral`,children:Cl.refreshFailed}),c.error&&(0,$.jsx)(`p`,{children:c.error})]}):(0,$.jsxs)(`div`,{className:`text-sm text-secondary space-y-1`,children:[(0,$.jsx)(`p`,{className:`text-neutral`,children:Cl.neverSynced}),m&&(0,$.jsx)(`p`,{children:Cl.neverSyncedAction})]})})]})]})]})}function Ol({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 lt(e,{propertyId:n.trim(),keyJson:o});try{await Ht(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-base font-semibold text-primary mb-1`,children:`Connect Google Analytics 4`}),(0,$.jsx)(`p`,{className:`text-sm text-secondary mb-5`,children:`Connect a GA4 property to see traffic data for this project. You'll need a service account key file from Google Cloud Console.`}),u&&(0,$.jsx)(`div`,{className:`mb-4 px-4 py-2 rounded-lg bg-negative-900/20 border border-negative-800/60 text-sm text-negative`,children:u}),(0,$.jsxs)(`div`,{className:`mb-4`,children:[(0,$.jsx)(`label`,{htmlFor:`ga4-property-id`,className:`block text-xs font-medium 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-lg bg-bg-elevated/60 border border-default px-3 py-2 text-sm text-strong placeholder-mono-600 focus:outline-none focus:ring-1 focus:ring-mono-600`}),(0,$.jsx)(`p`,{className:`mt-1 text-[11px] text-muted`,children:`Find this in GA4 → Admin → Property Settings. It's a numeric ID, not the Measurement ID (G-XXXXXX).`})]}),(0,$.jsxs)(`div`,{className:`mb-5`,children:[(0,$.jsx)(`label`,{className:`block text-xs font-medium 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-lg bg-bg-elevated/60 border border-default border-dashed px-4 py-3 text-sm text-secondary hover:border-mono-600 hover:text-neutral transition-colors cursor-pointer`,children:[(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-[11px] 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)(J,{variant:`default`,size:`sm`,disabled:c||!n.trim()||!o,onClick:kn(h),children:c?`Connecting & syncing…`:`Connect GA4`})]})}function kl({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:W(e.organicShare)})]})}function Al({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)(Mo,{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:ul[e.sourceDimension]??``,children:ll[e.sourceDimension]??e.sourceDimension}),(0,$.jsx)(`td`,{className:`py-1.5 pl-4 text-right text-primary tabular-nums`,children:e.sessions.toLocaleString()})]})}function jl(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 Ml=`Search Console is not connected yet. Your Canonry team can set this up.`,Nl=[`7d`,`30d`,`90d`,`all`],Pl=500,Fl=[{key:`clicks`,label:`Clicks`,color:ki[1],format:e=>e.toLocaleString()},{key:`impressions`,label:`Impressions`,color:ki[4],format:e=>e.toLocaleString()},{key:`ctr`,label:`CTR`,color:zi.caution,format:e=>W(e)},{key:`position`,label:`Avg position`,color:ki[2],inverted:!0,format:e=>e.toFixed(1)}],Il=25,Ll=`canonry:google-oauth-complete`;function Rl(e,t,n){if(!e)return`no comparison period`;let r=e.days;if(!e.comparable)return`property-level comparison unavailable`;let i=e.change[t];if(i===null||!Number.isFinite(i)){let n=e.prior[t],i=e.trailing[t];return n!==null&&i!==null&&n<=0&&i>0?`new in the last ${r}d`:n===null||n<=0?`no prior ${r}d to compare`:i===null?`no value in the last ${r}d`:`comparison unavailable`}return i===0?`→ no change vs prior ${r}d`:`${(n?i<0:i>0)?`↑`:`↓`} ${W(Math.abs(i))} vs prior ${r}d`}function zl(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 Bl(e){return e.contents?.reduce((e,t)=>e+Number(t.submitted||0),0)??0}function Vl(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 Hl(e){return e.isPending?`Processing`:Number(e.errors??0)>0?`Errors`:Number(e.warnings??0)>0?`Warnings`:`Success`}function Ul({projectName:e,refreshNonce:t}){let n=x(),{isAdmin:r}=On(),i=an(),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)([]),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(``),[E,D]=(0,Q.useState)(`30`),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(`30d`),[N,P]=(0,Q.useState)([`clicks`,`impressions`]),[F,I]=(0,Q.useState)(!0),[L,R]=(0,Q.useState)(null),[z,ee]=(0,Q.useState)(0),[B,V]=(0,Q.useState)({startDate:``,endDate:``,query:``,page:``}),[te,re]=(0,Q.useState)(0),[ie,U]=(0,Q.useState)(!1),[ae,oe]=(0,Q.useState)(0),[se,ce]=(0,Q.useState)(!1),[le,ue]=(0,Q.useState)(``),[de,fe]=(0,Q.useState)(!0),[pe,me]=(0,Q.useState)(!1),[he,ge]=(0,Q.useState)(!1),[_e,ye]=(0,Q.useState)(!1),[be,xe]=(0,Q.useState)(!1),[Se,Ce]=(0,Q.useState)(!1),[we,Te]=(0,Q.useState)(!1),[G,Ee]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)(!1),[Ae,je]=(0,Q.useState)(!1),[Me,Ne]=(0,Q.useState)(null),[Pe,Fe]=(0,Q.useState)(null),[Ie,Le]=(0,Q.useState)([]),[Re,ze]=(0,Q.useState)(new Set),[Be,Ve]=(0,Q.useState)({}),[He,Ue]=(0,Q.useState)(new Set),[We,K]=(0,Q.useState)(``),[Ke,qe]=(0,Q.useState)(null),[Je,Ye]=(0,Q.useState)(``),[Xe,Ze]=(0,Q.useState)(!1),[Qe,$e]=(0,Q.useState)(!1),[et,tt]=(0,Q.useState)(!1),[nt,rt]=(0,Q.useState)(!1),[it,at]=(0,Q.useState)(`indexed`),[ot,st]=(0,Q.useState)(null),ct=!!(B.query.trim()||B.page.trim()||ot),lt=ot!==null,ut=(0,Q.useMemo)(()=>{if(!ot)return d;let{key:e,dir:t}=ot;return[...d].sort((n,r)=>{let i=e===Cn.CTR?Number.isFinite(n.ctr)?n.ctr:0:n[e],a=e===Cn.CTR?Number.isFinite(r.ctr)?r.ctr:0:r[e];return t===`asc`?i-a:a-i})},[d,ot]),dt=Io({rows:ut,pageSize:25}),ft=se?dt.rows:ut,pt=Io({rows:(Me??[]).filter(e=>e.path.toLowerCase().includes(We.trim().toLowerCase())),pageSize:25}),[mt,gt]=(0,Q.useState)([]),[_t,yt]=(0,Q.useState)(null),[bt,xt]=(0,Q.useState)(1),St=(0,Q.useMemo)(()=>{if(mt.length<2)return null;let e=mt[mt.length-1],t=mt[mt.length-2];return{indexed:e.indexed-t.indexed,notIndexed:e.notIndexed-t.notIndexed}},[mt]);(0,Q.useEffect)(()=>{xt(1)},[G,it,_t]);let wt=(0,Q.useMemo)(()=>_t?(G?.reasonGroups??[]).find(e=>e.reason===_t):void 0,[G,_t]),Tt=(0,Q.useMemo)(()=>G?it===`indexed`?G.indexed:it===`deindexed`?G.deindexed:it===`notIndexed`?_t?wt?.urls??[]:(G.reasonGroups??[]).length===0?G.notIndexed:[]:[]:[],[G,it,_t,wt]),Et=Math.max(1,Math.ceil(Tt.length/Il)),Dt=Math.min(Math.max(1,bt),Et),Ot=(Dt-1)*Il,kt=(0,Q.useMemo)(()=>G?.indexed.slice(Ot,Ot+Il)??[],[G,Ot]),At=(0,Q.useMemo)(()=>G?.notIndexed.slice(Ot,Ot+Il)??[],[G,Ot]),jt=(0,Q.useMemo)(()=>G?.deindexed.slice(Ot,Ot+Il)??[],[G,Ot]),Mt=(0,Q.useMemo)(()=>(wt?.urls??[]).slice(Ot,Ot+Il),[wt,Ot]),[Nt,Ft]=(0,Q.useState)(!1),[Lt,Rt]=(0,Q.useState)(null),[zt,Vt]=(0,Q.useState)(null),[Ht,Ut]=(0,Q.useState)(null),[Wt,Gt]=(0,Q.useState)(null);function Kt(e,t){let n=$o(e),r=jl(n);r?(Vt(r),Rt(null)):(Vt(null),Rt(n.message||t))}let qt=s.find(e=>e.connectionType===`gsc`),Jt=(qt?.scopes??[]).includes(`https://www.googleapis.com/auth/webmasters`),Yt=Ie.length>0?Ie:(Me??[]).map(e=>e.path),Xt=Yt.filter(e=>Me?.some(t=>t.path===e&&t.isSitemapsIndex)).length,Qt=Xt===1?`Resubmit sitemap index`:Xt>1?`Resubmit sitemap indexes`:`Resubmit all sitemaps`,$t=d.length>0||h.length>0||_.length>0,en=Oo(),nn=Ua();async function rn(t,r=!1){if(i)u([]);else if(!t)u([]),C(``);else{ge(!0);try{let{sites:i}=await n.fetchQuery({...Xn({client:q,path:{name:e}}),staleTime:r?0:Nn});u(i),C(t.propertyId??i[0]?.siteUrl??``),Vt(null)}catch(e){u([]),Kt(e,`Failed to load Search Console properties`)}finally{ge(!1)}}}async function on(t){xe(!0);let r=t??te;try{let t=ct?Pl:25,i=ct?0:r,a={limit:String(t)};B.startDate&&(a.startDate=B.startDate),B.endDate&&(a.endDate=B.endDate),B.query&&(a.query=B.query),B.page&&(a.page=B.page),i>0&&(a.offset=String(i)),j&&j!==`all`&&!B.startDate&&(a.window=j);let o=await n.fetchQuery({...Vn({client:q,path:{name:e},query:a}),staleTime:Nn}),s=o.rows;ct?(U(!1),f(s),oe(s.length),ce(!0)):(U(i+s.length<o.totalMatching),f(s),oe(0),ce(!1))}catch(e){f([]),U(!1),oe(0),Rt(e instanceof Error?e.message:`Failed to load GSC performance data`)}finally{xe(!1)}}async function sn(){try{let t={};B.startDate&&(t.startDate=B.startDate),B.endDate&&(t.endDate=B.endDate),j&&j!==`all`&&!B.startDate&&(t.window=j);let r=await n.fetchQuery({...Di({client:q,path:{name:e},query:t}),staleTime:Nn});m(r)}catch{m(null)}}async function cn(t=!1){Ce(!0);try{let r=le.trim()||void 0,i={limit:`20`};r&&(i.url=r);let[a,o]=await Promise.all([n.fetchQuery({...sr({client:q,path:{name:e},query:i}),staleTime:t?0:Nn}),n.fetchQuery({...tr({client:q,path:{name:e}}),staleTime:t?0:Nn})]);g(a),v(o)}catch(e){g([]),v([]),Rt(e instanceof Error?e.message:`Failed to load GSC inspection history`)}finally{Ce(!1)}}async function ln(t=!1){ke(!0);try{let[r,i]=await Promise.all([n.fetchQuery({...Qn({client:q,path:{name:e}}),staleTime:t?0:Nn}),n.fetchQuery({...Jn({client:q,path:{name:e}}),staleTime:t?0:Nn}).catch(()=>[])]);Ee(r),gt(i)}catch(e){Ee(null),gt([]),Rt(e instanceof Error?e.message:`Failed to load coverage data`)}finally{ke(!1)}}async function un(t){Ft(!0),Rt(null);try{let{succeeded:n,failed:r,total:i}=(await De(e,{urls:t})).summary;jn({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){Rt(e instanceof Error?e.message:`Failed to request indexing`)}finally{Ft(!1)}}async function dn(){Ft(!0),Rt(null);try{let{succeeded:t,failed:n,total:r}=(await De(e,{urls:[],allUnindexed:!0})).summary;jn({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){Rt(e instanceof Error?e.message:`Failed to request indexing`)}finally{Ft(!1)}}async function fn(){je(!0),Rt(null);try{let t=await H(e);n.setQueryData(pr({client:q,path:{name:e}}),t),Ne(t.sitemaps),Fe(t.summary),Le(t.preferredSubmissionUrls),ze(new Set),Ve({}),t.sitemaps.length===0&&Ut(`No sitemaps found in this GSC property. Submit one here to start Google processing it.`)}catch(e){Rt(e instanceof Error?e.message:`Failed to list sitemaps`)}finally{je(!1)}}async function pn(t){let n=Re.has(t);if(ze(e=>{let r=new Set(e);return n?r.delete(t):r.add(t),r}),!(n||Be[t])){Ue(e=>new Set(e).add(t));try{let n=await H(e,t);Ve(e=>({...e,[t]:n.sitemaps}))}catch(e){Rt(e instanceof Error?e.message:`Failed to load sitemap files`)}finally{Ue(e=>{let n=new Set(e);return n.delete(t),n})}}}async function mn(t){if(!Jt||t.length===0)return;let n=[...new Set(t)];$e(!0),Rt(null),qe({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 Zt(e,s);r+=t.summary.accepted,i+=t.summary.failed,a+=s.length,qe({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}`,Rt(o),jn({title:`Sitemap resubmission partially completed`,detail:d,tone:`caution`,dedupeKey:`gsc:sitemap-submit:${e}`,dedupeMode:`replace`});return}}let t=n.length;jn({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`}),Ye(``)}catch(e){Rt(e instanceof Error?e.message:`Failed to submit sitemap to Google`)}finally{$e(!1),qe(null),await fn(),o&&Rt(o)}}async function hn(){$e(!0);let t=Me??[];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=Be[t.path];if(n)return n;let r=await H(e,t.path);return Ve(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 mn([...t.filter(e=>!e.isSitemapsIndex).map(e=>e.path),...r])}catch(e){Rt(e instanceof Error?e.message:`Failed to load sitemap files`),$e(!1)}}async function _n(t){Ze(!0),Rt(null);try{await ve(e,`gsc`,t),await Mn(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,sitemapUrl:t}:e)),jn({title:`Default sitemap updated`,detail:t,tone:`positive`,dedupeKey:`gsc:sitemap-default:${e}`,dedupeMode:`replace`})}catch(e){Rt(e instanceof Error?e.message:`Failed to set the default sitemap`)}finally{Ze(!1)}}async function vn(t){try{await nn.mutateAsync({projectName:e,projectLabel:e,opts:t?{sitemapUrl:t}:void 0})}catch{}}async function yn(){try{let t=(await n.fetchQuery({...Rr({client:q,path:{name:e},query:{kind:ht[`gsc-sync`],limit:1}}),staleTime:Nn}))[0];Gt(t?.status===vt.failed&&t.error?`Last saved Search Console sync failed: ${It(t.error)}`:null)}catch{Gt(`Saved Search Console sync status is unavailable.`)}}async function bn(){fe(!0),Rt(null);try{let[t,a]=await Promise.all([i||!r?Promise.resolve(null):Bt().catch(()=>null),n.fetchQuery({...or({client:q,path:{name:e}}),staleTime:Nn}).catch(()=>[])]);o(!!t?.google?.configured),c(a);let s=a.find(e=>e.connectionType===`gsc`);C(s?.propertyId??``),await Promise.all([!i&&s&&!s.propertyId?rn(s):Promise.resolve(),!i&&s?yn():Promise.resolve(),on(),sn(),cn(),ln()])}finally{fe(!1)}}(0,Q.useEffect)(()=>{u([]),tt(!1),Ne(null),Fe(null),Le([]),Gt(null),Vt(null),Ut(null)},[e]),(0,Q.useEffect)(()=>{bn()},[e,t,r]),(0,Q.useEffect)(()=>{re(0),R(null),V(e=>e.startDate||e.endDate?{...e,startDate:``,endDate:``}:e),ee(e=>e+1),sn()},[j]);let xn=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{xn.current?(re(0),dt.setPage(1),on(0)):xn.current=!0},[z]);function Tn(e){let t=L===e?null:e;R(t),V(e=>({...e,startDate:t??``,endDate:t??``})),ee(e=>e+1)}let En=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{En.current?(re(0),on(0)):En.current=!0},[lt]);async function Dn(){if(!a)Rt(`Google OAuth app credentials are not configured yet. Set them on the Settings page first.`);else{me(!0),Rt(null),Ut(null);try{let{authUrl:t,redirectUri:r}=await Pt(e,`gsc`);if(!t.startsWith(`https://accounts.google.com/`)){Rt(`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(),Ut(e?`Google connected. Refreshing access…`:`Refreshing Google connection…`);try{await Mn(n,`google`),await bn()}finally{Ut(null)}}};function u(e){if(e.source!==i||e.origin!==a||!e.data||typeof e.data!=`object`)return;let t=e.data;t.type===Ll&&t.connectionType===`gsc`&&l(!0)}window.addEventListener(`message`,u),Ut(`Finish the Google consent flow in the popup. This page will refresh automatically.`),s=window.setInterval(()=>{i.closed&&l(!1)},1e3)}catch(e){Rt(e instanceof Error?e.message:`Failed to start OAuth flow`)}finally{me(!1)}}}async function An(){Rt(null),Ut(null);try{await tn(e,`gsc`),await Mn(n,`google`),c(e=>e.filter(e=>e.connectionType!==`gsc`)),u([]),C(``)}catch(e){Rt(e instanceof Error?e.message:`Failed to disconnect`)}}async function Pn(){if(S){ye(!0),Rt(null);try{await ne(e,`gsc`,S),await Mn(n,`google`),c(e=>e.map(e=>e.connectionType===`gsc`?{...e,propertyId:S}:e)),jn({title:`GSC property updated`,detail:`${e} is now linked to ${S}.`,tone:`positive`,dedupeKey:`gsc:property:${e}`,dedupeMode:`drop`})}catch(e){Rt(e instanceof Error?e.message:`Failed to save GSC property`)}finally{ye(!1)}}}async function Fn(){Rt(null),Ut(null);try{await en.mutateAsync({projectName:e,projectLabel:e,opts:{days:parseInt(E,10)||void 0,full:k||void 0}}),await Mn(n,`gsc`)}catch{}}async function In(){if(w.trim()){Te(!0),Rt(null),Ut(null);try{let t=await Ct(e,w.trim());await Mn(n,`gsc`),b(t),T(``),await cn()}catch(e){Rt(e instanceof Error?e.message:`Failed to inspect URL`)}finally{Te(!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`})]})}),Wt&&(0,$.jsx)(`p`,{role:`status`,className:`mb-3 text-sm text-caution`,children:Wt}),zt&&(0,$.jsx)(`div`,{className:`mb-3 rounded-lg border border-caution-800/40 bg-caution-950/20 px-3 py-2.5 text-sm text-caution-200`,children:(0,$.jsxs)(`div`,{className:`flex items-start justify-between gap-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium text-caution-100`,children:zt.title}),(0,$.jsx)(`p`,{className:`mt-0.5 text-caution-200/90`,children:zt.message}),(Ha(zt.enableUrl)||Ha(zt.indexingApiUrl))&&(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-3`,children:[Ha(zt.enableUrl)&&(0,$.jsx)(`a`,{href:Ha(zt.enableUrl),target:`_blank`,rel:`noopener noreferrer`,className:`font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50`,children:`Enable Search Console API ↗`}),Ha(zt.indexingApiUrl)&&(0,$.jsx)(`a`,{href:Ha(zt.indexingApiUrl),target:`_blank`,rel:`noopener noreferrer`,className:`font-medium text-caution-100 underline decoration-caution-500/50 underline-offset-2 hover:text-caution-50`,children:`Enable Indexing API ↗`})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`text-caution-400 hover:text-caution-200`,onClick:()=>Vt(null),children:`×`})]})}),Lt&&(0,$.jsxs)(`div`,{className:`mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative`,children:[Lt,(0,$.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>Rt(null),children:`×`})]}),Ht&&(0,$.jsxs)(`div`,{className:`mb-3 rounded-lg border border-positive-800/40 bg-positive-950/20 px-3 py-2 text-sm text-positive`,children:[Ht,(0,$.jsx)(`button`,{type:`button`,className:`ml-2 text-positive-400 hover:text-positive-200`,onClick:()=>Ut(null),children:`×`})]}),de?(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:`Loading…`}):(0,$.jsxs)(`div`,{className:`space-y-3`,children:[qt?(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs 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:qt.domain}),(0,$.jsx)(`span`,{className:`text-mono-700`,children:`·`}),(0,$.jsxs)(`span`,{children:[`Coverage measured`,` `,G?.lastInspectedAt?gn(G.lastInspectedAt):`never`]}),!i&&(0,$.jsx)(`button`,{type:`button`,className:`ml-auto text-muted transition-colors hover:text-negative-400`,onClick:kn(An),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)(Y,{tone:a?`caution`:`negative`,children:a?`Ready to connect`:`App credentials missing`})]}),(0,$.jsxs)(`div`,{className:`mt-3 rounded-lg border border-default bg-surface px-4 py-5`,children:[(0,$.jsx)(`p`,{className:`text-sm text-neutral`,children:a?`Generate a Google OAuth link for this project and have the client sign in with a Google account that already has access to the correct Search Console property.`:`Set Google OAuth client credentials first. Once configured, you can generate a consent link for this project domain.`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-2`,children:[a?(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:pe,onClick:kn(Dn),children:pe?`Opening…`:`Connect Google Search Console`}):(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,asChild:!0,children:(0,$.jsx)(O,{to:`/settings`,children:`Open Settings`})}),!a&&(0,$.jsx)(`p`,{className:`text-xs 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-sm text-secondary`,children:Ml})}),(qt||$t)&&(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:`${zl(p?.periodComparison)} The optional trend line shows the fitted direction. Click any day to filter the table below to that date. Query and page filters match case-insensitive substrings and run on Apply filters. Filtering and sorting examine up to ${Pl.toLocaleString()} matching rows while the table shows 25 per page.`})]}),p?.window?.startDate&&p.window.endDate&&(0,$.jsxs)(`p`,{className:`text-xs text-muted`,children:[p.window.startDate,` to `,p.window.endDate,(p.window.daysSinceLatestData??0)>0&&` · latest data ${p.window.daysSinceLatestData} day${p.window.daysSinceLatestData===1?``:`s`} ago`]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(uc,{windows:Nl,value:j,onChange:e=>{M(e),re(0),dt.setPage(1)},label:`Search Console time period`,formatOption:e=>e===`all`?`All`:e}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:be,onClick:()=>{re(0),dt.setPage(1),on(0),sn()},children:be?`Loading…`:`Apply filters`})]})]}),p&&p.daily.length>0&&(()=>{let{totals:e,daily:t,trends:n,periodComparison:r}=p,i=Fl.filter(e=>N.includes(e.key)).map(e=>({dataKey:e.key,label:e.label,color:e.color,axisId:e.key,inverted:e.inverted,formatValue:e.format,trend:F?n?.[e.key]??null:null})),a=t=>e[t]??null,o=new Map(t.map(e=>[e.date,e])),s=t.length===0?[]:Ge(t[0].date,t[t.length-1].date).map(e=>o.get(e)??{date:e});return(0,$.jsxs)(`div`,{className:`mt-3`,children:[(0,$.jsx)(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-4`,children:Fl.map(e=>{let t=N.includes(e.key),n=a(e.key),i=n===null;return(0,$.jsxs)(`button`,{type:`button`,"aria-pressed":t,disabled:i,className:`rounded-md border px-3 py-2 text-left transition-colors ${t?`border-strong bg-surface-active`:`border-subtle bg-surface-subtle hover:bg-surface-hover`} ${i?`cursor-not-allowed opacity-50`:``}`,onClick:()=>{P(t=>t.includes(e.key)?t.length===1?t:t.filter(t=>t!==e.key):[...t,e.key])},children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`span`,{className:`inline-block h-2 w-2 rounded-full`,style:{backgroundColor:t?e.color:`transparent`,border:`1px solid ${e.color}`}}),(0,$.jsx)(`span`,{className:`text-xs text-secondary`,children:e.label})]}),(0,$.jsx)(`span`,{className:`mt-0.5 block text-lg tabular-nums text-strong`,children:n===null?`—`:e.format(n)}),(0,$.jsx)(`span`,{className:`block text-[11px] tabular-nums text-muted`,children:Rl(r,e.key,e.inverted)})]},e.key)})}),(0,$.jsx)(`div`,{className:`mt-2 flex items-center justify-end`,children:(0,$.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-1.5 text-xs text-secondary`,children:[(0,$.jsx)(`input`,{type:`checkbox`,className:`accent-mono-400`,checked:F,onChange:e=>I(e.target.checked)}),`Trend line`]})}),(0,$.jsx)(`div`,{className:`mt-1`,children:(0,$.jsx)(Ai,{data:s,xKey:`date`,series:i,xTickFormatter:ji,labelFormatter:Ii,onSelectX:Tn,selectedX:L})}),(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-xs focus:text-strong`,"aria-pressed":L===e.date,onClick:()=>Tn(e.date),children:[Ii(e.date),`: `,e.clicks,` clicks, `,e.impressions,` impressions`]},e.date))}),L&&(0,$.jsxs)(`div`,{className:`mt-1 flex items-center gap-2 text-xs`,children:[(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`Table showing `,Ii(L)]}),(0,$.jsxs)(`button`,{type:`button`,className:`text-link hover:underline`,onClick:()=>Tn(L),children:[`Show all `,e.days,` days`]})]}),e.position!==null&&(e.positionDays??e.days)<e.days&&(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] 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-[11px] 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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`Start date`,title:`Start date (inclusive). Leave blank to use the window above.`,value:B.startDate,onChange:e=>V(t=>({...t,startDate:e.target.value}))}),(0,$.jsx)(`input`,{className:`rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`date`,"aria-label":`End date`,title:`End date (inclusive).`,value:B.endDate,onChange:e=>V(t=>({...t,endDate:e.target.value}))}),(0,$.jsx)(No,{value:B.query,onChange:e=>V(t=>({...t,query:e})),label:`Filter search queries`,placeholder:`Contains query…`}),(0,$.jsx)(No,{value:B.page,onChange:e=>V(t=>({...t,page:e})),label:`Filter page URLs`,placeholder:`Contains page URL…`})]}),d.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-sm`,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(Cn).map(e=>(0,$.jsx)(`th`,{className:`text-right`,"aria-sort":ot?.key===e?ot.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:()=>{dt.setPage(1),st(t=>t?.key===e?t.dir===`desc`?{key:e,dir:`asc`}:null:{key:e,dir:`desc`})},children:[wn[e],ot?.key===e?ot.dir===`desc`?` ↓`:` ↑`:``]})},e))]})}),(0,$.jsx)(`tbody`,{children:ft.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)(Mo,{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:W(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)(Fo,{page:se?dt.page:Math.floor(te/25)+1,pageSize:25,visibleRows:ft.length,totalRows:se?ae:void 0,hasNextPage:se?void 0:ie,disabled:be,itemLabel:se?`matches`:`rows`,onPageChange:e=>{if(se){dt.setPage(e);return}let t=(e-1)*25;re(t),on(t)}}),se&&ae>=Pl?(0,$.jsxs)(`p`,{className:`mt-2 text-xs text-muted`,children:[`Results are capped at `,Pl.toLocaleString(),`; narrow the filters to search beyond this set.`]}):null]}):(0,$.jsx)(`p`,{className:`mt-3 text-sm 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:[G&&G.notIndexed.length>0&&(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Nt,onClick:()=>void dn(),children:Nt?`Requesting…`:`Request indexing (${G.notIndexed.length})`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Oe,onClick:()=>void ln(!0),children:Oe?`Loading…`:`Reload saved coverage`})]})]}),G&&G.summary.total>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`mt-6 flex flex-col items-center`,children:(()=>{let e=G.summary.indexedShare??0,t=G.summary.notIndexedShare??0,n=2*Math.PI*54,r=n*(1-e),i=n*t,a=n*e;return(0,$.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:Fi.trackSubtle,strokeWidth:`14`}),(0,$.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:zi.positiveDeep,strokeWidth:`14`,strokeDasharray:n,strokeDashoffset:r,strokeLinecap:`round`,transform:`rotate(-90 64 64)`,style:{transition:`stroke-dashoffset 0.6s ease`}}),G.summary.notIndexed>0&&(0,$.jsx)(`circle`,{cx:`64`,cy:`64`,r:54,fill:`none`,stroke:Fi.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-3xl font-bold tabular-nums text-primary`,children:W(G.summary.indexedShare)}),(0,$.jsx)(`span`,{className:`text-xs uppercase tracking-widest 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-2xl font-semibold tabular-nums text-primary`,children:G.summary.indexed.toLocaleString()}),(0,$.jsx)(`p`,{className:`text-[11px] uppercase tracking-wide 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-2xl font-semibold tabular-nums text-primary`,children:G.summary.notIndexed.toLocaleString()}),(0,$.jsxs)(`p`,{className:`text-[11px] uppercase tracking-wide text-muted`,children:[`Not indexed`,(G.reasonGroups??[]).length>0&&(0,$.jsxs)(`span`,{className:`ml-1 text-faint`,children:[`· `,(G.reasonGroups??[]).length,` `,(G.reasonGroups??[]).length===1?`reason`:`reasons`]})]})]})]}),G.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-2xl font-semibold tabular-nums text-primary`,children:G.summary.deindexed.toLocaleString()}),(0,$.jsx)(`p`,{className:`text-[11px] uppercase tracking-wide 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`?G.indexed.length:e===`notIndexed`?G.notIndexed.length:G.deindexed.length;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":it===e,className:`border-b-2 px-3 py-2 text-sm font-medium transition-colors ${it===e?`border-accent text-heading`:`border-transparent text-secondary hover:border-mono-600 hover:text-strong`}`,onClick:()=>{at(e),yt(null)},children:[e===`indexed`?`Indexed`:e===`notIndexed`?`Not Indexed`:`Deindexed`,` (`,t,`)`]},e)})}),(0,$.jsxs)(`div`,{className:`mt-3 overflow-x-auto`,children:[it===`indexed`&&G.indexed.length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:kt.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))})]}),it===`notIndexed`&&!_t&&(G.reasonGroups??[]).length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:(G.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:()=>yt(e.reason),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),yt(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))})]}),it===`notIndexed`&&!_t&&(G.reasonGroups??[]).length===0&&G.notIndexed.length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:At.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))})]}),it===`notIndexed`&&_t&&(()=>{let e=(G.reasonGroups??[]).find(e=>e.reason===_t);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-xs text-secondary hover:text-strong transition-colors`,onClick:()=>yt(null),children:[`←`,` Back to reasons`]})}),(0,$.jsxs)(`div`,{className:`mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-sm font-medium text-strong`,children:e.reason}),(0,$.jsxs)(`p`,{className:`mt-1 text-xs text-muted`,children:[e.count,` affected page`,e.count===1?``:`s`]})]}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Nt,onClick:()=>void un(e.urls.map(e=>e.url)),children:Nt?`Requesting…`:`Request indexing (${e.count})`})]}),(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:Mt.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-xs text-muted hover:text-strong transition-colors`,disabled:Nt,onClick:()=>void un([e.url]),title:`Request indexing`,children:`Index`})})]},e.id))})]})]}):null})(),it===`deindexed`&&G.deindexed.length>0&&(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:jt.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}`))})]}),(it===`indexed`&&G.indexed.length===0||it===`notIndexed`&&!_t&&G.notIndexed.length===0||it===`deindexed`&&G.deindexed.length===0)&&(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:`No URLs in this category.`}),(0,$.jsx)(Fo,{page:Dt,pageSize:Il,visibleRows:Math.min(Il,Tt.length-Ot),totalRows:Tt.length,onPageChange:xt,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-xs text-secondary hover:text-strong focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,"aria-expanded":nt,onClick:()=>rt(e=>!e),children:[(0,$.jsx)(`span`,{children:`Coverage history`}),(0,$.jsx)(`span`,{children:nt?`Hide snapshots`:mt.length>0?`View ${mt.length} snapshots`:`View history`})]}),(0,$.jsxs)(`p`,{className:`mt-1 text-xs text-muted`,children:[`Current: `,G.summary.indexed.toLocaleString(),` indexed, `,G.summary.notIndexed.toLocaleString(),` not indexed.`,St&&(0,$.jsxs)($.Fragment,{children:[` Since the last snapshot: `,St.indexed>=0?`+`:``,St.indexed.toLocaleString(),` indexed, `,St.notIndexed>=0?`+`:``,St.notIndexed.toLocaleString(),` not indexed.`]})]}),nt&&(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:mt.length>0?(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:mt.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-sm text-muted`,children:`No saved coverage snapshots yet.`})})]})]}):(0,$.jsx)(`p`,{className:`mt-3 text-sm text-muted`,children:Oe?`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`,{children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Sitemaps`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-1.5`,children:[(0,$.jsx)(`h3`,{children:`Sitemap operations`}),(0,$.jsx)(X,{text:`Submitting asks Google to refetch these sitemaps. Indexing is not guaranteed.`})]})]}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Ae||!qt?.propertyId,onClick:()=>void fn(),children:Ae?`Loading…`:Me===null?`Load from Google`:`Reload from Google`})]}),(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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`url`,placeholder:`https://example.com/sitemap.xml`,value:Je,onChange:e=>Ye(e.target.value),onKeyDown:e=>e.key===`Enter`&&void mn([Je.trim()])}),(0,$.jsx)(J,{type:`button`,size:`sm`,disabled:!Jt||Qe||!Je.trim(),onClick:()=>void mn([Je.trim()]),children:Qe?`Submitting…`:`Submit sitemap to Google`})]}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-2`,children:[(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:!Jt||Qe||Yt.length===0,onClick:()=>void mn(Yt),children:Qe?`Resubmitting…`:Qt}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:!Jt||Qe||!Me?.length,onClick:()=>void hn(),children:`Resubmit all files`}),Pe&&(0,$.jsxs)(`span`,{className:`text-xs text-muted`,children:[`Top level: `,Pe.indexes,` index`,Pe.indexes===1?``:`es`,`, `,Pe.files,` file`,Pe.files===1?``:`s`]}),Ke&&(0,$.jsxs)(`span`,{className:`text-xs text-secondary`,children:[`Submitting `,Ke.completed,`/`,Ke.total]})]}),!Jt&&qt&&(0,$.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 text-xs text-caution`,children:[(0,$.jsx)(`span`,{children:`Reconnect to let Canonry submit sitemaps. Your current Canonry OAuth grant is read-only.`}),(0,$.jsx)(`button`,{type:`button`,className:`text-secondary underline hover:text-strong`,onClick:kn(Dn),children:`Reconnect`})]}),Me===null&&(0,$.jsx)(`p`,{className:`mt-3 text-sm text-secondary`,children:`Load sitemaps from Google to view them and enable resubmission.`}),Me&&(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:Me.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(No,{value:We,onChange:e=>{K(e),pt.setPage(1)},label:`Filter sitemaps`,placeholder:`Filter sitemaps…`}),(0,$.jsxs)(`table`,{className:`data-table mt-3 w-full text-sm`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Sitemap`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Type`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Google status`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Last submitted`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Last read`}),(0,$.jsx)(`th`,{className:`text-right`,children:`Discovered URLs`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Issues`}),(0,$.jsx)(`th`,{className:`text-left`,children:`Actions`})]})}),(0,$.jsx)(`tbody`,{children:pt.rows.flatMap(e=>{let t=Bl(e),n=Vl(e),r=Hl(e),i=Be[e.path]??[],a=Re.has(e.path);return[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-xs text-strong`,children:(0,$.jsx)(Mo,{value:e.path})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.isSitemapsIndex?(0,$.jsx)(`button`,{type:`button`,className:`text-secondary hover:text-strong`,"aria-expanded":a,"aria-label":`${a?`Collapse`:`Expand`} files in ${e.path}`,onClick:()=>void pn(e.path),children:He.has(e.path)?`Loading…`:`${a?`▾`:`▸`} Index${Be[e.path]?` (${i.length})`:``}`}):`Sitemap`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:r}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.lastSubmitted?e.lastSubmitted.split(`T`)[0]:`—`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:e.lastDownloaded?e.lastDownloaded.split(`T`)[0]:`—`}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:t.toLocaleString()}),(0,$.jsx)(`td`,{className:`max-w-48 text-secondary`,children:n||`—`}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,className:`text-xs text-secondary hover:text-strong`,disabled:!Jt||Qe,onClick:()=>void mn([e.path]),children:e.lastSubmitted?`Resubmit to Google`:`Submit to Google`}),qt?.sitemapUrl===e.path?(0,$.jsx)(`span`,{className:`text-xs text-muted`,title:`Used when no sitemap URL is provided for Canonry GSC operations.`,children:`Default sitemap`}):(0,$.jsx)(`button`,{type:`button`,className:`text-xs text-secondary hover:text-strong`,disabled:Xe,title:`Use this sitemap by default for Canonry GSC operations.`,onClick:()=>void _n(e.path),children:`Set as default`}),(0,$.jsx)(`button`,{type:`button`,className:`text-xs text-secondary hover:text-strong`,disabled:nn.isPending,onClick:()=>void vn(e.path),children:`Inspect URLs`})]})})]},e.path),...e.isSitemapsIndex&&a?i.map(t=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`max-w-xs pl-6 text-secondary`,children:(0,$.jsx)(Mo,{value:t.path})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:`File`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Hl(t)}),(0,$.jsx)(`td`,{className:`text-secondary`,children:t.lastSubmitted?t.lastSubmitted.split(`T`)[0]:`—`}),(0,$.jsx)(`td`,{className:`text-secondary`,children:t.lastDownloaded?t.lastDownloaded.split(`T`)[0]:`—`}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-neutral`,children:Bl(t).toLocaleString()}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Vl(t)||`—`}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(`button`,{type:`button`,className:`text-xs text-secondary hover:text-strong`,disabled:!Jt||Qe,onClick:()=>void mn([t.path]),children:`Resubmit`}),qt?.sitemapUrl===t.path?(0,$.jsx)(`span`,{className:`text-xs text-muted`,title:`Used when no sitemap URL is provided for Canonry GSC operations.`,children:`Default sitemap`}):(0,$.jsx)(`button`,{type:`button`,className:`text-xs text-secondary hover:text-strong`,disabled:Xe,title:`Use this sitemap by default for Canonry GSC operations.`,onClick:()=>void _n(t.path),children:`Set as default`}),(0,$.jsx)(`button`,{type:`button`,className:`text-xs text-secondary hover:text-strong`,disabled:nn.isPending,onClick:()=>void vn(t.path),children:`Inspect URLs`})]})})]},`${e.path}:${t.path}`)):[]]})})]}),(0,$.jsx)(Fo,{page:pt.page,pageSize:25,visibleRows:pt.rows.length,totalRows:pt.totalRows,onPageChange:pt.setPage,itemLabel:`sitemaps`})]}):(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:`No sitemaps found for this 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:`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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`url`,placeholder:`https://example.com/page`,value:w,onChange:e=>T(e.target.value),onKeyDown:e=>e.key===`Enter`&&void In()}),(0,$.jsx)(J,{type:`button`,size:`sm`,disabled:we||!qt?.propertyId||!w.trim(),onClick:kn(In),children:we?`Inspecting…`:`Inspect URL`})]}),y&&(0,$.jsxs)(`div`,{className:`mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4`,children:[(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Indexing state`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:y.indexingState??`Unknown`})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Verdict`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:y.verdict??`Unknown`})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Mobile friendly`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:Sn(y.isMobileFriendly??null)})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Last crawl`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:gn(y.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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:Se,onClick:()=>void cn(!0),children:Se?`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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`text`,placeholder:`Filter exact URL`,value:le,onChange:e=>ue(e.target.value)}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:Se,onClick:()=>void cn(!0),children:`Apply filter`})]}),h.length>0?(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:h.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:Sn(e.isMobileFriendly??null)}),(0,$.jsx)(`td`,{className:`text-secondary`,children:gn(e.inspectedAt)})]},e.id))})]})}):(0,$.jsx)(`p`,{className:`mt-3 text-sm 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`})]})}),_.length>0?(0,$.jsx)(`div`,{className:`mt-3 overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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:_.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:gn(e.transitionDate)})]},`${e.url}:${e.transitionDate}`))})]})}):(0,$.jsx)(`p`,{className:`mt-3 text-sm text-muted`,children:`No deindexed transitions recorded.`})]})]}),qt&&!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:()=>{et||rn(qt),tt(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 ${et?`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-xs uppercase tracking-wide text-muted`,children:`Setup & Configuration`})]})}),et&&(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-xs 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-sm text-strong focus:border-mono-500 focus:outline-none`,value:S,disabled:he||l.length===0,onChange:e=>C(e.target.value),children:l.length===0?(0,$.jsx)(`option`,{value:``,children:he?`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)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:he,onClick:()=>void rn(qt,!0),children:he?`Refreshing…`:`Refresh properties`}),(0,$.jsx)(J,{type:`button`,size:`sm`,disabled:!S||_e,onClick:kn(Pn),children:_e?`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-xs 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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,value:E,onChange:e=>D(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:k,onChange:e=>A(e.target.checked)}),`Replace existing imported rows for the requested range`]})]}),(0,$.jsx)(J,{type:`button`,size:`sm`,disabled:en.isPending||!qt.propertyId,onClick:kn(Fn),children:en.isPending?`Queueing…`:`Queue sync`}),!qt.propertyId&&(0,$.jsx)(`p`,{className:`text-xs text-caution-400`,children:`Select a Search Console property before queueing a sync.`})]})]})]})})]})]})]})}var Wl=new Set([`gbp-listing-discrepancy`,`gbp-lodging-gap`,`gbp-cta-gap`,`gbp-metric-drop`,`gbp-keyword-drop`]);function Gl({projectName:e,projectId:t}){let n=x(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(!1),l=C(or({client:q,path:{name:e}})),u=l.data?.find(e=>e.connectionType===`gbp`),d=!!u,f=r?{locationName:r}:void 0,p=C({...ur({client:q,path:{name:e}}),enabled:d}),m=C({...Wr({client:q,path:{name:e},query:f}),enabled:d}),h=C({...yi({client:q,path:{name:e},query:f}),enabled:d}),g=C({...Kn({client:q,path:{name:e},query:f}),enabled:d}),_=C({...Wn({client:q,path:{name:e},query:f}),enabled:d}),v=C({...ir({client:q,path:{name:e},query:f}),enabled:d}),y=C({queryKey:[`gbp-section-insights`,e],queryFn:()=>qe(e),enabled:d});function b(){Mn(n,`gbp`)}let w=S({...xr(),onSuccess:n=>{Ya({id:n.runId,projectId:t,kind:ht[`gbp-sync`],projectLabel:e,sourceAction:`gbp-sync`}),jn({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)(Gi,Ra,Ra),E=Object.values(T.runs).some(e=>e.kind===ht[`gbp-sync`]&&e.projectId===t),D=w.isPending||E,O=S({...yr(),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 font-mono text-[11px] 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 font-mono text-[11px] 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-sm leading-6 text-muted`,children:`Track local performance, search terms, place-action CTAs, and how your public Maps listing compares to the profile you control. Four steps from the CLI:`}),(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-xs font-medium tabular-nums text-neutral`,"aria-hidden":`true`,children:t+1}),(0,$.jsxs)(`div`,{className:`min-w-0`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium 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 font-mono text-xs text-neutral`,children:e.command}),(0,$.jsx)(`p`,{className:`mt-1 text-xs leading-5 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)),B=P.filter(e=>z.has(e.locationName)),V=F.filter(e=>z.has(e.locationName)),H=new Set(j.map(e=>e.locationName)),te=r?M:M.filter(e=>H.has(e.locationName)),ne=!r&&j.length>1,re=(y.data??[]).filter(e=>!e.dismissed&&Wl.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)(Y,{tone:`positive`,children:`Connected`}),!U()&&(0,$.jsx)(pa,{type:`button`,variant:`outline`,size:`sm`,disabled:D,onClick:()=>w.mutate({client:q,path:{name:e},body:{}}),children:D?`Syncing…`:`Sync`})]})]}),(0,$.jsxs)(`p`,{className:`mb-4 text-xs 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-sm font-medium 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-sm 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-sm text-muted`,children:[`No locations are tracked yet. Open `,(0,$.jsx)(`span`,{className:`font-medium text-neutral`,children:`Manage locations`}),` below to track the one(s) for this business.`]}):(0,$.jsxs)($.Fragment,{children:[re.length>0&&(0,$.jsxs)(`div`,{className:`mb-6 grid gap-2`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Needs attention`}),re.map(e=>(0,$.jsx)(`div`,{className:[`insight-card`,cu(e.severity),`rounded-r-lg border border-default bg-surface p-3 pl-4`].filter(Boolean).join(` `),children:(0,$.jsxs)(`p`,{className:`flex items-center gap-2 text-sm font-medium text-strong`,children:[e.title,e.recommendation?.reason&&(0,$.jsx)(X,{text:e.recommendation.reason})]})},e.id))]}),k&&(0,$.jsx)(gu,{performance:k.performance,freshness:k.freshness,timeseries:k.timeseries}),k?.profileCompleteness&&(0,$.jsx)(Kl,{summary:k.profileCompleteness}),R.length>0&&(0,$.jsx)(ql,{locations:R,lodging:ee,places:V,placeActions:B,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-[11px] text-faint`,children:[W(h.data.thresholdedPct,oe.percent),` privacy-thresholded`]})]}),te.length===0?(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:`No keyword impressions stored yet.`}):(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`text-left`,children:`Search term`}),ne&&(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:te.slice(0,25).map(e=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`text-neutral`,children:e.keyword}),ne&&(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 font-mono text-[11px] 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-xs font-medium 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-sm 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-sm`,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`}),!U()&&(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)(Y,{tone:t.selected?`positive`:`neutral`,children:t.selected?`Tracked`:`Not tracked`})}),!U()&&(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(pa,{type:`button`,variant:`outline`,size:`sm`,disabled:O.isPending,onClick:()=>O.mutate({client:q,path:{name:e,locationName:t.locationName},body:{selected:!t.selected}}),children:t.selected?`Untrack`:`Track`})})]},t.id))})]})})]})]})})}function Kl({summary:e}){if(e.locationCount===0)return null;let t=e.locationCount,n=[{label:`Description`,value:`${e.withDescription}/${t}`,tone:ou(e.withDescription,t,`caution`)},{label:`Hours`,value:`${e.withHours}/${t}`,tone:ou(e.withHours,t,`caution`)},{label:`Phone`,value:`${e.withPrimaryPhone}/${t}`,tone:ou(e.withPrimaryPhone,t,`caution`)},{label:`Service area`,value:`${e.withServiceArea}/${t}`,tone:ou(e.withServiceArea,t,`neutral`)},{label:`Secondary categories`,value:`${e.withSecondaryCategories}/${t}`,detail:`${e.secondaryCategoryTotal} total`,tone:ou(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-xs text-muted`,children:e.label}),(0,$.jsx)(`span`,{className:`font-mono text-sm tabular-nums ${su(e.tone)}`,children:e.value}),e.detail&&(0,$.jsx)(`span`,{className:`col-span-2 text-[11px] text-faint`,children:e.detail})]},e.label))})]})}function ql({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:U()?`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-[11px] 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:`font-medium text-strong`,children:e.displayName}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-faint`,children:e.primaryCategoryDisplayName??`Primary category not returned`}),(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap gap-1.5`,children:[(0,$.jsx)(Y,{tone:e.selected?`positive`:`neutral`,children:e.selected?`Tracked`:`Not tracked`}),e.openStatus&&e.openStatus!==`OPEN`&&(0,$.jsx)(Y,{tone:e.openStatus===`CLOSED_PERMANENTLY`?`negative`:`caution`,children:uu(e.openStatus)})]})]})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Yl,{location:e})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Xl,{lodging:t})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Ql,{place:n,mapsUri:e.mapsUri})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(eu,{actions:r})}),(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(J,{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)(ru,{location:e,lodging:t,place:n,placeActions:r})})})]},e.id)})})]})})]})}function Jl(e){return[{label:`Description`,tone:lu(e.description)?`positive`:`neutral`,value:lu(e.description)?`set`:`not returned`},{label:`Hours`,tone:e.regularHours?`positive`:`neutral`,value:e.regularHours?`set`:`not returned`},{label:`Phone`,tone:lu(e.primaryPhone)?`positive`:`neutral`,value:lu(e.primaryPhone)?`set`:`not returned`},{label:`Website`,tone:lu(e.websiteUri)?`positive`:`neutral`,value:lu(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 Yl({location:e}){let t=Jl(e);return(0,$.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(e=>(0,$.jsxs)(Y,{tone:e.tone,children:[e.label,` `,e.value]},e.label))})}function Xl({lodging:e}){return(0,$.jsx)(nu,{...Zl(e)})}function Zl(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 Ql({place:e,mapsUri:t}){return(0,$.jsx)(nu,{...$l(e,t)})}function $l(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 eu({actions:e}){return(0,$.jsx)(nu,{...tu(e)})}function tu(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 nu({tone:e,label:t,detail:n}){return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(Y,{tone:e,children:t}),(0,$.jsx)(`p`,{className:`mt-1.5 text-xs leading-5 text-faint`,children:n})]})}function ru({location:e,lodging:t,place:n,placeActions:r}){let i=t?mu(t.attributes):[];return(0,$.jsxs)(`div`,{className:`grid gap-5 text-xs lg:grid-cols-3`,children:[(0,$.jsxs)(iu,{title:`Owner profile · Business Information`,children:[(0,$.jsx)(au,{label:`Primary category`,value:e.primaryCategoryDisplayName??`Not returned`}),(0,$.jsx)(au,{label:`Secondary categories`,value:e.additionalCategories.length>0?e.additionalCategories.join(`, `):`Not returned`}),(0,$.jsx)(au,{label:`Description`,value:lu(e.description)?e.description:`Not returned`}),(0,$.jsx)(au,{label:`Hours`,value:e.regularHours?`Returned by Google`:`Not returned`}),(0,$.jsx)(au,{label:`Service area`,value:e.serviceArea?`Returned by Google`:`Not returned`}),(0,$.jsx)(au,{label:`Phone`,value:e.primaryPhone??`Not returned`}),(0,$.jsx)(au,{label:`Website`,value:e.websiteUri??`Not returned`}),(0,$.jsx)(au,{label:`Open status`,value:uu(e.openStatus)}),(0,$.jsx)(au,{label:`Opening date`,value:e.openingDate??`Not returned`})]}),(0,$.jsx)(iu,{title:`Hotel data · Lodging API`,children:t?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(au,{label:`Last checked`,value:pu(t.syncedAt)}),(0,$.jsx)(au,{label:`Groups returned`,value:String(t.populatedGroupCount)}),(0,$.jsx)(au,{label:`Populated groups`,value:i.length>0?i.join(`, `):`None returned`})]}):(0,$.jsx)(`p`,{className:`leading-5 text-muted`,children:`No Lodging API snapshot was stored for this location.`})}),(0,$.jsxs)(iu,{title:`Public listing + CTAs`,children:[n?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(au,{label:`Places tier`,value:n.tier}),(0,$.jsx)(au,{label:`Last checked`,value:pu(n.syncedAt)}),(0,$.jsx)(au,{label:`Public signals`,value:n.amenities.length>0?n.amenities.join(`, `):`No supported signals detected`})]}):(0,$.jsx)(`p`,{className:`leading-5 text-muted`,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:`leading-5 text-muted`,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:`font-medium text-neutral`,children:[du(e.placeActionType),e.isPreferred?` · preferred`:``]}),(0,$.jsxs)(`span`,{className:`text-faint`,children:[du(e.providerType),e.uri?` · ${fu(e.uri)}`:``]})]},e.placeActionLinkName))})})]})]})}function iu({title:e,children:t}){return(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted`,children:e}),(0,$.jsx)(`div`,{className:`grid gap-2`,children:t})]})}function au({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 ou(e,t,n){return e===t?`positive`:e===0?n:`caution`}function su(e){switch(e){case`positive`:return`text-positive`;case`caution`:return`text-caution`;case`negative`:return`text-negative`;case`neutral`:return`text-neutral`}}function cu(e){return e===`critical`||e===`high`?`insight-card-negative`:e===`medium`?`insight-card-caution`:``}function lu(e){return typeof e==`string`&&e.trim().length>0}function uu(e){return e?du(e):`Not returned`}function du(e){return e?e.toLowerCase().split(`_`).filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(` `):`Unknown`}function fu(e){try{return new URL(e).hostname.replace(/^www\./,``)}catch{return e}}function pu(e){let t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString(void 0,{month:`short`,day:`numeric`,year:`numeric`})}function mu(e){return Object.entries(e).filter(([e,t])=>e!==`name`&&e!==`metadata`&&hu(t)).map(([e])=>du(e.replace(/([a-z])([A-Z])/g,`$1_$2`)))}function hu(e){return e==null?!1:Array.isArray(e)?e.length>0:typeof e!=`object`||Object.keys(e).length>0}function gu({performance:e,freshness:t,timeseries:n}){let r=e.totals,i=ut.filter(e=>(r[e]??0)>0),a=on.filter(e=>(r[e]??0)>0),o=Object.keys(r).filter(e=>(r[e]??0)>0&&Be(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 ${Ii(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-[11px] text-muted`,children:f})]}),!d||i.length===0?(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:`No profile action activity yet — run a sync.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(_u,{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-sm text-secondary`,children:[re(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)(_u,{data:c,metrics:a,kind:`area`,firstPending:l,lastDate:u})]}),s.length>0&&(0,$.jsxs)(`p`,{className:`text-xs text-faint`,children:[`Not active: `,s.map(e=>re(e)).join(`, `)]})]})}function _u({data:e,metrics:t,kind:n,firstPending:r,lastDate:i}){return(0,$.jsx)(`div`,{className:`h-48 w-full`,children:(0,$.jsx)(P,{width:`100%`,height:`100%`,children:(0,$.jsxs)(z,{data:e,margin:{top:8,right:8,bottom:0,left:0},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`date`,tick:Ri,tickLine:!1,axisLine:{stroke:Ui},tickFormatter:ji,minTickGap:24}),(0,$.jsx)(L,{tick:Ri,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),(0,$.jsx)(j,{...Hi,labelFormatter:Ii,formatter:(e,t)=>[typeof e==`number`?e.toLocaleString():String(e??0),re(String(t??``))]}),(0,$.jsx)(I,{wrapperStyle:{fontSize:11,color:Fi.text},formatter:e=>re(e)}),r&&i&&(0,$.jsx)(N,{x1:r,x2:i,fill:Fi.surface,fillOpacity:.55,stroke:`none`,label:{value:`pending`,position:`insideTopRight`,fill:Fi.textDim,fontSize:10}}),t.map((e,t)=>n===`line`?(0,$.jsx)(R,{type:`monotone`,dataKey:e,stroke:ki[t%ki.length],strokeWidth:2,dot:!1,isAnimationActive:!1},e):(0,$.jsx)(F,{type:`monotone`,dataKey:e,stackId:`reach`,stroke:ki[t%ki.length],fill:ki[t%ki.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},e))]})})})}function vu(e){return Li(Pi(String(e)))}function yu(e){return Mi(Pi(String(e)))}var bu=25;function xu(e){return typeof window>`u`?e:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,``)??``}${e}`}function Su(e){return e.toLocaleString()}function Cu(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){let t=e.filter(e=>e.kind===ht[`backlink-extract`]&&!wa(e.status));return t.length===0?null:t.reduce((e,t)=>e.createdAt>t.createdAt?e:t)}function Tu(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 Eu({projectName:e}){let t=an(),[n,r]=(0,Q.useState)(null),[a,c]=(0,Q.useState)(null),[u,d]=(0,Q.useState)([]),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),[y,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,i,a,o]=await Promise.all([We().catch(()=>null),ce(e,{excludeCrawlers:!0}).catch(()=>null),je(e,{limit:bu,offset:x,excludeCrawlers:!0}).catch(e=>{if(e instanceof at&&e.code===`NOT_FOUND`)return null;throw e}),Ie(e).catch(()=>[]),fe(e).catch(()=>[])]);m(t),r(n),c(i),d(a);let s=wu(o);g(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(!h)return;let e=h.id,t=!1,n=async()=>{try{let n=await Se(e);if(t)return;wa(n.status)?(g(null),v(n),await k()):g(e=>e?.id===n.id?{...e,...n}:e)}catch{}},r=window.setInterval(()=>{n()},3e3);return()=>{t=!0,window.clearInterval(r)}},[h,k]),(0,Q.useEffect)(()=>{if(!h)return;let e=window.setInterval(()=>b(Date.now()),1e3);return()=>window.clearInterval(e)},[h]),(0,Q.useEffect)(()=>{if(!_||_.status===`failed`)return;let e=window.setTimeout(()=>v(null),1e4);return()=>window.clearTimeout(e)},[_]);async function A(){E(!0),O(null);try{let t=await Ot(e);g(t)}catch(e){e instanceof at&&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 N=(0,Q.useMemo)(()=>u.slice().sort((e,t)=>e.queriedAt.localeCompare(t.queriedAt)).map(e=>({date:e.queriedAt,linkingDomains:e.totalLinkingDomains})),[u]),I=a?.rows??[],R=a?.total??0,ee=n?.excludedLinkingDomains??0,B=Math.floor(x/bu)+1;return(0,Q.useEffect)(()=>{x>0&&x>=R&&S(0)},[x,R]),(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 border-negative-800/60`,children:(0,$.jsx)(`p`,{className:`text-sm text-negative`,children:D})}),h&&(0,$.jsx)(Z,{className:`surface-card p-4 mb-4 border-info-800/60`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[(0,$.jsx)(f,{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-sm font-medium text-heading`,children:`Extract running`}),(0,$.jsx)(Y,{tone:`neutral`,children:h.status}),(0,$.jsxs)(`span`,{className:`text-sm text-secondary tabular-nums`,children:[Tu(h.startedAt??null,h.createdAt),` elapsed · refreshing every 3s`]}),(0,$.jsxs)(`span`,{className:`sr-only`,children:[`now=`,y]})]}),(0,$.jsx)(`p`,{className:`text-sm text-secondary mt-1`,children:`Refreshing this project from the current Common Crawl release.`})]})]})}),_&&!h&&(0,$.jsx)(Z,{className:`surface-card p-4 mb-4 ${_.status===`failed`?`border-negative-800/60`:`border-positive-800/60`}`,children:(0,$.jsxs)(`div`,{className:`flex items-start gap-3`,children:[_.status===`failed`?(0,$.jsx)(`span`,{className:`h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none`,"aria-hidden":!0,children:`!`}):(0,$.jsx)(i,{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-sm font-medium ${_.status===`failed`?`text-negative`:`text-positive`}`,children:_.status===`failed`?`Extract failed`:`Extract complete`}),_.error?(0,$.jsx)(`p`,{className:`text-sm text-secondary mt-1`,children:Tn(_.error)}):_.status===`failed`?null:(0,$.jsx)(`p`,{className:`text-sm text-secondary mt-1`,children:`Backlinks refreshed from the cached release.`})]})]})}),V()]});function V(){return C?(0,$.jsx)(Z,{className:`surface-card p-6`,children:(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:`Loading backlinks…`})}):H()}function H(){let e=n!==null&&n.totalLinkingDomains>0,r=_?.status===`failed`,i=n!==null&&n.totalLinkingDomains===0&&!r,a=p?.status===`ready`,c=p?.status===`failed`,u=p&&(p.status===`downloading`||p.status===`querying`||p.status===`queued`);return e?te((0,$.jsxs)($.Fragment,{children:[!U()&&!t&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:T||h!==null,onClick:kn(A),children:[(0,$.jsx)(o,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),h?`Extract running…`:T?`Queuing…`:`Re-run extract`]}),(0,$.jsx)(Ro,{label:`About re-running`,children:`Re-queries the current release for this project without downloading it again.`})]}),!U()&&!t&&(0,$.jsx)(J,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,$.jsx)(`a`,{href:xu(`/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-lg bg-bg-elevated text-secondary`,children:(0,$.jsx)(s,{className:`h-5 w-5`,"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`flex-1`,children:[!p&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-heading`,children:`No release sync yet`}),(0,$.jsx)(`p`,{className:`text-sm text-muted mt-1`,children:`Run a workspace release sync to populate backlinks for every project in this workspace.`}),!U()&&!t&&(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:xu(`/backlinks`),children:`Set up backlinks`})})})]}),u&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-heading`,children:`Sync in progress`}),(0,$.jsxs)(`p`,{className:`text-sm text-muted mt-1`,children:[`A workspace release sync is running (`,p.status,p.phaseDetail?` — ${p.phaseDetail}`:``,`). Backlinks will appear here once it finishes.`]}),!U()&&!t&&(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(J,{asChild:!0,type:`button`,variant:`outline`,size:`sm`,children:(0,$.jsx)(`a`,{href:xu(`/backlinks`),children:`View sync status`})})})]}),c&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-heading`,children:`Last sync failed`}),(0,$.jsx)(`p`,{className:`text-sm text-muted mt-1`,children:p.error??`The workspace release sync failed. Retry from the Backlinks admin page.`}),!U()&&!t&&(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:xu(`/backlinks`),children:`Go to Backlinks admin`})})})]}),a&&!u&&!i&&!r&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-heading`,children:`No backlinks yet for this project`}),(0,$.jsxs)(`p`,{className:`text-sm text-secondary mt-1`,children:[`Release `,(0,$.jsx)(`code`,{className:`text-neutral`,children:p.release}),` is ready. Run an extract for this project.`]}),!U()&&!t&&(0,$.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,$.jsxs)(J,{type:`button`,size:`sm`,disabled:T||h!==null,onClick:kn(A),children:[(0,$.jsx)(l,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),h?`Extract running…`:T?`Queuing…`:`Run extract`]}),(0,$.jsx)(Ro,{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-base font-semibold text-heading`,children:`Last extract failed`}),(0,$.jsx)(`p`,{className:`text-sm text-secondary mt-1`,children:`See the error above, then check the workspace source before retrying.`}),!U()&&!t&&(0,$.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:(0,$.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:xu(`/backlinks`),children:`Go to Backlinks admin`})})})]}),i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-heading`,children:`No referring domains found`}),(0,$.jsxs)(`p`,{className:`text-sm text-secondary mt-1`,children:[`The latest release found no referring domains for `,n.targetDomain,`. Try a newer release or re-run this extract.`]}),!U()&&!t&&(0,$.jsxs)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:[(0,$.jsx)(J,{asChild:!0,type:`button`,size:`sm`,children:(0,$.jsx)(`a`,{href:xu(`/backlinks`),children:`Go to Backlinks admin`})}),(0,$.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:T||h!==null,onClick:kn(A),children:[(0,$.jsx)(l,{className:`h-4 w-4 mr-1.5`,"aria-hidden":!0}),h?`Extract running…`:T?`Queuing…`:`Re-run extract`]}),(0,$.jsxs)(Ro,{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 te(e){if(!n)return null;let t=`linking hosts`,r=`release`;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`gauge-row`,children:[(0,$.jsxs)(`div`,{className:`metric-card`,children:[(0,$.jsx)(`p`,{className:`metric-card-eyebrow`,children:`Referring domains`}),(0,$.jsx)(`p`,{className:`metric-card-big-value`,children:(0,$.jsx)(`span`,{className:`text-primary`,children:Su(n.totalLinkingDomains)})}),(0,$.jsxs)(`p`,{className:`metric-card-sub`,children:[`unique domains linking to `,n.targetDomain]})]}),(0,$.jsxs)(`div`,{className:`metric-card`,children:[(0,$.jsxs)(`p`,{className:`metric-card-eyebrow`,children:[`Total `,t]}),(0,$.jsx)(`p`,{className:`metric-card-big-value`,children:(0,$.jsx)(`span`,{className:`text-primary`,children:Su(n.totalHosts)})}),(0,$.jsxs)(`p`,{className:`metric-card-sub`,children:[`aggregate `,t,` across referring domains`]})]}),(0,$.jsxs)(`div`,{className:`metric-card`,children:[(0,$.jsx)(`p`,{className:`metric-card-eyebrow`,children:`Top-10 concentration`}),(0,$.jsx)(`p`,{className:`metric-card-big-value`,children:(0,$.jsx)(`span`,{className:`text-primary`,children:W(Number(n.top10HostsShare))})}),(0,$.jsxs)(`p`,{className:`metric-card-sub`,children:[`share of `,t,` from the 10 largest linking domains`]})]})]}),(0,$.jsxs)(`p`,{className:`text-xs text-muted mt-2`,children:[(0,$.jsx)(`span`,{className:`text-secondary`,children:`Common Crawl`}),` · `,r,` `,(0,$.jsx)(`code`,{className:`text-secondary`,children:n.release}),` · queried `,Cu(n.queriedAt),ee>0&&(0,$.jsxs)($.Fragment,{children:[` · `,ee,` excluded domain`,ee===1?``:`s`]})]}),N.length>=2&&(0,$.jsxs)(Z,{className:`surface-card p-4 mt-4`,children:[(0,$.jsx)(`p`,{className:`eyebrow eyebrow-soft`,children:`Referring domains over time`}),(0,$.jsx)(`div`,{className:`h-40 mt-2`,children:(0,$.jsx)(P,{width:`100%`,height:`100%`,children:(0,$.jsxs)(z,{data:N,margin:{top:8,right:12,bottom:0,left:12},children:[(0,$.jsx)(`defs`,{children:(0,$.jsxs)(`linearGradient`,{id:`bl-gradient`,x1:`0`,y1:`0`,x2:`0`,y2:`1`,children:[(0,$.jsx)(`stop`,{offset:`0%`,stopColor:ki[0],stopOpacity:.4}),(0,$.jsx)(`stop`,{offset:`100%`,stopColor:ki[0],stopOpacity:0})]})}),(0,$.jsx)(M,{dataKey:`date`,tick:Ri,stroke:`var(--chart-axis, #27272a)`,tickFormatter:vu}),(0,$.jsx)(L,{tick:Ri,stroke:`var(--chart-axis, #27272a)`,allowDecimals:!1}),(0,$.jsx)(j,{contentStyle:Hi.contentStyle,labelStyle:Hi.labelStyle,itemStyle:Hi.itemStyle,labelFormatter:yu}),(0,$.jsx)(F,{type:`monotone`,dataKey:`linkingDomains`,name:`Referring domains`,stroke:ki[0],fill:`url(#bl-gradient)`,strokeWidth:2})]})})})]}),(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-sm`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base text-left text-xs uppercase tracking-wide text-faint`,children:[(0,$.jsx)(`th`,{className:`px-4 py-2 font-medium`,children:`Domain`}),(0,$.jsx)(`th`,{className:`px-4 py-2 text-right font-medium`,children:`Linking hosts`})]})}),(0,$.jsxs)(`tbody`,{children:[I.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:Su(e.numHosts)})]},e.linkingDomain)),I.length===0&&(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{className:`px-4 py-4 text-sm text-muted`,colSpan:2,children:ee>0&&R===0?`Every referring domain in this ${r} was a crawler/proxy host (${ee} hidden).`:`No referring domains in this ${r}.`})})]})]})}),(0,$.jsx)(Fo,{page:B,pageSize:bu,visibleRows:I.length,totalRows:R,onPageChange:e=>S((e-1)*bu)})]}),(0,$.jsx)(`div`,{className:`mt-4 flex items-center gap-3 flex-wrap`,children:e})]})}}var Du={[K[`keyword-metrics`]]:`Search demand`,[K[`domain-intelligence`]]:`Domain comparison`,[K[`ranked-keywords`]]:`Searches you rank for`,[K[`market-rankings`]]:`Market rankings`},Ou={[et.queued]:`Queued`,[et.running]:`Refreshing`,[et.completed]:`Completed`,[et.partial]:`Partial results`,[et.failed]:`Failed`,[et.cancelled]:`Cancelled`,[et[`reconciliation-required`]]:`Needs review`},ku=25,Au=new Intl.NumberFormat(`en-US`,{maximumFractionDigits:1}),ju=new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`,maximumFractionDigits:2}),Mu=Intl.DateTimeFormat().resolvedOptions().timeZone,Nu=`min-h-11 w-full rounded-md border border-default bg-bg px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,Pu=`px-4 py-3 text-right align-top tabular-nums whitespace-nowrap`,Fu=`min-w-56 px-4 py-3 text-left align-top font-normal`,Iu=`Position on the page, counting maps and other blocks`;function Lu(e){return e?.status===et.queued||e?.status===et.running}function Ru({value:e,currency:t=!1}){return e===null?(0,$.jsx)(`span`,{className:`text-muted`,"aria-label":`Not supplied`,children:`—`}):(0,$.jsx)($.Fragment,{children:t?ju.format(e):Au.format(e)})}function zu({status:e}){let t=e===et.completed?`positive`:e===et.failed?`negative`:e===et.partial||e===et[`reconciliation-required`]?`caution`:`neutral`;return(0,$.jsx)(Y,{tone:t,children:Ou[e]})}function Bu(e){let t=B(e).split(`/`).at(-1)??e,n=Re.safeParse(t.replaceAll(`_`,`-`));return n.success?Du[n.data]:t.replaceAll(/[-_]/g,` `)}function Vu(e){return e===`mobile`?`phone results`:e===`desktop`?`computer results`:`device not specified by source`}function Hu(e){return e.capabilities.includes(K[`market-rankings`])?`Market locations`:`Location ${e.locationCode}`}function Uu(e){return e.capabilities.includes(K[`market-rankings`])?`searches`:`tasks`}function Wu(e){return e.capability!==K[`market-rankings`]||![et.queued,et.running,et.completed].includes(e.status)}function Gu(e,t){let n=e.capabilities.includes(K[`market-rankings`]);return`${t} ${t===1?n?`search`:`task`:Uu(e)}`}function Ku(e,t){return Number.isFinite(Date.parse(e))?Ze(Te(e,t)):null}var qu={[et.failed]:`Latest refresh failed`,[et.cancelled]:`Latest refresh cancelled`,[et[`reconciliation-required`]]:`Latest refresh needs review`};function Ju(e,t){let n=e&&e.id!==t?.id?qu[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=`${Gu(t,t.failedTasks)} failed`,n=t.capabilities.includes(K[`market-rankings`])?`Their queries show as Failed.`:`Open Activity for details.`;return{label:e,text:`${e}: ${t.failedTasks} of ${Gu(t,t.taskCount)} in this refresh returned no results. ${n}`}}return t.status===et.partial?{label:`Partial results`,text:`Partial results: ${t.error??`some ${Uu(t)} returned only part of their results or did not run. Open Activity for details.`}`}:null}function Yu({source:e}){return(0,$.jsxs)(`dl`,{className:`grid gap-x-8 gap-y-2 text-[13px] sm:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Dataset`}),(0,$.jsx)(`dd`,{children:Bu(e.dataset)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Search engine`}),(0,$.jsxs)(`dd`,{children:[`Google · `,Vu(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:$e(e.collectedAt,Mu)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-muted`,children:`Source updated`}),(0,$.jsx)(`dd`,{children:e.sourceUpdatedAt?me(e.sourceUpdatedAt):`Not supplied`})]})]})}function Xu({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-[13px] 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-[13px] leading-relaxed text-secondary`,children:[n,t&&(0,$.jsx)(Yu,{source:t})]})]})}function Zu({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-sm`,children:[(0,$.jsx)(`p`,{children:Xo(e)}),(0,$.jsx)(J,{variant:`secondary`,className:`min-h-11`,onClick:t,children:`Retry`})]})}function Qu({title:e,children:t}){return(0,$.jsxs)(`div`,{className:`py-12 text-center`,children:[(0,$.jsx)(`h3`,{className:`font-medium text-heading`,children:e}),(0,$.jsx)(`p`,{className:`mx-auto mt-2 max-w-lg text-sm leading-relaxed text-secondary`,children:t})]})}function $u({projectName:e}){let t=T({strict:!1}),n=w(),r=C(Tr({client:q,path:{name:e}})),i=C(qn({client:q,path:{name:e}})),a=C({...ar({client:q,path:{name:e,id:t.seoRunId??``}}),enabled:!!t.seoRunId}),[o,s]=(0,Q.useState)(null),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=t.seoProfileId??a.data?.profileId,d=u?i.data?.profiles.find(e=>e.id===u):t.seoRunId?void 0:i.data?.profiles[0],f=t=>{s(null),n({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})})},p=r.data?.access.canWrite===!0&&!U()&&!an(),m=()=>{s(null),c.current?.focus()};if((0,Q.useEffect)(()=>{!t.seoProfileId&&d&&n({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoProfileId:d.id}),replace:!0})},[n,e,t.seoProfileId,d]),r.error)return(0,$.jsx)(Zu,{error:r.error,retry:()=>{r.refetch()}});if(i.error)return(0,$.jsx)(Zu,{error:i.error,retry:()=>{i.refetch()}});if(!r.data||!i.data)return(0,$.jsx)(`p`,{role:`status`,className:`py-10 text-sm text-secondary`,children:`Loading SEO data…`});let h=r.data.available&&r.data.connections.some(e=>e.capabilities.length>0),g=h&&r.data.connections.some(e=>e.capabilities.some(e=>r.data.scopes.some(t=>t.capabilities?.includes(e)??!0))),_=d&&r.data.scopes.find(e=>e.kind===d.scope.kind&&e.key===(d.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-xl font-semibold tracking-tight text-heading`,children:`SEO`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:`Search demand and organic rankings.`})]}),p&&g&&(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[d&&(0,$.jsx)(J,{variant:`ghost`,className:`min-h-11`,onClick:e=>{c.current=e.currentTarget,s({profile:d,id:d.id})},children:`Edit profile`}),(0,$.jsxs)(J,{variant:`secondary`,className:`min-h-11`,onClick:e=>{c.current=e.currentTarget,s({id:crypto.randomUUID()})},children:[(0,$.jsx)(y,{"aria-hidden":`true`,className:`size-4`}),`New profile`]})]})]}),i.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-[13px] text-secondary`,children:`Profile`}),(0,$.jsxs)(`select`,{ref:l,"aria-label":`SEO profile`,value:d?.id??``,onChange:e=>f(e.target.value),className:`${Nu} min-w-0 sm:w-64`,children:[!d&&(0,$.jsx)(`option`,{value:``,disabled:!0,children:`Profile unavailable`}),i.data.profiles.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),d&&(0,$.jsxs)(`div`,{className:`min-w-0 text-[13px] text-secondary`,children:[(0,$.jsx)(`p`,{className:`break-words font-medium text-primary`,children:_?.label??`${d.scope.kind}${d.scope.key?`: ${d.scope.key}`:``}`}),(0,$.jsxs)(`p`,{children:[d.rankings?`${d.rankings.locations.length} search location${d.rankings.locations.length===1?``:`s`}`:`Location ${d.locationCode}`,` · `,d.languageCode]})]})]}),o&&(0,$.jsx)(Md,{projectName:e,context:r.data,profile:o.profile,id:o.id,onClose:m,onSaved:e=>{f(e),requestAnimationFrame(()=>l.current?.focus())}},o.id),!an()&&!r.data.available&&i.data.profiles.length>0&&(0,$.jsx)(`p`,{role:`status`,className:`rounded-md border border-default px-4 py-3 text-sm text-secondary`,children:r.data.reason??`Configure an SEO data provider to refresh saved profiles.`}),t.seoRunId&&a.error?(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsx)(Zu,{error:a.error,retry:()=>{a.refetch()}}),d?(0,$.jsx)(J,{variant:`secondary`,className:`min-h-11`,onClick:()=>f(d.id),children:`View latest data`}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`Select a profile to view its latest data.`})]}):t.seoRunId&&a.isPending?(0,$.jsx)(`p`,{role:`status`,className:`py-10 text-sm text-secondary`,children:`Loading refresh…`}):d&&a.data&&a.data.profileId!==d.id?(0,$.jsxs)(Qu,{title:`Refresh belongs to another profile`,children:[`Choose the refresh’s profile, or return to the selected profile’s latest data.`,(0,$.jsx)(J,{variant:`secondary`,className:`mt-4 min-h-11`,onClick:()=>f(d.id),children:`View latest data`})]}):d?(0,$.jsx)(ed,{projectName:e,profile:d,context:r.data,selectedRunId:t.seoRunId,onLatest:()=>f(d.id)},`${d.id}:${d.revision}:${t.seoRunId??``}`):!g&&i.data.profiles.length===0?(0,$.jsx)(Qu,{title:h?`SEO scope unavailable`:`Configure an SEO data provider`,children:h?r.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.`}):u?(0,$.jsx)(Qu,{title:`Profile unavailable`,children:`This saved profile is no longer available. Select another profile to view its data.`}):!o&&(0,$.jsx)(Qu,{title:`No SEO data yet`,children:p?`Create a profile to choose the scope, source, and searches to measure.`:`An SEO profile is needed before data can be collected.`})]})}function ed({projectName:e,profile:t,context:n,selectedRunId:r,onLatest:i}){let a=x(),[o,s]=(0,Q.useState)(r?`activity`:t.capabilities.includes(K[`ranked-keywords`])?K[`ranked-keywords`]:t.capabilities.at(0)??`activity`),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),p={name:e},m=C({...dr({client:q,path:p,query:{profileId:t.id,runId:r}}),refetchInterval:e=>Lu(e.state.data?.latestRun)?2e3:!1}),h=S({...Yr({client:q}),meta:{skipGlobalErrorToast:!0}}),g=S({...Lr({client:q}),meta:{skipGlobalErrorToast:!0}}),_=m.data?.latestRun,y=m.data?.evidenceRun,b=m.data?.evidenceRun?.capabilities??t.capabilities,w=o===`activity`||b.includes(o)?o:b.at(0)??`activity`,T=Lu(_),E=h.isPending||g.isPending,D=n.access.canRun&&!U()&&!an(),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=C({...br({client:q,path:p,query:{kind:Me[`seo-sync`]}}),retry:!1}),j=!A.isError&&A.data?.enabled&&A.data.nextRunAt?A.data.nextRunAt:null,M=j?Ku(j,A.data?.timezone??`UTC`):null,N=y?.finishedAt&&(y.status===et.completed||y.status===et.partial)?Ku(y.finishedAt,Mu):null,P=T?null:Ju(_,y);return(0,Q.useEffect)(()=>{_&&(Lu(_)?d.current=_.id:d.current===_.id&&(d.current=null,Mn(a,`seo`,{projectName:e,profileId:t.id})))},[_,t.id,e,a]),(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-sm text-secondary`,children:[(0,$.jsx)(`div`,{"aria-live":`polite`,children:T&&_?(0,$.jsxs)(`p`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(f,{className:`size-4 animate-spin`,"aria-hidden":`true`}),_.cancelRequested?`Cancellation requested`:Ou[_.status],` · `,_.completedTasks,` of `,_.taskCount,` `,Uu(_),` completed`]}):(0,$.jsxs)(`p`,{children:[N&&y?.finishedAt?(0,$.jsxs)($.Fragment,{children:[`Updated `,(0,$.jsx)(`time`,{dateTime:y.finishedAt,title:$e(y.finishedAt,Mu)??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})]}),r?(0,$.jsx)(J,{variant:`secondary`,className:`min-h-11`,onClick:i,children:`View latest data`}):D&&(0,$.jsxs)(J,{className:`min-h-11`,disabled:E||T||!n.available||!O,onClick:kn(async()=>{if(!(!D||r||T||E)){l(null);try{if(!u.current){let e=await h.mutateAsync({path:p,body:{profileId:t.id}});if(e.availability!==ge.ready){l(e.reason??`This profile cannot be refreshed. Review its scope and source.`);return}u.current={quoteToken:e.token,idempotencyKey:crypto.randomUUID()}}let e=await g.mutateAsync({path:p,body:u.current});u.current=null,Lu(e)&&(d.current=e.id),await a.fetchQuery(dr({client:q,path:p,query:{profileId:t.id}}))}catch(e){$o(e).code===`VALIDATION_ERROR`&&(u.current=null),l(Xo(e))}}}),children:[(0,$.jsx)(v,{"aria-hidden":`true`,className:`size-4 ${E?`animate-spin`:``}`}),E?`Starting refresh…`:T?`Refresh in progress`:u.current?`Retry refresh`:`Refresh data`]})]}),c&&(0,$.jsxs)(`p`,{role:`alert`,className:`rounded-md border border-default p-4 text-sm text-secondary`,children:[c,u.current&&` Retry uses the same request, so it will not start a duplicate refresh.`]}),r&&(0,$.jsxs)(`p`,{className:`break-all text-[13px] text-secondary`,children:[`Viewing saved refresh `,r,`.`]}),m.data?.evidenceRun&&m.data.evidenceRun.profileRevision!==t.revision&&(0,$.jsxs)(`p`,{role:`status`,className:`text-sm text-secondary`,children:[`Saved data uses profile revision `,m.data.evidenceRun.profileRevision,` · `,Hu(m.data.evidenceRun),` · `,m.data.evidenceRun.languageCode,`. The current profile has changed.`]}),!an()&&k&&!k.supported&&(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:k.reason??`This scope is not supported for domain data.`}),m.error?(0,$.jsx)(Zu,{error:m.error,retry:()=>{m.refetch()}}):m.data?.summary&&(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`p`,{className:`mb-3 break-words text-[13px] text-secondary`,children:[m.data.summary.target.value,m.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-[13px] text-secondary`,children:`Searches you rank for`}),(0,$.jsx)(`dd`,{className:`mt-2 text-3xl font-semibold tabular-nums tracking-tight text-heading`,children:(0,$.jsx)(Ru,{value:m.data.summary.organicKeywords})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-[13px] text-secondary`,children:`In the top 10`}),(0,$.jsx)(`dd`,{className:`mt-2 text-3xl font-semibold tabular-nums tracking-tight text-heading`,children:(0,$.jsx)(Ru,{value:m.data.summary.inTop10})})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`dt`,{className:`flex items-center gap-1.5 text-[13px] 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-3xl font-semibold tabular-nums tracking-tight text-heading`,children:(0,$.jsx)(Ru,{value:m.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":w===e,className:`min-h-11 border-b-2 text-sm font-medium focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400 ${w===e?`border-strong text-primary`:`border-transparent text-secondary hover:text-primary`}`,onClick:()=>s(e),children:e===`activity`?`Activity`:Du[e]},e))}),w===`activity`?(0,$.jsx)(jd,{projectName:e,profileId:t.id,canRun:D,selectedRunId:r}):m.isPending?(0,$.jsx)(`p`,{role:`status`,className:`py-8 text-sm text-secondary`,children:`Loading saved data…`}):m.data&&(0,$.jsx)(td,{projectName:e,profileId:t.id,runId:m.data.evidenceRunId,view:w,active:T,nextRefresh:M},`${t.id}:${w}:${m.data.evidenceRunId??`empty`}`)]}),(0,$.jsxs)(`details`,{className:`border-t border-subtle text-sm text-secondary`,children:[(0,$.jsx)(`summary`,{className:`flex min-h-11 cursor-pointer items-center font-medium 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-[13px] leading-relaxed`,children:[(0,$.jsxs)(`p`,{children:[`Current profile source: `,an()?`Fictional demo data`:O?.label??`Source unavailable`,`. Google; `,Vu(t.rankings?.device??`unspecified`),`.`]}),m.data?.evidenceRun&&(0,$.jsxs)(`p`,{children:[`Saved evidence: `,m.data.evidenceRun.scope.kind,m.data.evidenceRun.scope.key?` · ${m.data.evidenceRun.scope.key}`:``,m.data.evidenceRun.scope.expectedPlanRevision===void 0?``:` · plan revision ${m.data.evidenceRun.scope.expectedPlanRevision}`,`. `,Hu(m.data.evidenceRun),` · `,m.data.evidenceRun.languageCode,` · profile revision `,m.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,`.`]}),m.data?.summary&&(0,$.jsx)(Yu,{source:m.data.summary.provenance})]})]})]})}function td({projectName:e,profileId:t,runId:n,view:r,active:i,nextRefresh:a}){return r===K[`market-rankings`]?n?(0,$.jsx)(xd,{projectName:e,profileId:t,runId:n,active:i}):(0,$.jsx)(Qu,{title:`No market rankings yet`,children:a?`First refresh ${a}`:`Refresh this profile to rank its tracked queries in each market.`}):(0,$.jsx)(nd,{projectName:e,profileId:t,runId:n,view:r,active:i})}function nd({projectName:e,profileId:t,runId:n,view:r,active:i}){let[a,o]=(0,Q.useState)(1),s={client:q,path:{name:e},query:{profileId:t,runId:n??void 0,limit:ku,offset:(a-1)*ku}},c=C({...Gn(s),enabled:!!n&&r===K[`ranked-keywords`]}),l=C({...lr(s),enabled:!!n&&r===K[`keyword-metrics`]}),u=C({...Ci(s),enabled:!!n&&r===K[`domain-intelligence`]}),d=r===K[`ranked-keywords`]?c:r===K[`keyword-metrics`]?l:u;return n?d.error?(0,$.jsx)(`div`,{className:`py-4`,children:(0,$.jsx)(Zu,{error:d.error,retry:()=>{d.refetch()}})}):d.data?d.data.items.length===0?(0,$.jsx)(Qu,{title:i?`Refresh in progress`:`No results returned`,children:i?`This profile is collecting data.`:`The source did not return records for this scope. Review the refresh in Activity before changing the profile.`}):(0,$.jsxs)(`div`,{className:`pt-4`,children:[(0,$.jsxs)(`div`,{className:`relative overflow-x-auto rounded-md border border-default`,role:`region`,"aria-label":`${Du[r]} table`,tabIndex:0,children:[r===K[`ranked-keywords`]&&c.data&&(0,$.jsx)(rd,{rows:c.data.items}),r===K[`keyword-metrics`]&&l.data&&(0,$.jsx)(id,{rows:l.data.items}),r===K[`domain-intelligence`]&&u.data&&(0,$.jsx)(ad,{rows:u.data.items})]}),(0,$.jsx)(Fo,{page:a,pageSize:ku,visibleRows:d.data.items.length,totalRows:d.data.total,onPageChange:o,disabled:d.isFetching,className:`text-[13px] [&_button]:min-h-11`})]}):(0,$.jsxs)(`p`,{role:`status`,className:`py-8 text-sm text-secondary`,children:[`Loading `,Du[r].toLowerCase(),`…`]}):(0,$.jsxs)(Qu,{title:`No saved data yet`,children:[`Refresh this profile to collect `,Du[r].toLowerCase(),` for its saved scope.`]})}function rd({rows:e}){return(0,$.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Searches you rank for, from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-[13px] text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-4 py-3 text-left font-medium`,children:`Search`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`Position`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`Monthly searches`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`Est. traffic`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,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:Fu,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.keyword}),(0,$.jsx)(`p`,{className:`mt-1 text-[13px] text-secondary`,children:(0,$.jsx)(Mo,{value:e.url??e.target.value})})]}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.rankOrganic})}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.searchVolume})}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.estimatedTraffic})}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.keywordDifficulty})}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsxs)(Xu,{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:[Iu,`: `,(0,$.jsx)(Ru,{value:e.rankAbsolute})]}),(0,$.jsxs)(`p`,{children:[`CPC: `,(0,$.jsx)(Ru,{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 id({rows:e}){return(0,$.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Search demand from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-[13px] text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-4 py-3 text-left font-medium`,children:`Search`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`Monthly searches`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`CPC`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`Difficulty /100`}),(0,$.jsx)(`th`,{className:`px-4 py-3 text-left font-medium`,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:`${Fu} text-primary`,children:e.keyword}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.searchVolume})}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.cpcUsd,currency:!0})}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{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)(Xu,{label:e.keyword,source:e.provenance,children:[(0,$.jsxs)(`p`,{children:[`Ad competition: `,e.adCompetition===null?`Not supplied`:W(e.adCompetition,oe.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)(Ru,{value:e.searchVolume})})]},`${e.year}-${e.month}`))})]})})]},`${e.keyword}:${t}`))})]})}function ad({rows:e}){return(0,$.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:`Domain comparison from the selected refresh`}),(0,$.jsx)(`thead`,{className:`bg-surface text-[13px] text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{className:`px-4 py-3 text-left font-medium`,children:`Domain`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,children:`Searches ranked for`}),(0,$.jsx)(`th`,{className:`${Pu} font-medium`,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:Fu,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.target.value}),(0,$.jsx)(`p`,{className:`mt-1 text-[13px] text-secondary`,children:e.target.includeSubdomains?`Includes subdomains`:`Exact host`})]}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.organicKeywords})}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Ru,{value:e.estimatedOrganicTraffic})}),(0,$.jsx)(`td`,{className:`px-4 align-top`,children:(0,$.jsx)(Xu,{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)(Ru,{value:e.top1})}),(0,$.jsx)(`dt`,{children:`Positions 2–3`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(Ru,{value:e.top2To3})}),(0,$.jsx)(`dt`,{children:`Positions 4–10`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(Ru,{value:e.top4To10})}),(0,$.jsx)(`dt`,{children:`Positions 11–20`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(Ru,{value:e.top11To20})}),(0,$.jsx)(`dt`,{children:`Est. traffic value`}),(0,$.jsx)(`dd`,{children:(0,$.jsx)(Ru,{value:e.estimatedOrganicTrafficValueUsd,currency:!0})})]})})})]},`${e.target.value}:${t}`))})]})}var od=5,sd=10,cd=`all`;function ld(e){return e===cd?cd:gt.safeParse(e).data??null}var ud={column:`ranks11To20`,descending:!0},dd={3:`sm:grid-cols-3`,4:`sm:grid-cols-4`,5:`sm:grid-cols-5`},fd=`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`,pd=`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 md(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 hd(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 gd(e){let t=e.filter(e=>e.kind===pe.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 _d(e,t){return e.counts[t]}function vd(e){let t=e.descending?-1:1,n=e.column;return n===`label`?(e,n)=>t*(At(e.label,n.label)||At(e.key,n.key)):(e,r)=>t*(_d(e,n)-_d(r,n))||At(e.label,r.label)||At(e.key,r.key)}function yd(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 bd({label:e,align:t,sorted:n,onSort:r}){return(0,$.jsx)(`th`,{scope:`col`,"aria-sort":n??void 0,className:`px-4 font-medium whitespace-nowrap ${t===`right`?`text-right`:`text-left`}`,children:(0,$.jsxs)(`button`,{type:`button`,onClick:r,className:`${fd} ${n?`text-primary`:``}`,children:[e,n&&(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`ml-0.5`,children:n===`ascending`?`↑`:`↓`})]})})}function xd({projectName:e,profileId:t,runId:n,active:r}){let i=T({strict:!1}),a=w(),o=i.seoRegion,s=i.seoMarket,c=ld(i.seoShow),l=Qt.safeParse(i.seoSort).data??Ce.rank,u=t=>{a({to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,...t}),replace:!0})},d=(0,Q.useId)(),f=C(bi({client:q,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)(Zu,{error:f.error,retry:()=>{f.refetch()}})});if(!f.data)return(0,$.jsx)(`p`,{role:`status`,className:`py-8 text-sm 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)(Cd,{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)(Qu,{title:`No rankings here`,children:[`This refresh has no rankings for this `,s===void 0?`region`:`market`,`.`]}):(0,$.jsx)(Qu,{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=Je(m,p),b=c??(p.needsWork>0?Xe[`needs-work`]:cd),x=h.length>1||h.some(e=>e.kind===pe.region),S=[`${Au.format(p.queries)} ${p.queries===1?`query`:`queries`}`,...p.partlyChecked>0?[`${Au.format(p.partlyChecked)} partly checked`]:[],...p.failed>0?[`${Au.format(p.failed)} failed`]:[],...p.cancelled>0?[`${Au.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-base font-semibold text-heading`,children:`Google rank`}),(0,$.jsx)(`p`,{className:`text-[13px] tabular-nums text-secondary`,children:S})]}),(0,$.jsxs)(`dl`,{className:`grid grid-cols-2 gap-5 border-b border-subtle pb-5 ${dd[y.length+1]??`sm:grid-cols-5`}`,children:[y.map(e=>(0,$.jsx)(Sd,{label:e.label,help:md(e,m),value:p[e.count]},e.count)),(0,$.jsx)(Sd,{label:`Rival ahead`,help:hd(m),value:p.rivalAhead,className:`sm:border-l sm:border-subtle sm:pl-5`})]})]}),x&&(0,$.jsx)(wd,{projectName:e,groups:h,bands:y},`groups\u0000${g}`),(0,$.jsx)(Td,{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===Ce.rank?void 0:e}),urlQ:i.seoQ??``,onQ:e=>u({seoQ:e||void 0}),onClear:()=>u({seoShow:cd,seoQ:void 0})},`queries\u0000${g}`)]})}function Sd({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-[13px] text-secondary`,children:[e,(0,$.jsx)(X,{text:t,placement:`bottom`})]}),(0,$.jsx)(`dd`,{className:`mt-2 text-3xl font-semibold tabular-nums tracking-tight text-heading`,children:Au.format(n)})]})}function Cd({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-sm`,children:[(0,$.jsx)(O,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoRegion:void 0,seoMarket:void 0}),className:pd,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:`font-medium text-primary`,children:a}):(0,$.jsx)(O,{to:`/projects/$projectName/seo-data`,params:{projectName:e},search:e=>({...e,seoMarket:void 0}),className:pd,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:`font-medium text-primary`,children:i??`Market not in this refresh`})]})]})}function wd({projectName:e,groups:t,bands:n}){let r=w(),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(1),c=gd(t),l=(i===null?t:[...t].sort(vd(i))).slice((o-1)*od,o*od),d=i??(n.some(e=>e.count===ud.column)?ud: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??ud;a(t.column===e?{column:e,descending:!t.descending}:{column:e,descending:e!==`label`}),s(1)},m=e=>d?.column===e?d.descending?`descending`:`ascending`:null,h=e=>e.kind===pe.region?t=>({...t,seoRegion:e.key,seoMarket:void 0}):t=>({...t,seoMarket:e.key}),g=`Google rank by ${c.label.toLowerCase()}`;return(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`h3`,{className:`text-base font-semibold text-heading`,children:[`By `,c.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-sm`,children:[(0,$.jsx)(`caption`,{className:`sr-only`,children:g}),(0,$.jsx)(`thead`,{className:`bg-surface text-[13px] text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(bd,{label:c.label,align:`left`,sorted:m(`label`),onSort:()=>p(`label`)}),f.map(e=>(0,$.jsx)(bd,{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:l.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 font-normal`,children:(0,$.jsx)(O,{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:Pu,children:Au.format(t.counts[e.column])},e.column)),(0,$.jsx)(`td`,{className:`px-4 py-3 text-right align-top`,children:(0,$.jsx)(u,{"aria-hidden":`true`,className:`ml-auto size-4 text-muted`})})]},`${t.kind}:${t.key}`))})]})}),(0,$.jsx)(Fo,{page:o,pageSize:od,visibleRows:l.length,totalRows:t.length,onPageChange:s,itemLabel:c.plural,className:`text-[13px] [&_button]:min-h-11`})]})}function Td({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=yd(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 w=x.filterKey===b?x.page:1,T=C({...Un({client:q,path:{name:e},query:{profileId:t,runId:n,regionKey:r,marketKey:i,outcome:c===cd?void 0:c,q:v||void 0,sort:u,limit:sd,offset:(w-1)*sd}}),placeholderData:k}),E=[{value:Xe[`needs-work`],label:`Needs work`,count:a.needsWork},...o.map(e=>({value:e.filter,label:e.label,count:a[e.count]})),{value:Xe[`rival-ahead`],label:`Rival ahead`,count:a.rivalAhead},{value:Xe[`partly-checked`],label:`Partly checked`,count:a.partlyChecked},{value:Xe.failed,label:`Failed`,count:a.failed},{value:Xe.cancelled,label:`Not searched`,count:a.cancelled},{value:cd,label:`All`,count:a.queries}],D=[Xe[`partly-checked`],Xe.failed,Xe.cancelled],O=E.filter(e=>e.value===c||e.count>0||!D.includes(e.value)),A=O.find(e=>e.value===c)?.label??`All`,j=u===Ce.rank?`ascending`:u===Ce[`-rank`]?`descending`:null,M=u===Ce.query?`ascending`:u===Ce[`-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`:`${Au.format(T.data.total)} ${T.data.total===1?`query`:`queries`}: ${A}`;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-base font-semibold 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-[13px] text-secondary`,children:`Show`}),(0,$.jsx)(`select`,{"aria-label":`Show queries`,value:c,onChange:e=>l(e.target.value),className:`${Nu} min-w-0 sm:w-56`,children:O.map(e=>(0,$.jsxs)(`option`,{value:e.value,children:[e.label,` (`,Au.format(e.count),`)`]},e.value))})]}),(0,$.jsx)(No,{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)(Zu,{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:`font-medium text-heading`,children:`No queries match`}),(0,$.jsx)(J,{variant:`secondary`,className:`mt-4 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-sm`,children:[(0,$.jsxs)(`caption`,{className:`sr-only`,children:[`Queries: `,A]}),(0,$.jsx)(`thead`,{className:`bg-surface text-[13px] text-secondary`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(bd,{label:`Query`,align:`left`,sorted:M,onSort:()=>d(u===Ce.query?Ce[`-query`]:Ce.query)}),(0,$.jsx)(bd,{label:`Google rank`,align:`right`,sorted:j,onSort:()=>d(u===Ce.rank?Ce[`-rank`]:Ce.rank)}),(0,$.jsx)(`th`,{className:`px-4 py-3 text-left font-medium whitespace-nowrap`,children:`Top rival`}),(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)(Ed,{row:e,requested:s},`${e.marketKey}\u0000${e.queryId??e.queryText}\u0000${t}`))})]})}),(0,$.jsx)(Fo,{page:w,pageSize:sd,visibleRows:N.length,totalRows:T.data.total,onPageChange:e=>S({filterKey:b,page:e}),disabled:T.isFetching,itemLabel:`queries`,className:`text-[13px] [&_button]:min-h-11`})]}):(0,$.jsx)(`p`,{className:`py-8 text-sm text-secondary`,children:`Loading queries…`})]})}function Ed({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:Fu,children:[(0,$.jsx)(`p`,{className:`text-primary`,children:e.queryText}),(0,$.jsx)(`p`,{className:`mt-1 text-[13px] text-secondary`,children:e.marketLabel})]}),(0,$.jsx)(`td`,{className:Pu,children:(0,$.jsx)(Od,{row:e,requested:t})}),(0,$.jsx)(`td`,{className:`px-4 py-3 align-top text-[13px]`,children:(0,$.jsx)(kd,{row:e})}),(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-[13px] 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:4,className:`bg-surface-subtle px-4 pb-4 pt-3`,children:(0,$.jsx)(Ad,{row:e,requested:t})})})]})}function Dd(e){return e.outcome===we.failed||e.outcome===we.cancelled}function Od({row:e,requested:t}){return e.outcome===we.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===we.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===we[`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 kd({row:e}){if(Dd(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.competitors[0];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}),(0,$.jsxs)(`span`,{className:`tabular-nums text-secondary`,children:[`#`,t.rankOrganic]}),e.rivalAhead&&(0,$.jsx)(Y,{tone:`caution`,children:`Ahead`})]}):(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`None in top `,e.depth]})}function Ad({row:e,requested:t}){let n=`text-muted`,r=`mt-0.5 text-primary`,i=e.outcome===we.failed?`No result: the search failed`:e.outcome===we.cancelled?`No result: not searched`:`Not in the top ${e.depth}`;return(0,$.jsxs)(`div`,{className:`grid gap-x-8 gap-y-3 text-[13px] leading-relaxed 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)(to,{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:Iu}),(0,$.jsx)(`p`,{className:`${r} tabular-nums`,children:(0,$.jsx)(Ru,{value:e.rankAbsolute})})]}),e.searchStatus===Gt.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}`]})]}),!Dd(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)(Yu,{source:e.provenance})})]})}function jd({projectName:e,profileId:t,canRun:n,selectedRunId:r}){let[i,a]=(0,Q.useState)(r??null),[o,s]=(0,Q.useState)(null),c=C({...Gr({client:q,path:{name:e},query:{profileId:t}}),refetchInterval:e=>e.state.data?.runs.some(Lu)?2e3:!1}),l=C({...ar({client:q,path:{name:e,id:i??``}}),enabled:!!i,refetchInterval:e=>Lu(e.state.data)?2e3:!1}),u=S({...Br({client:q}),meta:{skipGlobalErrorToast:!0}}),d=async t=>{if(n&&!u.isPending){s(null);try{await u.mutateAsync({path:{name:e,id:t}})}catch(e){s(Xo(e))}}};if(c.error)return(0,$.jsx)(`div`,{className:`py-4`,children:(0,$.jsx)(Zu,{error:c.error,retry:()=>{c.refetch()}})});if(!c.data)return(0,$.jsx)(`p`,{role:`status`,className:`py-8 text-sm 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-sm`,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)(zu,{status:e.status}),(0,$.jsx)(`span`,{className:`text-sm`,children:$e(e.createdAt,Mu)})]}),(0,$.jsxs)(`p`,{className:`text-[13px] text-secondary`,children:[e.completedTasks,` of `,e.taskCount,` `,Uu(e),` completed`,e.failedTasks>0?` · ${e.failedTasks} failed`:``]})]}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsxs)(J,{variant:`ghost`,className:`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&&Lu(e)&&(0,$.jsx)(J,{variant:`secondary`,className:`min-h-11`,disabled:u.isPending||e.cancelRequested,onClick:kn(()=>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-[13px] text-secondary`,children:[(0,$.jsxs)(`p`,{className:`break-all`,children:[`Refresh `,e.id]}),(0,$.jsxs)(`p`,{children:[`Profile revision `,e.profileRevision,` · `,Hu(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)(Zu,{error:l.error,retry:()=>{l.refetch()}}):l.data?l.data.tasks.some(Wu)&&(0,$.jsx)(`ul`,{className:`space-y-3`,children:l.data.tasks.filter(Wu).map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{children:[Du[e.capability],e.searchText===null?e.target?` · ${e.target.value}`:``:` · “${e.searchText}” from ${e.locationLabel??`its market`}`,e.retried?` · retried once`:``]}),(0,$.jsx)(zu,{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)(Qu,{title:`No refreshes yet`,children:`Refresh this profile to collect its first saved results.`})}function Md({projectName:e,context:t,profile:n,id:r,onClose:i,onSaved:a}){let o=x(),[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??[K[`ranked-keywords`]]),[p,m]=(0,Q.useState)(n?.targets??[{kind:nt.domain,value:``,includeSubdomains:!0}]),[h,g]=(0,Q.useState)(n?.keywords.join(`
2
- `)??``),[v,y]=(0,Q.useState)(n?.locationCode.toString()??``),[b,C]=(0,Q.useState)(n?.languageCode??`en`),[w,T]=(0,Q.useState)(n?.limit.toString()??`100`),[E,D]=(0,Q.useState)(n?`${n.scope.kind}:${n.scope.key??``}`:`${Qe.project}:`),[O,k]=(0,Q.useState)(null),A=S({...Si({client:q}),meta:{skipGlobalErrorToast:!0}}),j=t.connections.find(e=>e.id===l),M=t.scopes.find(e=>`${e.kind}:${e.key??``}`===E),N=j?.capabilities.filter(e=>M?.capabilities?.includes(e)??!0)??[],P=d.filter(e=>N.includes(e)),F=P.includes(K[`ranked-keywords`])||P.includes(K[`domain-intelligence`])||P.includes(K[`market-rankings`]),I=P.includes(K[`ranked-keywords`]),L=(0,Q.useId)(),R=P.includes(K[`market-rankings`]),z=e=>e===K[`market-rankings`]?!n?.rankings||P.some(e=>e!==K[`market-rankings`]):R,ee=N.includes(K[`market-rankings`])?n?.rankings?`Market rankings use their own profile.`:`Set up market rankings with the CLI or API.`:null,B=async()=>{if(!t.access.canWrite||U()||an()||A.isPending)return;if(!M){k(`Choose a measurement scope.`);return}let i={name:s,connectionId:l,capabilities:P,targets:F?p:[],keywords:h.split(`
3
- `).map(e=>e.trim()).filter(Boolean),locationCode:Number(v),languageCode:b,limit:I?Number(w):n?.limit??100,scope:{kind:M.kind,...M.key?{key:M.key}:{},...M.planRevision===void 0?{}:{expectedPlanRevision:M.planRevision}},...P.includes(K[`market-rankings`])&&n?.rankings?{rankings:n.rankings}:{}},c=zt.safeParse(i);if(!c.success)k(c.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(` `));else{k(null);try{await A.mutateAsync({path:{name:e,id:r},body:c.data}),await o.fetchQuery(qn({client:q,path:{name:e}})),a(r)}catch(e){k(Xo(e))}}},V=(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(),B()},children:[(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsx)(`h3`,{className:`font-medium text-heading`,children:n?`Edit profile`:`New profile`}),(0,$.jsx)(J,{type:`button`,variant:`ghost`,className:`size-11 p-0`,"aria-label":`Close profile editor`,onClick:i,children:(0,$.jsx)(_,{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-sm`,children:[(0,$.jsx)(`span`,{children:`Profile name`}),(0,$.jsx)(`input`,{className:Nu,required:!0,maxLength:120,value:s,onChange:e=>c(e.target.value),autoFocus:!0})]}),(0,$.jsxs)(`label`,{className:`space-y-1.5 text-sm`,children:[(0,$.jsx)(`span`,{children:`Source`}),(0,$.jsxs)(`select`,{className:Nu,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-sm sm:col-span-2`,children:[(0,$.jsx)(`span`,{children:`Measurement scope`}),(0,$.jsxs)(`select`,{className:Nu,required:!0,value:M?E:``,onChange:e=>{let n=t.scopes.find(t=>`${t.kind}:${t.key??``}`===e.target.value);D(e.target.value),f(e=>e.filter(e=>n?.capabilities?.includes(e)??!0))},children:[(0,$.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}`))]}),M?.reason?(0,$.jsx)(`span`,{className:`block text-[13px] text-secondary`,children:M.reason}):M&&!M.supported&&(0,$.jsx)(`span`,{className:`block text-[13px] text-secondary`,children:`Domain data is not supported for this scope.`})]})]}),(0,$.jsxs)(`fieldset`,{children:[(0,$.jsx)(`legend`,{className:`mb-2 text-sm`,children:`Collect`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-x-6 gap-y-2`,children:Object.values(K).map(e=>{let t=z(e);return(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-sm`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:P.includes(e),disabled:!N.includes(e)||t,"aria-describedby":t&&ee?L:void 0,onChange:t=>f(n=>t.target.checked?[...n,e]:n.filter(t=>t!==e))}),Du[e]]},e)})}),M?.capabilities&&(0,$.jsx)(`p`,{className:`mt-1 text-[13px] text-secondary`,children:`Available datasets follow this scope and source. Changing scope clears unsupported selections.`}),ee&&(0,$.jsx)(`p`,{id:L,className:`mt-1 text-[13px] text-secondary`,children:ee})]}),F&&(0,$.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,$.jsx)(`legend`,{className:`mb-2 text-sm`,children:`Targets`}),(0,$.jsx)(`p`,{className:`text-[13px] text-secondary`,children:R?`Market rankings report the Google rank of one target: one of this project’s own domains.`:`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-sm`,children:[(0,$.jsxs)(`span`,{className:`sr-only`,children:[`Target `,t+1]}),(0,$.jsx)(`input`,{className:Nu,value:e.value,placeholder:`example.com`,"aria-label":`Target ${t+1}`,onChange:e=>V(t,{value:e.target.value}),required:!0,maxLength:253})]}),(0,$.jsxs)(`label`,{className:`space-y-1 text-sm`,children:[(0,$.jsxs)(`span`,{className:`sr-only`,children:[`Target `,t+1,` kind`]}),(0,$.jsxs)(`select`,{className:Nu,"aria-label":`Target ${t+1} kind`,value:e.kind,onChange:e=>V(t,{kind:e.target.value,includeSubdomains:e.target.value===nt.domain}),children:[(0,$.jsx)(`option`,{value:nt.domain,children:`Domain + subdomains`}),(0,$.jsx)(`option`,{value:nt.host,children:`Exact host`})]})]}),(0,$.jsx)(J,{type:`button`,variant:`ghost`,className:`min-h-11`,onClick:()=>m(e=>e.filter((e,n)=>n!==t)),"aria-label":`Remove target ${t+1}`,children:`Remove`})]},t)),(0,$.jsx)(J,{type:`button`,variant:`secondary`,className:`min-h-11`,disabled:p.length>=(R?1:20),onClick:()=>m(e=>[...e,{kind:nt.domain,value:``,includeSubdomains:!0}]),children:`Add target`})]}),P.includes(K[`keyword-metrics`])&&(0,$.jsxs)(`label`,{className:`block space-y-1.5 text-sm`,children:[(0,$.jsx)(`span`,{children:`Searches`}),(0,$.jsx)(`textarea`,{className:`${Nu} min-h-28`,value:h,onChange:e=>g(e.target.value),placeholder:`One search per line`}),(0,$.jsx)(`span`,{className:`block text-[13px] text-secondary`,children:`Up to 700 searches to measure, each at most 10 words and 80 characters.`})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 ${I?`sm:grid-cols-3`:`sm:grid-cols-2`}`,children:[(0,$.jsxs)(`label`,{className:`space-y-1.5 text-sm`,children:[(0,$.jsx)(`span`,{children:`Provider location code`}),(0,$.jsx)(`input`,{className:Nu,type:`number`,min:1,step:1,required:!0,value:v,onChange:e=>y(e.target.value)}),(0,$.jsx)(`span`,{className:`block text-[13px] text-secondary`,children:R?`Used only when the project has no markets or locations.`:`The source’s location identifier.`})]}),(0,$.jsxs)(`label`,{className:`space-y-1.5 text-sm`,children:[(0,$.jsx)(`span`,{children:`Language code`}),(0,$.jsx)(`input`,{className:Nu,required:!0,minLength:2,maxLength:10,value:b,onChange:e=>C(e.target.value)})]}),I&&(0,$.jsxs)(`label`,{className:`space-y-1.5 text-sm`,children:[(0,$.jsx)(`span`,{children:`Ranked searches per target`}),(0,$.jsx)(`input`,{className:Nu,type:`number`,min:1,max:1e3,step:1,required:!0,value:w,onChange:e=>T(e.target.value)})]})]}),O&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-secondary`,children:O}),(0,$.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(J,{type:`submit`,className:`min-h-11`,disabled:A.isPending||!j||!P.length,children:A.isPending?`Saving…`:`Save profile`}),(0,$.jsx)(J,{type:`button`,variant:`ghost`,className:`min-h-11`,onClick:i,children:`Cancel`})]})]})}var Nd=[`non-brand`,`branded`,`unclassified`],Pd={"non-brand":`Non-brand`,branded:`Branded`,unclassified:`Unclassified`};function Fd(e,t){return t<=0?`neutral`:e/t*100>=70?`positive`:`caution`}function Id(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 Nd.map(e=>r.get(e)).filter(e=>e!==void 0&&e.queries>0)}function Ld(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 Rd={engine:`engine no longer configured`,query:`query no longer tracked`},zd={"non-brand":`non-brand queries`,branded:`branded queries`,unclassified:`unclassified queries`},Bd=`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 Vd(e,t,n){return e===1?t:n}function Hd({projectName:e,classify:t,hasCompetitors:n,providerScores:r=[]}){let i=(0,Q.useId)(),[a,o]=(0,Q.useState)(`non-brand`),s=C({...Nr({client:q,path:{name:e}}),staleTime:Pn}),c=s.data??null,l=c?.status===`ready`?Id(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-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Could not load engine results: `,Xo(s.error)]}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{s.refetch()},children:`Retry`})]}):c?c.status===`no-data`?d=(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:c.reason===`no-queries`?`Add queries to start tracking AI citations.`:He()?Ao:`Engine results appear after the first AI Visibility check.`}):u||(d=(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No engine answers yet.`})):d=(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:`Loading engine results…`});let f=[];if(u&&c?.status===`ready`){let e=Vd(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:[ra(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}),` `,Vd(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]}),` `,Vd(i,`engine`,`engines`),`, named by `,(0,$.jsxs)(`strong`,{children:[n,` of `,i]})]}));for(let e of r)f.push((0,$.jsxs)($.Fragment,{children:[ra(e.provider),e.model?` (${e.model})`:``,` citation rate:`,` `,(0,$.jsx)(`strong`,{children:W(e.score,oe.percent)}),`, `,(0,$.jsxs)(`strong`,{children:[e.cited,` of `,e.total]}),` `,Vd(e.total,`answer`,`answers`),`, all queries`]}));for(let e of u.competitorGaps)f.push(`"${e.query}" (${ra(e.provider)}): ${e.competitors.join(`, `)} cited instead of you`);for(let e of Ld(c))f.push(`"${e.query}" (${ra(e.provider)}): ${e.competitors.join(`, `)} cited instead of you, not counted (${Rd[e.reason]})`)}let p=c?.status===`ready`?c.summary.latestRunAt:null,m=(e,t)=>u?.key===`non-brand`?lo[Fd(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:Bd})]}),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 `,hn(p)]}):null,l.length>1?(0,$.jsx)(ys,{label:`Query type`,className:`flex-wrap`,options:l.map(e=>({value:e.key,label:Pd[e.key]})),value:u.key,onChange:o}):u?(0,$.jsx)(`span`,{className:`mention-share-class`,children:Pd[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, ${zd[u.key]}`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{children:[(0,$.jsxs)(`th`,{scope:`col`,children:[`Of `,u.queries,` `,Vd(u.queries,`query`,`queries`)]}),u.engines.map(e=>(0,$.jsx)(`th`,{scope:`col`,children:ra(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,` `,Vd(u.answers,`answer`,`answers`)]}),(0,$.jsxs)(`span`,{className:`sr-only`,children:[` · `,zd[u.key]]})]}):(0,$.jsx)(`span`,{className:`text-[13px] text-secondary`,children:`No competitors tracked`})]})]}))}),(0,$.jsx)(vs,{items:f})]})}var Ud={[vt.queued]:{word:`queued`,tone:`text-secondary`},[vt.running]:{word:`running`,tone:`text-info-300`},[vt.completed]:{word:`completed`,tone:`text-secondary`},[vt.partial]:{word:`partial`,tone:`text-caution-400`},[vt.failed]:{word:`failed`,tone:`text-negative-400`},[vt.cancelled]:{word:`cancelled`,tone:`text-secondary`}};function Wd({runs:e,projectName:t,collapsed:n=!1}){let i=(0,Q.useId)(),a=new Set(e.map(e=>e.location??``)).size>1,o=e.some(e=>e.kind!==ht[`answer-visibility`]),s=e.map(e=>`${e.startedAt}: ${e.summary}.${e.statusDetail?` ${e.statusDetail}`:``}`);return(0,$.jsx)(`section`,{className:`overview-brief`,"aria-labelledby":i,children:(0,$.jsxs)(`details`,{className:`av-history`,open:!n||void 0,children:[(0,$.jsxs)(`summary`,{className:`av-card-head`,children:[(0,$.jsx)(`h2`,{id:i,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)(r,{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-sm text-secondary`,children:`No checks yet.`}):(0,$.jsxs)(`table`,{className:`av-grid av-grid-dense av-grid-sweeps`,"aria-labelledby":i,children:[(0,$.jsx)(`thead`,{className:`sr-only`,children:(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`col`,children:`Started`}),o?(0,$.jsx)(`th`,{scope:`col`,children:`Type`}):null,(0,$.jsx)(`th`,{scope:`col`,children:`Trigger`}),a?(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=Ud[e.status],r=e.status===vt.partial||e.status===vt.failed;return(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,className:`av-row-label tabular-nums`,children:(0,$.jsx)(ea,{run:e,projectName:t,className:`av-link`,label:e.opensSeoWorkspace?`View SEO refresh from ${e.startedAt}`:`View the ${e.startedAt} check`,children:e.startedAt})}),o?(0,$.jsx)(`td`,{className:`text-[13px] text-secondary`,children:e.kindLabel}):null,(0,$.jsx)(`td`,{className:`text-[13px] text-secondary`,children:e.triggerLabel}),a?(0,$.jsx)(`td`,{className:`text-[13px] text-secondary`,children:e.location??`No location`}):null,(0,$.jsx)(`td`,{className:`text-[13px] 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-[13px] text-secondary`,children:e.statusDetail}):null]})]},e.id)})})]})}),(0,$.jsx)(vs,{items:s})]})})}var Gd=[{value:`7d`,label:`7 days`},{value:`30d`,label:`30 days`},{value:`90d`,label:`90 days`},{value:`all`,label:`All`}],Kd=`Measured answers`,qd=`Close answers`,Jd={"non-brand":`Non-brand queries`,branded:`Branded queries`,unknown:`Unclassified queries`},Yd={"non-brand":`non-brand queries`,branded:`branded queries`,unknown:`unclassified queries`},Xd={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.`},Zd={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.`},Qd=`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.`,$d=`min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`;function ef(e){return e.kind===`project`?`Whole site`:e.kind===`group`?`${e.label} · Group`:e.kind===`market`?`${e.label} · Market`:e.label}function tf(e){return e.reason===`identity-ambiguous`?En.ambiguous:e.reason===`not-applicable`?`Not applicable`:`Not measured`}function nf({value:e,signal:t}){if(e.rate===null)return(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:tf(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:W(e.rate)}),(0,$.jsxs)(`span`,{className:`text-sm 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 rf({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 af(e,t){if(!e||e.state===`unavailable`)return null;let n=e[t];if(n.state===`unavailable`)switch(n.reason){case be[`previous-unavailable`]:return{text:Xd.previousUnavailable,tone:`text-secondary`};case be[`current-unavailable`]:case be[`not-applicable`]:return null}let{direction:r,magnitude:i}=tt(n.delta);switch(r){case`up`:return{text:Xd.up(i),tone:`text-positive`};case`down`:return{text:Xd.down(i),tone:`text-negative`};case`none`:return{text:Xd.none,tone:`text-secondary`}}}function of(e,t){let n=Pi(e);return t!==null&&Ni(n)===Ni(Pi(t))?Bi(n):Mi(n)}function sf(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 cf(e,t){if(!e)return null;if(e.state===`unavailable`){let n=e.previousRun?of(e.previousRun.createdAt,t):null;switch(e.reason){case ue[`no-selected-run`]:return null;case ue[`no-previous-run`]:return Xd.noPreviousRun;case ue[`definition-changed`]:return Xd.definitionChanged(n);case ue[`model-changed`]:return Xd.modelChanged(n);case ue[`legacy-unknown`]:return Xd.legacyUnknown;case ue[`partial-run`]:return Xd.partialRun;case ue[`scoped-run`]:return Xd.scopedRun}}return Xd.comparedWith(of(e.previousRun.createdAt,t))}function lf(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 uf({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-sm text-secondary`,children:[(0,$.jsx)(`span`,{children:e}),(0,$.jsx)(X,{text:t})]}),n.rate===null?(0,$.jsxs)(`dd`,{className:`text-lg text-secondary`,children:[tf(n),s]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`dd`,{className:`report-headline-value`,children:[(0,$.jsx)(`span`,{className:`text-3xl font-semibold tabular-nums text-heading`,children:W(n.rate)}),s,o?(0,$.jsx)(`span`,{className:`text-sm ${o.tone}`,children:o.text}):null]}),(0,$.jsx)(`dd`,{className:`text-sm 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 df={otherQueries:`Other queries`},ff={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 pf(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(` · `)||df.otherQueries;return r.sort((e,t)=>e.marketLabel.localeCompare(t.marketLabel)||e.query.localeCompare(t.query))}var mf={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 hf({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?mf.savedCite(r.citedAnswers,r.answers,r.citedTargetKeys.map(i).join(`, `)):mf.savedCiteNone(e.targetKeys.length===1?i(e.targetKeys[0]):null);return(0,$.jsxs)($.Fragment,{children:[n?(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:mf.partlySaved(r.answers)}):null,(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:a})]})}function gf({value:e,signal:t,singleAnswer:r,row:i,targetLabels:o}){if(r&&e.denominator===1&&e.unattributed===void 0&&e.unchecked===void 0&&(e.rate===0||e.rate===1)){let t=e.rate===1;return(0,$.jsxs)(`span`,{className:`inline-flex items-center gap-2 text-sm ${t?`text-positive`:`text-secondary`}`,children:[t?(0,$.jsx)(a,{size:16,"aria-hidden":`true`}):(0,$.jsx)(n,{size:16,"aria-hidden":`true`}),t?`Yes`:`No`]})}let s=t===`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)(nf,{value:e,signal:t}),s?(0,$.jsx)(hf,{row:s,targetLabels:o??new Map,showCount:e.rate===null}):null]}),s?(0,$.jsx)(X,{text:mf.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 _f({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 vf({group:e,queryClass:t,advanced:n,targetLabels:r,marketHeading:i,onViewAnswers:a}){let o=e.rows[0],s=e=>JSON.stringify([...e.targetKeys].sort()),c=e.rows.every(e=>s(e)===s(o)),l=e.rows.every(e=>e.location===o.location),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-base font-semibold 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-base font-medium text-heading`,children:e.query}),(0,$.jsx)(`div`,{className:`text-sm font-normal`,children:(0,$.jsx)(Ki,{showLabel:!0,queryId:o.queryId,sourceSnapshotIds:e.rows.flatMap(e=>e.sourceSnapshotIds??[]),queryClass:t===`unknown`?null:t,location:l?o.location:void 0})})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-5 text-sm font-normal text-secondary`,children:[n&&c?(0,$.jsx)(_f,{targetKeys:o.targetKeys,labels:r}):null,l?(0,$.jsx)(`span`,{children:d(o.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:`font-medium text-heading`,children:ra(e.provider)}),(0,$.jsx)(`span`,{className:`block break-words text-sm text-secondary`,children:e.model??`Model not recorded`}),n&&!c?(0,$.jsx)(`div`,{className:`mt-1 text-sm text-secondary`,children:(0,$.jsx)(_f,{targetKeys:e.targetKeys,labels:r})}):null,l?null:(0,$.jsx)(`span`,{className:`mt-1 block text-sm text-secondary`,children:d(e.location)}),(0,$.jsx)(Qi,{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)(gf,{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)(gf,{value:e.citationCoverage,signal:`cited`,singleAnswer:e.answerCount===1,row:e,targetLabels:r})]}),(0,$.jsx)(`td`,{className:`measurement-result-action`,children:(0,$.jsxs)(J,{variant:`ghost`,className:`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)(u,{size:16,"aria-hidden":`true`})]})})]},JSON.stringify([e.provider,e.model,e.location])))]})}var yf=`Cited counts only answers whose sources could be checked.`,bf=[{key:`mentioned`,label:`Mentioned`,color:ki[1],dashed:!1},{key:`cited`,label:`Cited`,color:zi.positive,dashed:!0}],xf=`var(--chart-tooltip-bg)`;function Sf({population:e}){let t=(0,Q.useId)(),[n,r]=(0,Q.useState)({mentioned:!0,cited:!0}),i=bf.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)?[yf]:[]];if(s.length===0)return(0,$.jsx)(`p`,{className:`py-6 text-sm 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-sm text-secondary`,children:[(0,$.jsx)(`legend`,{className:`sr-only`,children:`Trend legend`}),bf.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?xf:e.color,stroke:e.color,strokeWidth:`2`})]}),e.label]},e.key))]}),u.length>0&&(0,$.jsx)(`p`,{id:t,className:`pb-3 text-sm 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":`${Jd[e.queryClass]} mention and citation trend`,children:(0,$.jsx)(P,{width:`100%`,height:`100%`,children:(0,$.jsxs)(z,{data:s,margin:{top:8,right:8,bottom:0,left:0},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`createdAt`,type:`number`,scale:`time`,domain:[`dataMin`,`dataMax`],tick:Ri,tickLine:!1,axisLine:{stroke:Ui},tickFormatter:e=>new Date(Number(e)).toLocaleDateString(void 0,{month:`short`,day:`numeric`}),minTickGap:24}),(0,$.jsx)(L,{domain:[0,1],tick:Ri,tickLine:!1,axisLine:!1,width:48,tickFormatter:e=>W(Number(e))}),(0,$.jsx)(j,{...Hi,formatter:e=>typeof e==`number`?W(e):`Not measured`,labelFormatter:e=>new Date(Number(e)).toLocaleDateString()}),c.map(e=>(0,$.jsxs)(Q.Fragment,{children:[n.mentioned?(0,$.jsx)(R,{type:`linear`,dataKey:`mentioned-${e}`,name:`Mentioned`,stroke:ki[1],strokeWidth:2,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:ki[1]}}):null,n.cited?(0,$.jsx)(R,{type:`linear`,dataKey:`cited-${e}`,name:`Cited`,stroke:zi.positive,strokeWidth:2,strokeDasharray:`6 4`,connectNulls:!1,isAnimationActive:!1,dot:{r:3,fill:xf,strokeDasharray:`none`}}):null]},e))]})})})]}):(0,$.jsx)(`p`,{className:`py-6 text-sm 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":`${Jd[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)(nf,{value:e.mentionCoverage,signal:`mentioned`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(nf,{value:e.citationCoverage,signal:`cited`})}),(0,$.jsx)(`td`,{children:e.continuity.state.replaceAll(`-`,` `)})]},e.runId))})]})})]})}function Cf(e,t){return t?e?.populations.find(e=>[...e.queries.items,...e.evidence.items].some(e=>e.queryKey===t)):void 0}function wf(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=Cf(r,t)??Cf(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 Tf={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: ${ra(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(` `)},Ef={measurementProvider:void 0,measurementModel:void 0,measurementLocation:void 0,measurementFrom:void 0,measurementTo:void 0,measurementRunId:void 0},Df=`min-h-11 rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`;function Of(e,t){return e&&t?Tf.dateRange(e.slice(0,4)===t.slice(0,4)?Wi(e):Ii(e),Ii(t)):e?Tf.dateFrom(Ii(e)):t?Tf.dateThrough(Ii(t)):null}function kf(e,t){let n=[];e.provider&&n.push({key:`engine`,label:Tf.engine(e.provider),patch:{measurementProvider:void 0}}),e.model&&n.push({key:`model`,label:Tf.model(e.model),patch:{measurementModel:void 0}}),e.location&&n.push({key:`location`,label:e.location===`none`?Tf.noLocation:Tf.location(e.location),patch:{measurementLocation:void 0}});let r=Of(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?Tf.resultsFrom(Mi(Pi(r.createdAt))):Tf.resultsFromSelectedSweep,patch:{measurementRunId:void 0}})}return n}function Af(e,t,n){return t===``||e.some(e=>e.value===t)?e:[...e,{value:t,label:n}]}function jf({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,h=m.measurement,g=wf(e,t.queryKey,t.answer),v=t.queryClass===`all`?g.queryClass:t.queryClass,y=kf(t,e),b=t.measurementScope===`property`?t.measurementScopeKey:void 0,x=b?i?.({id:b,label:ss(e.scopeOptions,t)?.label??b}):null,S=t.provider??``,C=t.model??``,w=t.location??``,T=t.measurementRunId??``,E=!s&&h.awaitingSweep&&h.measuredRevision!==null&&!m.run.explicit&&t.measurementRunId===void 0&&t.revision===void 0&&t.to===void 0,D=()=>u.current?.focus(),O=(e,t,r,i,a)=>(0,$.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-sm font-medium text-heading`,children:e}),a?(0,$.jsx)(X,{text:a}):null]}),(0,$.jsx)(`select`,{id:`${d}-${t}`,className:$d,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-sm font-medium text-heading`,children:e}),(0,$.jsx)(`input`,{id:`${d}-${t}`,type:`date`,className:$d,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-sm font-medium text-heading`,children:Tf.queryType}),(0,$.jsxs)(`select`,{"aria-label":Tf.queryType,className:Df,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)(Y,{tone:h.state===`measured`?`positive`:`neutral`,children:h.state===`measured`?`Complete`:h.state===`partial`?`Partial`:`Not measured`}),h.completedAt?(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:Mi(Pi(h.completedAt))}):null]})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-3`,children:[(0,$.jsx)(J,{ref:u,type:`button`,variant:`outline`,className:`min-h-11`,"aria-expanded":c,"aria-controls":f,onClick:()=>l(e=>!e),children:Tf.filters(y.length)}),y.map(e=>(0,$.jsxs)(J,{type:`button`,variant:`outline`,className:`visibility-filter-token min-h-11 rounded-md text-sm`,"aria-label":Tf.removeFilter(e.label),onClick:()=>{n(e.patch),D()},children:[(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:e.label}),(0,$.jsx)(_,{size:16,className:`shrink-0`,"aria-hidden":`true`})]},e.key)),x,r?(0,$.jsx)(J,{type:`button`,variant:`outline`,className:`min-h-11`,onClick:r,children:Tf.manageQueries}):null]})]}),(0,$.jsxs)(`div`,{id:f,role:`group`,"aria-label":Tf.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,Af([{value:``,label:`All engines`},...p.providers.map(e=>({value:e,label:ra(e)}))],S,ra(S))),O(`Requested search location`,`measurementLocation`,w,Af([{value:``,label:`All requested locations`},...p.locations.flatMap(e=>e.kind===`exact`?[{value:e.value,label:e.value}]:e.kind===`none`?[{value:`none`,label:Tf.noLocation}]:[])],w,w===`none`?Tf.noLocation:w)),O(`AI model`,`measurementModel`,C,Af([{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,Af([{value:``,label:`Latest saved check`},...[...g.trend].reverse().map(e=>({value:e.runId,label:new Date(e.createdAt).toLocaleString()}))],T,`Selected check`),`Choose a saved AI Visibility check to view its results. No new check starts.`)]}),(0,$.jsx)(`div`,{className:`flex justify-end pb-3`,children:(0,$.jsx)(J,{type:`button`,variant:`ghost`,className:`min-h-11`,disabled:y.length===0,onClick:()=>{n({...Ef}),D()},children:Tf.clearFilters})})]}),E?(0,$.jsx)(`p`,{role:`status`,className:`border-b border-default py-3 text-sm text-secondary`,children:Tf.trackingChanged(a?Bi(Pi(a)):null,h.completedAt?Bi(Pi(h.completedAt)):null,o??null)}):null]})}function Mf({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=wf(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="${Kd}"]`);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=ef(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-sm text-secondary`,children:[(0,$.jsx)(`p`,{children:`These saved results aren't separated by query type.`}),(0,$.jsx)(J,{variant:`outline`,onClick:()=>n({queryClass:`all`,measurementQueryKey:void 0}),children:`View all saved results`})]}):null,[g].map(t=>{let s=pf(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=Yd[t.queryClass],_=cf(t.comparison,sf(x,t));return(0,$.jsxs)(`section`,{"aria-label":Jd[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:Jd[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:lf(t.summary,_)}),(0,$.jsx)(X,{text:Xd.explanation})]})]}),(0,$.jsxs)(`dl`,{className:`report-headline mt-3`,"data-columns":m?3:2,"aria-label":`${Jd[t.queryClass]} headline results`,children:[(0,$.jsx)(uf,{label:m?`Answers mentioning a property`:`Mentioned answers`,help:x.mode===`advanced`?Zd.advancedMention:Zd.simpleMention,value:t.summary.mentionCoverage,signal:`mentioned`,unit:`answers`,classNoun:g,change:af(t.comparison,`mentionCoverage`)}),(0,$.jsx)(uf,{label:m?`Answers citing a property`:`Cited answers`,help:x.mode===`advanced`?Zd.advancedCitation:Zd.simpleCitation,value:t.summary.citationCoverage,signal:`cited`,unit:`answers`,classNoun:g,change:af(t.comparison,`citationCoverage`)}),m?(0,$.jsx)(uf,{label:`Properties mentioned`,help:Zd.propertyReach,value:t.summary.propertyReach,signal:`mentioned`,unit:`properties`,classNoun:g,change:af(t.comparison,`propertyReach`)}):null]}),(0,$.jsx)(io,{queryClass:x.queryClass,manage:!0}),(0,$.jsx)(Sf,{population:t}),m&&(t.breakdown.groups.length>0||t.breakdown.properties.length>0)?(0,$.jsx)(Nf,{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":`${Jd[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-sm text-secondary`,children:n})]},e))}),t.summary.notMeasuredUnchecked?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:mf.outcomes(t.summary.notMeasuredUnchecked)}):null]}),(0,$.jsx)(X,{text:Qd})]})]}):null,(0,$.jsxs)(`details`,{className:`visibility-disclosure`,"data-query-results":t.queryClass,"aria-label":`${Jd[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 ${Jd[t.queryClass]}`,placeholder:`Search queries`,className:`${$d} 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":`${Jd[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)(vf,{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-sm text-secondary`,children:`No measured queries match this selection.`}):(0,$.jsxs)(`p`,{className:`mt-3 text-sm 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)(J,{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":Kd,"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-base font-semibold text-heading [overflow-wrap:anywhere]`,children:p??`Answers`}),(0,$.jsx)(J,{variant:`ghost`,className:`min-h-11`,onClick:T,children:qd})]}),l?(0,$.jsx)(`p`,{role:`status`,className:`py-4 text-sm text-secondary`,children:`Loading saved answers…`}):u?(0,$.jsxs)(`div`,{role:`alert`,className:`py-4 text-sm text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`Saved answers unavailable: `,u]}),d?(0,$.jsx)(J,{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-sm text-heading`,children:ra(e.provider)}),e.model?(0,$.jsx)(`span`,{className:`text-[13px] text-secondary`,children:e.model}):null,(0,$.jsx)(`span`,{className:`text-[13px] text-secondary`,children:e.location===null?Tf.noLocation:Tf.location(e.location)}),(0,$.jsx)(`span`,{className:`text-[13px] text-secondary`,children:new Date(e.createdAt).toLocaleDateString()}),(0,$.jsx)(Y,{tone:`neutral`,children:e.mentioned===null?e.mentionUnavailableReason===`identity-ambiguous`?En.ambiguous:`Mention not checked`:e.mentioned?`Mentioned`:`Not mentioned`}),(0,$.jsx)(Y,{tone:`neutral`,children:e.cited===null?`Citation not checked`:e.cited?`Cited`:`Not cited`})]}),(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(Vo,{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-sm text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:[Jo,` (`,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)(to,{url:e})},e))})]}):null]},e.answerId)),w(t).items.length===0?(0,$.jsx)(`p`,{className:`py-4 text-sm 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)(J,{variant:`outline`,onClick:()=>f(w(t).nextCursor),children:`Next answers`}):null]})]}):null]})]}),(0,$.jsxs)(`details`,{className:`visibility-disclosure`,"aria-label":`${Jd[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-sm text-secondary`,children:`Competitor rates unavailable for this historical definition.`}):t.competitors.length===0?(0,$.jsx)(`p`,{className:`text-sm 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)(nf,{value:e.mentionCoverage,signal:`mentioned`})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(nf,{value:e.citationCoverage,signal:`cited`})})]},e.domain))})]})}),t.observedCompetitors.length>0?(0,$.jsxs)(`details`,{className:`mt-4 text-sm`,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 Nf({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=Io({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)(J,{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:`${$d} 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)(nf,{value:e.mentionCoverage,signal:`mentioned`}),(0,$.jsx)(rf,{value:e.mentionCoverage})]}),(0,$.jsxs)(`td`,{children:[(0,$.jsx)(nf,{value:e.citationCoverage,signal:`cited`}),(0,$.jsx)(rf,{value:e.citationCoverage})]})]},e.id))})]})}),u.rows.length===0?(0,$.jsxs)(`p`,{className:`py-3 text-sm text-secondary`,children:[`No `,c,` match this search.`]}):null,(0,$.jsx)(Fo,{page:u.page,pageSize:u.pageSize,visibleRows:u.rows.length,totalRows:u.totalRows,itemLabel:c,onPageChange:u.setPage})]})}function Pf(e,t,{enabled:n}){return C({..._r({client:q,path:{name:e},query:la(t)}),enabled:n,staleTime:In,retry:!1,placeholderData:k})}function Ff(e,t){return t&&e.selection.mode===`simple`&&e.selection.measurement.state===`not-measured`}function If({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=x(),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=C({..._r({client:q,path:{name:e},query:{...la(t),cursor:a,search:s||void 0}}),staleTime:In,retry:!1,placeholderData:k}),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=C({..._r({client:q,path:{name:e},query:{...m,cursor:l?.selection===h?l.cursor:void 0}}),enabled:!!t.queryKey&&!!p.data&&!p.isPlaceholderData,retry:!1});if((0,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&&!Cf(p.data,t.queryKey)&&!g.data)return;let r=wf(p.data,t.queryKey,t.answer,g.data);if(!a&&!s){let{queryKey:n}=_r({client:q,path:{name:e},query:la({...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&&Ff(p.data,i))return(0,$.jsx)($.Fragment,{children:r});if(p.error){let e=ze(ft(p.error)),t=e?.reason===Ee[`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-sm text-secondary`,children:t?ff.retiredMarket:e?ff.retiredScope:ke(p.error)}),t?(0,$.jsx)(J,{variant:`outline`,onClick:()=>{o(void 0),n({measurementMarketKey:void 0})},children:ff.showAllMarkets}):e?(0,$.jsx)(J,{variant:`outline`,onClick:()=>{o(void 0),n({measurementScope:`project`,measurementScopeKey:void 0})},children:ff.showWholeSite}):(0,$.jsx)(J,{variant:`outline`,onClick:()=>{o(void 0),p.refetch()},children:`Retry`})]})}return p.data?(0,$.jsx)(`div`,{"aria-busy":p.isFetching,children:(0,$.jsx)(Mf,{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?ke(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 Lf({projectName:e,selection:t,onSelectionChange:n,onManageQueries:r,renderPropertyLink:i,trackingChangedAt:a,nextSweepDate:o,fallback:s,showUnmeasuredFallback:c=!1}){let l=Pf(e,t,{enabled:!0}),u=l.error?void 0:l.data,d=!l.isPlaceholderData&&u?.selection.availability.state===`available`?u.selection.run.id:null;_a(d,null);let f=!(!u||u.selection.availability.state!==`available`||Ff(u,c));return(0,$.jsxs)($.Fragment,{children:[f?(0,$.jsx)(jf,{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)(ya,{})}):null,(0,$.jsx)(If,{projectName:e,selection:t,onSelectionChange:n,fallback:s,showUnmeasuredFallback:c},`${e}:${JSON.stringify({...t,queryKey:void 0,answer:void 0})}`)]})}var Rf=[{value:`byProvider`,label:`By engine`},{value:`overall`,label:`All engines`}],zf=[{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.`}],Bf=[{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.`}],Vf=ki[2],Hf=ki[4],Uf=`var(--chart-tooltip-bg)`,Wf={up:`text-positive-400`,down:`text-negative-400`,none:`text-muted`};function Gf({direction:e,magnitude:t}){switch(e){case`up`:return`up ${t} points`;case`down`:return`down ${t} points`;case`none`:return`no change`}}function Kf(e){return e.direction===`none`?`no change over the period`:`${Gf(e)} over the period`}function qf(e){return e===`__cited__`||e===`__mentioned__`||e===`__mentionShare__`}function Jf(e){return e===`__cited__`?`Cited`:e===`__mentioned__`?`Mentioned`:e===`__mentionShare__`?`Mention share`:ra(e)}function Yf(e,t){return e===`__cited__`?zi.positive:e===`__mentioned__`?ki[1]:e===`__mentionShare__`?Vf:Oi(ro(e),t)}function Xf(e){return e===`non-brand`?`non-brand answers`:`all answers`}function Zf(e){return e===`cited`?`Cited`:e===`mentionShare`?`Mention share`:`Mentioned`}function Qf(e,t){return e===`mentionShare`?`Mention share in ${Xf(t)}`:Zf(e)}function $f(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 ep(e){return e===`cited`?`citationRate`:`mentionRate`}function tp(e,t){return t===`cited`?e.cited:e.mentionedCount}function np(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 rp(e,t){if(t===`mentionShare`){let{projectMentionSnapshots:t,competitorMentionSnapshots:n}=e.mentionShare;return`${t} of ${t+n} tracked-brand mentions`}return`${tp(e,t)} of ${e.total} answers`}function ip(e,t){if(t===void 0)return null;let n=String(t);return e.find(e=>e.startDate===n)??null}function ap(e){let t=Yi(e);return t===null?[]:Object.entries(t).sort(([e],[t])=>ro(e).localeCompare(ro(t))).map(([e,t])=>`${ra(e)}: ${To(t)}`)}function op(e,t){return new Date(e).toDateString()===new Date(t).toDateString()}function sp(e){return`${e} ${e===1?`query`:`queries`}`}function cp(e){let{added:t,removed:n}=e;return[...t.length>0?[`${sp(t.length)} added`]:[],...n.length>0?[`${t.length>0?n.length:sp(n.length)} removed`]:[]].join(`, `)}function lp(e,t){let n=ja(e),r=Ea(e),i=Sa(e,t);if(!n||!r||!i)return null;let a=ma(i.moves),o=op(n.start,n.end),s=e=>hn(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 up(e,t,n){let r=lp(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?`, `:``,cp(e),` `,(0,$.jsx)(`strong`,{children:Da(Pi(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 dp=`Queries changed`;function fp(e){let t=ma(e.moves);return t?`${dp}: ${t} between the first and latest points, so the change compares different queries.`:`${dp}: the first and latest points have answers for ${e.firstCount} and ${e.latestCount} queries, so the change compares different queries.`}function pp(e){return e.replace(/ /g,`\xA0`)}function mp({state:e,from:t=!1}){return(0,$.jsx)(`span`,{className:t?`av-model av-model-from`:`av-model`,children:To(e)})}function hp(e,t){return e.reroute?`Same preset, answered with a different model.`:ta(e.provider,e.to)?e.served?`Preset picks its own model. Answered with ${To(e.served.to)} (was ${To(e.served.from)}).`:t&&t.length>0?`Preset picks its own model. Answered with ${t.join(`, `)}.`:`Preset picks its own model.`:null}function gp({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=>Da(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:cp(e)}),toHelp:null}))});let p=[...new Set(n.map(e=>e.provider))].sort((e,t)=>ra(e).localeCompare(ra(t)));for(let e of p){let t=r[e]?.latestServedModelIds??null,a=n.filter(t=>t.provider===e);f.push({key:e,label:ra(e),rows:a.map((n,r)=>{let a=d.get(e)===n?i.get(e).text:null,o=[hp(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)(mp,{state:n.from,from:!0}),to:(0,$.jsx)(mp,{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?Ea(l):null;for(let[e,t]of Object.entries(l?Yi(l)??{}:{}).sort(([e],[t])=>e.localeCompare(t)))t.status===`mixed`&&g&&h.push((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:g}),` point mixes `,ra(e),` models: `,Zi(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)??[],ra(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: `,$i(t)]}):`Changed before this date range: ${$i(t)}`);for(let e of a)h.push(`${ra(e.provider)}: most recent ${e.shown} of ${e.total} changes`);for(let e of o)h.push(`${ra(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:[ra(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])=>ra(e).localeCompare(ra(t)))){let n=t.latestServedModelIds??[],r=n.length>0?n.join(`, `):To(t.latestObservation.state);h.push((0,$.jsxs)($.Fragment,{children:[ra(e),` last answered with `,(0,$.jsx)(`strong`,{children:r}),` on `,(0,$.jsx)(`strong`,{children:u(Pi(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=>hn(e,e));y+=` ${t} = the ${$i(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=ua(r[0],c,e,o);s&&(y+=` Check before: ${u(s)}.`)}let b=Pa({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 ${pp(u(t.at))}`:pp(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)(vs,{items:h})]}):(0,$.jsx)(`ul`,{className:`av-details-list`,children:h.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})})]})}function _p({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:ra(e)}),(0,$.jsxs)(`span`,{className:`text-secondary`,children:[`selected `,(0,$.jsx)(mp,{state:t.configured}),` · answered `,(0,$.jsx)(mp,{state:t.served})]}),(0,$.jsx)(`span`,{className:`av-status text-caution-400`,children:`substituted`})]},e))})}function vp({active:e,label:t,payload:n,metric:r,mode:i,buckets:a,basketChanges:o}){if(!e)return null;let s=ip(a,t);if(!s)return null;let c=ja(s),l=c!==null&&op(c.start,c.end)?c.start:null,u=Ba(s,o),d=ap(s),f=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`trend-tooltip-label`,children:Wa(s)}),u.map(e=>(0,$.jsxs)(`p`,{className:`trend-tooltip-detail trend-tooltip-note`,children:[cp(e),` `,hn(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:Vf},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`trend-tooltip-name`,children:Qf(`mentionShare`,s.mentionShare.scope)}),(0,$.jsx)(`span`,{className:`trend-tooltip-value`,children:W(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`?co:Qa}];return(0,$.jsxs)(`div`,{className:`trend-tooltip`,children:[f,m.map((e,t)=>{let n=String(e.dataKey??e.name??``),a=i===`byProvider`?np(s,n,r):null,o=a?.count??tp(s,r),c=a?.total??s.total,l=a?a.rate:s[ep(r)],u=e.color??Yf(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:Jf(n)}),(0,$.jsx)(`span`,{className:`trend-tooltip-value`,children:W(l)}),(0,$.jsxs)(`span`,{className:`trend-tooltip-count`,children:[o,` of `,c]})]})},`${n}-${t}`)}),p]})}function yp({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:[Qf(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=Xf(e.mentionShare.scope);i=n>0?`${W(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=np(e,n,t);return r?`${ra(n)} ${W(r.rate)} ${Zf(t).toLowerCase()}, ${r.count} of ${r.total} answers`:`${ra(n)} no data`}).join(`; `):`${W(e[ep(t)])} ${Zf(t).toLowerCase()}, ${tp(e,t)} of ${e.total} answers`;let a=ap(e);return a.length>0&&(i+=`; models: ${a.join(`; `)}`),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`th`,{scope:`row`,children:Wa(e)}),(0,$.jsx)(`td`,{children:i})]},e.startDate)})})]})})}function bp({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)(()=>ko(t,n),[t,n]),b=C({queryKey:[`analytics-metrics`,e,c,y,r,h],queryFn:()=>Oe(e,c,h),staleTime:Pn}),x=b.data??null,S=b.error,w=u===`mentionShare`?`overall`:g,T=(0,Q.useMemo)(()=>x?wo(x,u,w):null,[x,u,w]),E=x?sa(x):null,D=(0,Q.useMemo)(()=>ga(E??{}),[E]),O=(0,Q.useMemo)(()=>Ia(E??{}),[E]),k=(0,Q.useMemo)(()=>Object.entries(E??{}).filter(([,e])=>e.anchorUnavailable).map(([e])=>e).sort(),[E]),N=(0,Q.useMemo)(()=>x?aa(x):{},[x]),F=(0,Q.useMemo)(()=>x?go(Na(x)):[],[x]),I=(0,Q.useMemo)(()=>x?jo(x):[],[x]),B=(0,Q.useMemo)(()=>x?ca(x):[],[x]),V=(0,Q.useMemo)(()=>qi(E??{},N),[E,N]),H=(0,Q.useMemo)(()=>x?ka(x):{},[x]),te=(0,Q.useMemo)(()=>_e(H,{engineName:ra}),[H]),ne=(0,Q.useMemo)(()=>{let e=new Map;for(let[t,n]of Object.entries(H).sort(([e],[t])=>e.localeCompare(t))){let r=_e({[t]:n},{engineName:ra});r?.kind===`no-known-change`&&e.set(t,{text:`${r.text} ${r.detail}`,modelIds:n.modelIds??[]})}return e},[H]),re=(0,Q.useMemo)(()=>{let e=new Map(i.map(e=>[yt(e),e]));return t=>e.get(yt(t))??t},[i]),ie=u!==`mentionShare`&&w===`byProvider`,U=x?.buckets??[],ae=U[U.length-1]?.mentionShare.scope??x?.mentionShareScope??`pooled`,se=Qf(u,ae),ce=ie?Fi.textDim:u===`cited`?zi.positive:u===`mentionShare`?Vf:ki[1],le=(0,Q.useMemo)(()=>{let e=new Map(U.map(e=>[e.startDate,Do(e)]));return t=>e.get(String(t))??``},[U]),ue=u===`mentionShare`?U.filter(e=>typeof e.mentionShare.rate==`number`&&Number.isFinite(e.mentionShare.rate)):U,de=ue.at(-1),fe=(x?va(x,u):[]).at(-1)??null,pe=x?ao(x,u):null,me=Ta(ue,I),he=fa(me,u,ae,a),ge=fe!==null&&pe!==null?tt(pe.delta):null,ve=ge!==null&&!he,ye=t.length,be=[];if(fe!==null&&de&&be.push((0,$.jsxs)($.Fragment,{children:[`Latest point: `,(0,$.jsx)(`strong`,{children:rp(de,u)})]})),de&&pe!==null&&me&&!he&&be.push(up(me,de,I)),de&&ue.length===1){let e=lp(de,I);e&&!fa(Sa(de,I),u,ae,a)&&be.push(e)}if(ge!==null&&ue[0]){let e=Ea(ue[0]);e&&be.push((0,$.jsxs)($.Fragment,{children:[`Base: `,(0,$.jsx)(`strong`,{children:e}),` point`]}))}ie&&fe!==null&&be.push((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`strong`,{children:W(fe)}),` pools all answers; not an average of engines`]}));let xe=[...new Set([...D.buckets.map(e=>e.bucketStartDate),...U.filter(e=>Ba(e,I).length>0).map(e=>e.startDate)])].sort(),Se=fe!==null&&de&&(0,$.jsxs)(`div`,{className:`visibility-trend-current`,children:[(0,$.jsx)(`span`,{className:`visibility-trend-current-dot`,style:{backgroundColor:ce},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`visibility-trend-current-label`,children:se}),(0,$.jsx)(`span`,{className:`visibility-trend-current-value`,children:W(fe)}),ge!==null&&(0,$.jsx)(`span`,{className:`visibility-trend-current-delta ${ve?`text-muted`:Wf[ge.direction]}`,children:Gf(ge)}),ve&&me?(0,$.jsx)(X,{tone:`caution`,label:`Queries changed`,text:fp(me)}):null]}),Ce=(0,$.jsxs)(`div`,{className:`visibility-trend-controls`,children:[m&&(0,$.jsx)(ys,{options:zf,value:f,onChange:p,label:`Query type`}),(0,$.jsx)(ys,{options:Bf,value:u,onChange:d,label:`Metric`,className:`visibility-trend-metric-control`}),u!==`mentionShare`&&(0,$.jsx)(ys,{options:Rf,value:g,onChange:_,label:`Series`}),(0,$.jsx)(ys,{options:Gd,value:c,onChange:l,label:`Time window`,className:`sm:ml-auto`})]}),we;if(S)we=(0,$.jsx)(`p`,{className:`text-sm text-negative-400`,children:ke(S)});else if(b.isLoading&&!x)we=(0,$.jsx)(`div`,{className:`visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40`,"aria-hidden":`true`});else if(u===`mentionShare`&&ye===0)we=(0,$.jsx)(`p`,{className:`text-sm 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-sm text-secondary`,children:u===`mentionShare`?`No answer-text brand mentions for you or tracked competitors in ${Xf(ae)} in this window yet.`:h===`all`?He()?Ao:`Run a check to start tracking citations and mentions over time.`:`No ${h} answers in this window.`});else if(ie&&t.length===0)we=(0,$.jsxs)(`p`,{className:`text-sm 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=`${se} rate${h===`all`?``:` in ${h} answers`} across ${e.length} ${e.length===1?`check`:`checks`}. Latest ${W(fe)}${ge===null?``:`, ${Kf(ge)}${ve?`, not the same queries`:``}`}.`;we=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`sr-only`,children:n}),(0,$.jsx)(yp,{buckets:U,metric:u,mode:w,series:t,mentionShareScope:ae}),ie&&t.length>0&&(0,$.jsx)(`ul`,{className:`trend-legend`,"aria-label":`Engines`,children:t.map((e,t)=>{let n=ba(x,e,u);return(0,$.jsxs)(`li`,{className:`trend-legend-item`,children:[(0,$.jsx)(`span`,{className:`trend-legend-swatch`,style:{backgroundColor:Yf(e,t)},"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`trend-legend-name`,children:Jf(e)}),n!==null&&(0,$.jsx)(`span`,{className:`trend-legend-value`,children:W(n)})]},e)})}),(0,$.jsx)(`div`,{className:`visibility-trend-chart`,role:`img`,"aria-label":`${se} trend chart over ${e.length} ${e.length===1?`point`:`points`}`,children:(0,$.jsx)(P,{width:`100%`,height:`100%`,children:(0,$.jsxs)(z,{data:e,margin:{top:8,right:20,bottom:0,left:0},children:[(0,$.jsx)(A,{stroke:Vi,vertical:!1}),(0,$.jsx)(M,{dataKey:`date`,tick:Ri,tickLine:!1,axisLine:{stroke:Ui},tickFormatter:le,minTickGap:24}),(0,$.jsx)(L,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:e=>W(e,oe.percent),tick:Ri,tickLine:!1,axisLine:!1,width:40}),(0,$.jsx)(j,{cursor:{stroke:Ui,strokeWidth:1},content:(0,$.jsx)(vp,{metric:u,mode:w,buckets:U,basketChanges:I})}),xe.map(e=>(0,$.jsx)(ee,{x:e,stroke:Hf,strokeDasharray:`4 4`,strokeWidth:1.5,ifOverflow:`extendDomain`},`setup-change-${e}`)),t.map((e,t)=>(0,$.jsx)(R,{type:`monotone`,dataKey:e,name:e,stroke:Yf(e,t),strokeDasharray:e===`__mentionShare__`?`5 4`:void 0,strokeWidth:qf(e)?2.5:2,dot:e===`__mentionShare__`?{r:2.75,fill:`var(--chart-tooltip-bg)`,stroke:Yf(e,t),strokeWidth:1.5}:{r:2.5,fill:Yf(e,t),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Uf},connectNulls:e!==Za,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:$f(ae)})]}),de?(0,$.jsx)(`p`,{className:`av-card-meta`,children:Wa(de)}):null]}),(0,$.jsxs)(`div`,{className:`visibility-trend-body`,children:[te?.kind===`change`&&(0,$.jsx)(`p`,{className:`mb-3 rounded-lg border border-caution-800/60 bg-caution-950/20 px-3 py-2 text-[11px] leading-snug text-secondary`,children:te.text}),Se,Ce,we]}),(0,$.jsx)(vs,{items:be})]}),x&&!S?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(gp,{buckets:U,queryChanges:B,modelRows:V,served:N,pointerNotices:ne,truncated:O,incompleteHistory:k,queryName:re,sweepTimes:o}),(0,$.jsx)(_p,{substitutions:F})]}):null]})}var xp=new Set([st.queued,st.running]),Sp={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 Cp({projectName:e,onReviewForTracking:t,scopeOptions:n,planRevision:r,selectedScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c=[],viewerResearchConfig:l=null}){let u=x(),{account:d,canWrite:f}=On(),p=d?.role===`viewer`&&l!==null,m=!f,h=an(),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(``),[b,w]=(0,Q.useState)(null),[T,D]=(0,Q.useState)([]),O=(0,Q.useRef)(null),k=(0,Q.useRef)(!1),[A,j]=(0,Q.useState)(0),M=C({...ui({client:q,path:{name:e}}),staleTime:6e4}),N=C({...fi({client:q}),enabled:!m&&!h,staleTime:6e4}),P={client:q,path:{name:e},query:{limit:20}},F=E({...Xr(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=>xp.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]&&w(R[0].id)},[R,b]);let B=R.find(e=>e.id===b)??null,V=C({...ii({client:q,path:{name:e,runId:b??``}}),enabled:!I&&!!b,refetchInterval:B&&xp.has(B.status)?3e3:!1}),H=I||V.isError?null:V.data??null,te=M.data?.locations??[],ne=(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=Ga(e),r=new Map((N.data?.providers??[]).filter(e=>e.configured).map(e=>[e.name,e])),i=[...r.values()].filter(e=>!So(e.name,n)&&!le(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=>oo(e,yo)&&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=>le(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(le).flatMap(e=>{let n=G(e);if(!n)return[];let r=t.get(e),i=s.get(e),a=r??(o?{...o,name:e,displayName:i?.displayName??ra(e),modelConfigurable:!1,defaultModel:n,knownModels:o.knownModels.filter(e=>e.id===n)}:i);return a?[{name:e,displayName:i?.displayName??ra(e),configured:!0,defaultModel:n,catalog:a}]:[]});return[...i,...c,...a]},[L?.providers,m,M.data?.providers,N.data]),re=!(m?F.isPending:N.isPending)&&ne.length===0,ie=ne.find(e=>e.name===g)??null;(0,Q.useEffect)(()=>{if(!g&&M.data&&!M.isError&&!N.isError){let e=ne.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,ne,M.data,M.isError,N.isError]);let ae=ie?.catalog.modelConfigurable??!1,oe=m?ie?.catalog.defaultModel:(ie?M.data?.providerModels[ie.name]:``)||ie?.catalog.defaultModel,se=(ae?v.trim():``)||oe,ce=ie?[...new Map([{id:ie.catalog.defaultModel,displayName:ie.catalog.defaultModel},...v.trim()?[{id:v.trim(),displayName:v.trim()}]:[],...ie.catalog.knownModels].map(e=>[e.id,e])).values()]:[],ue=S({...ri(),onSuccess:async e=>{O.current=null,j(e=>e+1),D(e.runs),w(e.runs[0]?.id??null),await zp(u),jn({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=>{jn({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-sm text-secondary`,children:`This public demo shows saved research results. Running research is unavailable.`})}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Ep,{projectName:e,canWrite:f,researchAllowed:z&&!I,limitedAccess:m,isEmbed:U(),scopeOptions:n??[],planRevision:r??i?.planRevision??null,initialScope:i,scopePending:a,scopeError:o,onRetryScope:s,templates:c,locations:te,defaultLocation:M.data?.defaultLocation??null,providerOptions:ne,provider:g,onProviderChange:e=>{_(e),y(``)},resolvedModel:se,visibilityModel:oe,configurableModel:ae,model:v,onModelChange:y,modelOptions:ce,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||U()||k.current||(O.current?.fingerprint!==n&&(O.current={fingerprint:n,key:crypto.randomUUID()}),k.current=!0,ue.mutate({client:q,path:{name:e},body:{...t,idempotencyKey:O.current.key}}))}},`${e}:${A}`),ee!==null&&(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[`Up to `,ee,` destination runs per project per day.`]}),!m&&N.isError?(0,$.jsxs)(`div`,{role:`alert`,className:`text-sm text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load API providers.`}),(0,$.jsx)(J,{variant:`outline`,onClick:()=>{N.refetch()},children:`Retry providers`})]}):null,M.isError?(0,$.jsxs)(`div`,{role:`alert`,className:`text-sm text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load project locations.`}),(0,$.jsx)(J,{variant:`outline`,onClick:()=>{M.refetch()},children:`Retry locations`})]}):null,!(m?I:N.isError)&&re&&(0,$.jsx)(`p`,{className:`rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm 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-sm 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:()=>w(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:Sp.historyTitle})}),F.isFetching&&(0,$.jsx)(Y,{tone:`neutral`,children:`Loading`})]}),I?(0,$.jsxs)(`div`,{role:`alert`,className:`mt-4 text-sm text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load research history.`}),(0,$.jsx)(J,{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-sm text-muted`,children:Sp.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 font-medium text-heading hover:text-link focus:outline-none focus:underline`,onClick:()=>w(e.id),children:Fp(e.createdAt)})}),(0,$.jsxs)(`td`,{className:`text-secondary`,children:[(0,$.jsx)(`span`,{className:`block`,children:e.provider}),(0,$.jsx)(`span`,{className:`font-mono text-[11px] 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)(Y,{tone:Lp(e.status),children:e.status})})]},e.id))})]})}),F.isFetchNextPageError&&(0,$.jsx)(`p`,{role:`alert`,className:`mt-3 text-sm text-negative`,children:Sp.historyMoreError}),F.hasNextPage&&(0,$.jsx)(J,{className:`mt-3`,variant:`outline`,disabled:F.isFetching,onClick:()=>{F.fetchNextPage()},children:F.isFetchingNextPage?Sp.historyLoading:Sp.historyMore})]})]}),!I&&V.isError?(0,$.jsxs)(`div`,{role:`alert`,className:`text-sm text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load saved research results.`}),(0,$.jsx)(J,{variant:`outline`,onClick:()=>{V.refetch()},children:`Retry results`})]}):I?null:(0,$.jsx)(jp,{detail:H,isLoading:V.isFetching,onReviewForTracking:h?void 0:t})]})}var wp=`mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong placeholder-mono-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 disabled:opacity-50`,Tp=`__none__`;function Ep(e){let{projectName:t,locations:n,provider:r,resolvedModel:i,planRevision:a}=e,o=x(),[s,c]=(0,Q.useState)(`once`),[u,d]=(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),[y,b]=(0,Q.useState)([]),[C,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)(``),B=(0,Q.useRef)(null),V=(0,Q.useRef)(!1),H=(0,Q.useRef)(null),te=e.initialScope?`${e.initialScope.kind}:${e.initialScope.key}`:`project`;(0,Q.useEffect)(()=>{h(te),O(null)},[te]);let ne=e.scopeOptions.filter(e=>e.kind===`market`||e.kind===`property`),re=s===`markets`?`market`:`property`,ie=ne.filter(e=>e.kind===re),U=t=>({kind:t.kind,key:t.id,label:t.label,planRevision:a??e.initialScope?.planRevision??0}),ae=e=>e===Tp?null:n.find(t=>t.label===e),oe=g??e.defaultLocation??Tp,se=ne.find(e=>`${e.kind}:${e.id}`===m),ce=se?U(se):null,le=s===`once`?[{scope:ce,location:ae(oe)}]:s===`locations`?y.map(e=>({scope:null,location:ae(e)})):y.map(e=>ie.find(t=>`${t.kind}:${t.id}`===e)).map(e=>e?{scope:U(e),location:ae(T[`${e.kind}:${e.id}`]??Tp)}:null),ue=[...new Map([...k,...e.templates].map(e=>[e.id,e])).values()],de=D?ue.find(e=>e.id===D.id):null,fe=D!==null&&de?.version!==D.version,pe=s===`once`?u:f,me=pe.split(/\r?\n/).filter(e=>e.trim()),he=Ut(me),ge=[...new Set([...f.matchAll(/\{([^{}]+)\}/g)].map(e=>e[1]))],_e=/[{}]/.test(f.replace(/\{(?:market|submarket|property|propertyBrand|location)\}/g,``)),ve=[];me.length||ve.push(s===`once`?`Enter at least one query.`:`Enter at least one query pattern.`),me.some(e=>e.length>4e3)&&ve.push(`Keep each query under 4,001 characters.`),s!==`once`&&_e&&ve.push(`Use the name buttons to insert a supported variable. Remove unknown or incomplete braces.`),le.length||ve.push(s===`locations`?`Select at least one location.`:`Select at least one destination.`),le.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||le.some(e=>!e?.scope))&&ve.push(`Load the current published markets and properties before running scoped research.`);let be=(s===`once`?he.length:me.length)*le.length;if(le.length>20&&ve.push(`Select at most 20 destinations.`),be>50&&ve.push(`${be} queries selected. Reduce the selection to 50 or fewer.`),fe&&ve.push(`This saved pattern changed. Select its current version from Saved patterns.`),s!==`once`&&!_e){for(let e of le)if(e&&e.location!==void 0)try{Xt(D??{pattern:f,variables:ge},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:pe,contexts:le,provider:r,resolvedModel:i,template:D,...ye?{planRevision:a}:{}}),Se=j!==null&&j.signature!==xe,Ce=s===`once`?he.map((e,t)=>({id:String(t),query:e,scope:ce,location:le[0]?.location??null})):j?.rows??[],W=Ap(Ce),we=[];s!==`once`&&j&&(Se&&we.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))&&we.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)))&&we.push(`A preview location changed. Regenerate the preview.`),W.some(e=>Ut(e.queries).length!==e.queries.length)&&we.push(`Remove duplicate queries within each destination and location.`),W.length>20&&we.push(`The preview exceeds 20 runs.`));let Te=e.researchAllowed&&!e.isEmbed&&!e.isPending&&e.settingsReady&&e.projectReady&&!!(r&&i)&&!ve.length&&!we.length&&(s===`once`||j!==null),G=()=>({runs:W.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}:{}}))}),Ee=()=>{if(P(!0),ve.length)return;let e=le.flatMap((e,t)=>me.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})},De=e=>{c(e),b([]),O(null),w(``),P(!1)},Oe=e=>{if(ee(``),s===`once`)try{d(Xt(e,ce,ae(oe)).output)}catch{ee(`Select a matching market, property, or location before using this pattern.`);return}else p(e.pattern);O(e)},ke=e=>{let t=H.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)})},Ae=S({...wr(),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(``),B.current=null,await o.invalidateQueries({queryKey:si({client:q,path:{name:t}})}),jn({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:()=>{V.current=!1}}),je=()=>{if(!e.canWrite||e.isEmbed||V.current)return;let n=s===`once`?u:f,r=s===`once`?[]:ge;if(!L.trim()||!n.trim()||n.length>4e3||s!==`once`&&_e){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);B.current?.fingerprint!==a&&(B.current={fingerprint:a,id:crypto.randomUUID()}),V.current=!0,Ae.mutate({client:q,path:{name:t,templateId:B.current.id},body:i})},Me=[...new Set([...N||pe.trim()?ve:[],...we])],Ne=ue.filter(e=>{let t=s===`once`?pt(ce,ae(oe)):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-sm 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||Ae.isPending,children:[(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium text-heading`,children:`Run mode`}),(0,$.jsxs)(`select`,{className:wp,value:s,disabled:e.isPending,onChange:e=>De(e.target.value),children:[(0,$.jsx)(`option`,{value:`once`,children:`Run once`}),(0,$.jsx)(`option`,{value:`markets`,disabled:!ne.some(e=>e.kind===`market`),children:`Repeat across markets`}),(0,$.jsx)(`option`,{value:`properties`,disabled:!ne.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:[(ne.length>0||m!==`project`)&&(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium text-heading`,children:`Save results under`}),(0,$.jsxs)(`select`,{className:wp,value:m,onChange:e=>{h(e.target.value),O(null)},children:[(0,$.jsx)(`option`,{value:`project`,children:`Whole site`}),m!==`project`&&!se&&(0,$.jsx)(`option`,{value:m,disabled:!0,children:`Selected destination unavailable`}),ne.map(e=>(0,$.jsxs)(`option`,{value:`${e.kind}:${e.id}`,children:[e.label,` (`,e.kind,`)`]},`${e.kind}:${e.id}`))]})]}),(0,$.jsx)(Dp,{label:`Answer engine location`,value:oe,locations:n,onChange:e=>{_(e),O(null)}})]}),s!==`once`&&(0,$.jsxs)(`fieldset`,{className:`space-y-3`,children:[(0,$.jsx)(`legend`,{className:`text-sm font-medium text-heading`,children:s===`locations`?`Select locations`:`Select ${s}`}),(0,$.jsx)(`p`,{className:`text-sm 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:wp,placeholder:`Search ${s}`,value:C,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})):ie.map(e=>({key:`${e.kind}:${e.id}`,label:e.label}))).filter(e=>e.label.toLocaleLowerCase().includes(C.toLocaleLowerCase())).map(e=>{let t=y.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-sm 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)(Dp,{label:`Answer engine location for ${e.label}`,value:T[e.key]??Tp,locations:n,onChange:t=>E(n=>({...n,[e.key]:t}))})]},e.key)})}),(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[y.length,` selected. A market or property name changes query text, not the answer engine's location.`]})]}),e.scopeError&&(0,$.jsxs)(`p`,{className:`text-sm text-caution`,children:[`Markets and properties could not load. Whole-site and location research remain available. `,(0,$.jsx)(J,{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-sm font-medium text-heading`,children:s===`once`?`Queries`:`Query pattern`})}),(0,$.jsx)(`p`,{id:`research-query-guidance`,className:`mt-1 text-sm 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:H,className:`${wp} min-h-32`,"aria-describedby":`research-query-guidance research-query-count`,value:pe,placeholder:s===`once`?Sp.queryPlaceholder:s===`markets`?`Best apartments in {market}`:s===`properties`?`What amenities does {property} offer?`:`Best apartments in {location}`,onChange:e=>{s===`once`?d(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)(J,{size:`sm`,variant:`outline`,onClick:()=>ke(s===`markets`?`market`:s===`properties`?`property`:`location`),children:[`Insert `,s===`markets`?`market`:s===`properties`?`property`:`location`,` name`]}),(0,$.jsx)(`span`,{className:`self-center text-sm text-secondary`,children:`One pattern per line.`})]}),(0,$.jsxs)(`p`,{id:`research-query-count`,className:`mt-2 text-sm text-secondary`,children:[be,` / `,50,` queries`,s===`once`?``:` across ${le.length} destinations`]})]}),s!==`once`&&(0,$.jsxs)(`details`,{className:`border-t border-default pt-3`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer text-sm font-medium text-heading focus-visible:outline focus-visible:outline-2`,children:[`Saved patterns `,(0,$.jsx)(`span`,{className:`font-normal text-secondary`,children:`(optional)`})]}),(0,$.jsxs)(`div`,{className:`mt-3 space-y-3`,children:[(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`Reusable starting text, not active measurement templates. Saving a pattern does not run or track queries.`}),Ne.length?(0,$.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:Ne.map(e=>(0,$.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>Oe(e),children:e.label},e.id))}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No saved patterns for this selection.`}),D&&(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[`Using: `,D.label]}),e.canWrite&&!e.isEmbed&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(J,{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-sm text-heading`,children:[`Pattern name`,(0,$.jsx)(`input`,{className:wp,value:L,maxLength:120,onChange:e=>R(e.target.value)})]}),(0,$.jsx)(J,{size:`sm`,disabled:Ae.isPending||!L.trim()||!pe.trim(),onClick:je,children:Ae.isPending?`Saving…`:`Save pattern`})]})]}),z&&(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-negative`,children:z})]})]}),(0,$.jsxs)(`div`,{className:`grid gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{className:`block text-sm font-medium text-heading`,children:[`Answer engine`,(0,$.jsxs)(`select`,{className:wp,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-sm font-medium text-heading`,children:[`Model`,e.limitedAccess?(0,$.jsxs)(`select`,{className:wp,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:wp,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))})]})]})]}),Me.length>0&&(0,$.jsx)(kp,{errors:Me}),s!==`once`&&(0,$.jsxs)(`div`,{className:`space-y-4 border-t border-default pt-4`,children:[(0,$.jsxs)(J,{variant:`outline`,size:`sm`,disabled:e.isPending||!e.projectReady,onClick:Ee,children:[(0,$.jsx)(v,{size:14}),j?Sp.refreshPreview:`Preview queries`]}),j&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`h4`,{className:`font-medium text-heading`,children:`Queries to run`}),(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[Ce.length,` query executions in `,W.length,` saved runs · `,r,` · `,i,`. Edit any query or location below.`]}),(0,$.jsx)(Op,{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-sm 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)(J,{size:`sm`,disabled:!Te,onClick:()=>{if(Te){let n=G();e.onSubmit(n,JSON.stringify({projectName:t,...n}))}},children:[(0,$.jsx)(l,{size:14}),e.isPending?`Starting…`:Sp.runAction]}),(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[s===`once`?`${he.length} queries`:`${Ce.length} reviewed queries`,` · `,r||`Choose an engine`,` · `,i||`Choose a model`,`. Uses your configured answer engine.`]})]})]})]})}function Dp({label:e,value:t,locations:n,onChange:r}){return(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium text-heading`,children:e}),(0,$.jsxs)(`select`,{className:wp,value:t,onChange:e=>r(e.target.value),children:[(0,$.jsx)(`option`,{value:Tp,children:`No location context`}),n.map(e=>(0,$.jsx)(`option`,{value:e.label,children:e.label},e.label))]})]})}function Op({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-sm`,children:[(0,$.jsxs)(`span`,{className:`block text-secondary`,children:[`Query `,r+1]}),(0,$.jsx)(`span`,{className:`font-medium 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-sm font-medium text-heading`,children:[`Query`,(0,$.jsx)(`textarea`,{className:`${wp} 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)(Dp,{label:`Location for query ${r+1}`,value:e.location?.label??Tp,locations:t,onChange:r=>n(e.id,{location:t.find(e=>e.label===r)??null})})]},e.id))})}function kp({errors:e}){return(0,$.jsx)(`div`,{role:`alert`,className:`text-sm 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 Ap(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 jp({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":Sp.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 ${Ip(e.id)}`:Sp.resultsEmpty})]}),e&&(0,$.jsx)(Y,{tone:Lp(e.status),children:e.status})]}),e&&(0,$.jsxs)(`div`,{className:`mt-3 space-y-3 text-sm 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:`font-medium`,children:`Answer engine`}),(0,$.jsx)(`dd`,{children:e.provider})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-medium`,children:`Requested model`}),(0,$.jsx)(`dd`,{className:`font-mono`,children:e.requestedModel??e.resolvedModel})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-medium`,children:`Location`}),(0,$.jsx)(`dd`,{children:e.location?.label??`No location`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-medium`,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:Sp.templateProvenance}),(0,$.jsxs)(`dl`,{className:`mt-2 space-y-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-medium`,children:`Saved pattern`}),(0,$.jsx)(`dd`,{className:`whitespace-pre-wrap`,children:e.template.template})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`font-medium`,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:`font-medium`,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 font-mono text-xs`,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:Sp.methodologySummary}),(0,$.jsx)(`p`,{className:`mt-2 max-w-prose leading-6`,children:Sp.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 font-medium text-heading hover:text-link focus:outline-none focus:underline`,onClick:()=>i(e.id),children:e.query})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{tone:e.queryClass===`branded`?`positive`:e.queryClass===`non-brand`?`neutral`:`caution`,children:e.queryClass===`branded`?Sp.brandedQuery:e.queryClass===`non-brand`?Sp.discoveryQuery:Sp.unclassifiedQuery})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{tone:Rp(e.status),children:e.status})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{tone:e.answerMentioned===!0?`positive`:e.answerMentioned===!1?`neutral`:e.status===kt.failed?`negative`:`caution`,children:e.answerMentioned===null?e.status===kt.failed?`Unavailable`:`Pending`:e.answerMentioned?`Matched`:`No match`})}),(0,$.jsx)(`td`,{children:e.citationMeasured===!1&&e.status===kt.completed?(0,$.jsx)(Y,{tone:`neutral`,children:`Not measured`}):(0,$.jsx)(Y,{tone:e.citationState===`cited`?`positive`:e.citationState===`not-cited`?`neutral`:e.status===kt.failed?`negative`:`caution`,children:e.citationState===null?e.status===kt.failed?`Unavailable`:`Pending`:e.citationState===`cited`?`Cited`:`Not cited`})})]},e.id))})]})}),(0,$.jsx)(Mp,{query:a,scope:e.scope??null,isLoading:t,onReviewForTracking:n})]}):(0,$.jsx)(`p`,{className:`mt-4 text-sm text-muted`,children:`Select a saved run to inspect each answer and its source links.`})]})}function Mp({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-[10px] uppercase tracking-wide text-muted`,children:`Selected query`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm font-medium leading-6 text-heading`,children:e.query})]}),!U()&&r&&(0,$.jsxs)(`div`,{className:`rounded-md border border-default bg-surface-subtle px-3 py-3`,children:[(0,$.jsx)(pa,{type:`button`,size:`sm`,onClick:()=>r({researchRunQueryId:e.id,scope:n}),children:`Review for tracking`}),(0,$.jsx)(`p`,{className:`mt-2 text-xs leading-5 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-sm text-negative`,children:e.error}),e.error&&e.evidence&&e.answerText?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[10px] uppercase tracking-wide text-muted`,children:`Partial answer, not measured`}),(0,$.jsx)(`div`,{className:`mt-1`,children:(0,$.jsx)(Vo,{headingLevel:4,copyable:!0,children:e.answerText})})]}):e.error?null:e.answerText?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`text-[10px] uppercase tracking-wide text-muted`,children:`Answer`}),(0,$.jsx)(`div`,{className:`mt-1`,children:(0,$.jsx)(Vo,{headingLevel:4,copyable:!0,children:e.answerText})})]}):(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:e.status===kt.failed?`This query did not return an answer.`:e.status===kt[`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-[10px] uppercase tracking-wide 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-[10px] uppercase tracking-wide text-muted`,children:`Cited competitor domains`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs leading-5 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-[10px] uppercase tracking-wide 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)(to,{url:e.uri,title:e.title})},`${e.uri}-${t}`))})]}),e.evidence&&(0,$.jsx)(Pp,{evidence:e.evidence})]}):(0,$.jsx)(`p`,{className:`text-sm text-muted`,children:t?`Loading saved answers…`:`Select a query to inspect its answer.`})}var Np={"explicit-citation":`Cited in the answer`,"answer-support":`Used for the answer`,"search-result":`Search result`,"page-read":`Page read`};function Pp({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-[10px] uppercase tracking-wide 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:bt(e.completion.status)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{children:`Profile`}),(0,$.jsx)(`dd`,{className:`font-mono text-xs`,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:rt(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-xs text-muted`,children:Np[e.relationship]}),(0,$.jsx)(to,{url:e.url,title:e.title??e.url})]},`${e.url}-${t}`))})]})}function Fp(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 Ip(e){return e.length>8?e.slice(0,8):e}function Lp(e){return e===st.completed?`positive`:e===st.partial||e===st[`waiting-upstream`]?`caution`:e===st.failed?`negative`:`neutral`}function Rp(e){return e===kt.completed?`positive`:e===kt.failed?`negative`:e===kt[`waiting-upstream`]?`caution`:`neutral`}async function zp(e){await Mn(e,`researchRuns`)}var Bp=new Set([`queued`,`seeding`,`probing`]);function Vp({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}=On(),[d,f]=(0,Q.useState)(`tracked`),[p,m]=(0,Q.useState)(`find`),[h,g]=(0,Q.useState)(null),_=u?.role===`viewer`?mt():null,v=is(u?.role,_),y=as(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)(Hp,{active:y===`tracked`,label:`Tracked`,onClick:()=>x(`tracked`)}),v?(0,$.jsx)(Hp,{active:y===`research`,label:`Research`,onClick:()=>x(`research`)}):null]}),(0,$.jsx)(`div`,{className:`mt-4`,children:y===`tracked`?(0,$.jsx)(Tm,{projectName:e,selection:a,onSelectionChange:o,trackingQueryId:s,onTrackingQueryIdChange:c,pendingTrackingSource:h,onPendingTrackingSourceHandled:()=>g(null),publishGuard:l}):(0,$.jsx)(Up,{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 Hp({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-sm font-medium 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 Up({projectName:e,selection:t,mode:n,onModeChange:r,onReviewSavedSource:i,viewerResearchConfig:a}){let{canWrite:o}=On(),s=!o||n===`test`,c=C({...jr({client:q,path:{name:e}}),enabled:s,staleTime:6e4}),l=C({...Qr({client:q,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)(Hp,{active:n===`find`,label:`Find queries`,onClick:()=>r(`find`)}),(0,$.jsx)(Hp,{active:n===`test`,label:`Test queries`,onClick:()=>r(`test`)})]}),(0,$.jsx)(`div`,{className:`mt-4`,children:n===`find`?(0,$.jsx)(Em,{projectName:e,onReviewDiscoveryProbe:e=>i({source:`discovery`,discoveryProbeId:e})}):(0,$.jsx)(Cp,{...f,onReviewForTracking:({researchRunQueryId:e,scope:t})=>i({source:`research`,researchRunQueryId:e},t??null)})})]}):(0,$.jsx)(Cp,{...f,viewerResearchConfig:a})}function Wp({workspace:e,selection:n,onSelectionChange:r,trackingQueryId:i,onTrackingQueryIdChange:a,pendingTrackingSource:o,onPendingTrackingSourceHandled:s,templates:c,preview:l,isPreviewing:u,isCommitting:d,onPreview:f,onCommit:p,publishGuard:m}){let[h,_]=(0,Q.useState)(null),[v,b]=(0,Q.useState)(()=>Gp(n)),[x,S]=(0,Q.useState)(null),C=(0,Q.useRef)(null),w=(0,Q.useRef)(null),T=os(e,n),E=(0,Q.useMemo)(()=>tm(e.tracked,n,e.mode),[n,e.mode,e.tracked]),D=Io({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 t=`${i}:${rm(n)}`;if(w.current===t)return;let r=e.tracked.find(e=>e.queryId===i);r&&(w.current=t,_({kind:`edit`,row:r,audience:e.mode===`advanced`?Qp(n):void 0,scopeLabel:$p(n,e)}),b(Kp(r,n)),S(null))},[n,i,T,e]),(0,Q.useEffect)(()=>{if(T||!o)return;let e=Gp(o.trackingSelection??n);_({kind:`add`}),b(o.source===`research`?{...e,source:`research`,researchRunQueryId:o.researchRunQueryId}:{...e,source:`discovery`,discoveryProbeId:o.discoveryProbeId}),S(null),s()},[s,o,n,T]),(0,Q.useEffect)(()=>{T&&(_(null),S(null),i!==void 0&&a?.(void 0))},[a,i,T]),(0,Q.useEffect)(()=>{if(!h||h.kind===`remove`)return;let e=C.current;e&&(e.scrollIntoView?.({block:`start`}),e.focus({preventScroll:!0}))},[h]);function O(e=`manual`){_({kind:`add`}),b({...Gp(n),source:e}),S(null),a?.(void 0)}function k(t){w.current=`${t.queryId}:${rm(n)}`,_({kind:`edit`,row:t,audience:e.mode===`advanced`?Qp(n):void 0,scopeLabel:$p(n,e)}),b(Kp(t,n)),S(null),a?.(t.queryId)}function A(t){w.current=`${t.queryId}:${rm(n)}`,_({kind:`remove`,row:t,audience:e.mode===`advanced`?Qp(n):void 0,scopeLabel:$p(n,e)}),S(null),a?.(t.queryId)}function j(){_(null),S(null),a?.(void 0)}let M=h?qp(h,v,e):null,N=h!==null&&h.kind===`add`&&e.mode===`advanced`&&!Xp(v),P=M!==null&&(!N||v.contexts.length>0)&&!u;return T?(0,$.jsx)(`div`,{className:`query-tracking-workspace space-y-4`,children:(0,$.jsxs)(`section`,{"aria-label":`Tracked queries`,className:`py-4 text-sm text-secondary`,children:[(0,$.jsxs)(`p`,{children:[`This saved `,n.measurementScope,` filter is unavailable in the current measurement.`]}),(0,$.jsx)(J,{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)(nm,{selection:n,onSelectionChange:r}):null,(0,$.jsx)(No,{value:D.query,onChange:D.setQuery,label:`Filter tracked queries`,placeholder:`Search tracked queries`,className:`min-w-64 flex-[2]`}),!U()&&(0,$.jsxs)(pa,{type:`button`,size:`sm`,onClick:()=>O(),children:[(0,$.jsx)(y,{"aria-hidden":`true`,size:14}),`Add query`]})]}),(0,$.jsxs)(`p`,{className:`mt-2 text-xs leading-5 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.`]}),n.measurementScope===`group`?(0,$.jsx)(`p`,{className:`mt-1 text-xs leading-5 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-sm text-caution`,children:`No published measurement yet.`}),D.rows.length===0?(0,$.jsx)(`p`,{className:`mt-5 text-sm 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(r=>(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`tracking-query-cell break-words font-medium text-heading`,children:r.queryText}),(0,$.jsx)(`td`,{className:`tracking-scope-cell text-secondary`,children:(0,$.jsx)(om,{row:r,workspace:e,selection:n})}),e.mode===`advanced`?(0,$.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,$.jsx)(cm,{row:r})}):null,(0,$.jsx)(`td`,{className:`whitespace-nowrap text-secondary`,children:im(r)}),(0,$.jsx)(`td`,{className:`whitespace-nowrap`,children:(0,$.jsx)(lm,{row:r,outsidePlan:e.mode===`advanced`&&r.assignments.length===0})}),(0,$.jsx)(`td`,{className:`measurement-table-actions whitespace-nowrap text-right`,children:!U()&&(0,$.jsxs)(`div`,{className:`tracking-row-actions flex min-w-max justify-end gap-2`,children:[(0,$.jsxs)(pa,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Edit ${r.queryText}`,onClick:()=>k(r),children:[(0,$.jsx)(t,{"aria-hidden":`true`,size:13}),` Edit`]}),(0,$.jsxs)(pa,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Remove ${r.queryText}`,onClick:()=>A(r),children:[(0,$.jsx)(g,{"aria-hidden":`true`,size:13}),` Remove`]})]})})]},r.queryId))})]})}),(0,$.jsx)(Fo,{page:D.page,pageSize:D.pageSize,visibleRows:D.rows.length,totalRows:D.totalRows,itemLabel:`queries`,onPageChange:D.setPage})]}),h&&!U()&&(0,$.jsx)(um,{workspace:e,templates:c,action:h,draft:v,onDraftChange:e=>{b(e),S(null)},onClose:j,canReview:P,isPreviewing:u,editorHeadingRef:C,onReview:()=>{M&&(S(M),f(M))}}),l&&x&&h&&(0,$.jsx)(bm,{preview:l,workspace:e,isCommitting:d,sweepActive:m?.sweepActive??!1,onConfirm:()=>{p({...x,expectedWorkspaceVersion:l.workspaceVersion,previewToken:l.previewToken,reviewedAt:l.reviewedAt})}})]})}function Gp(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 Kp(e,t){return{...Gp(t),text:e.queryText,queryClass:`keep`}}function qp(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=Jp(t);if(!i||Zp(t)||r&&!t.wholeSite&&t.targetKeys.length+t.groupKeys.length+t.marketKeys.length===0)return null;let a=r?Yp(t,n):void 0;return{additions:[{input:i,...a?{audience:a}:{},...r&&!Xp(t)&&t.contexts.length>0?{contexts:t.contexts}:{},...r&&t.queryClass!==`auto`&&t.queryClass!==`keep`?{queryClass:t.queryClass}:{}}],removals:[]}}function Jp(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 Yp(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 Xp(e){return e.marketKeys.length>0&&e.targetKeys.length===0&&e.groupKeys.length===0}function Zp(e){return e.source===`template`&&e.template.includes(`{market}`)&&(e.wholeSite||e.marketKeys.length===0)}function Qp(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 $p(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 em(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 tm(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=>em(e,t)))}function nm({selection:e,onSelectionChange:t}){return(0,$.jsxs)(`label`,{className:`min-w-40 flex-1`,children:[(0,$.jsx)(`span`,{className:`mb-1 block text-xs font-medium 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-sm 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 rm(e){return e.measurementScopeKey&&e.measurementScope!==`project`?`${e.measurementScope}:${e.measurementScopeKey}`:`project`}function im(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 am(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=>em(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 om({row:e,workspace:t,selection:n}){let r=sm(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:am(e,t,n)}),(0,$.jsxs)(`div`,{className:`mt-2 rounded border border-default bg-surface p-2 text-xs leading-5 text-secondary`,children:[(0,$.jsx)(`p`,{className:`font-medium 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 sm(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=>em(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 cm({row:e}){let t=[...new Set(e.assignments.map(e=>e.queryClass??`unknown`))],n=t.join(`, `);return(0,$.jsx)(Y,{tone:t.includes(`unknown`)?`caution`:`neutral`,children:n||`Unknown`})}function lm({row:e,outsidePlan:t=!1}){return t?(0,$.jsx)(Y,{tone:`neutral`,children:`Not in current plan`}):e.state===`tracked`?(0,$.jsx)(Y,{tone:`positive`,children:`Measured`}):(0,$.jsx)(Y,{tone:`caution`,children:`Awaiting check`})}function um({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-sm leading-6 text-secondary`,children:[`Remove “`,n.row.queryText,`” from future tracking?`]}),(0,$.jsxs)(`p`,{className:`mt-1 text-sm leading-5 text-secondary`,children:[n.audience?`Only assignments in ${n.scopeLabel} will be removed.`:`All assignments will be removed.`,` Earlier results stay unchanged.`]})]})}),(0,$.jsx)(ym,{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)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:a,children:`Cancel`})]}),(0,$.jsxs)(`p`,{className:`mt-3 text-sm leading-6 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-xs font-medium 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-sm 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-xs font-medium 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-sm 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-sm leading-6 text-secondary`,children:`Existing locations and engines are preserved. Use Add query to create assignments in another scope.`})]}),(0,$.jsx)(ym,{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)(J,{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-sm font-medium 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-sm text-strong placeholder-mono-600 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)(dm,{templates:t,advanced:e.mode===`advanced`,draft:r,onDraftChange:i}):null,r.source===`research`?(0,$.jsx)(fm,{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)(fm,{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-sm font-medium 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-sm 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-sm leading-6 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)(vm,{workspace:e,draft:r,onDraftChange:i}):null]}),e.mode===`advanced`&&!Xp(r)?(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(_m,{workspace:e,draft:r,onDraftChange:i})}):null,(0,$.jsxs)(`details`,{className:`mt-4 border-t border-default text-sm 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-xs font-medium 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-sm 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:`rounded-md border border-default bg-surface-subtle px-3 py-2`,children:[(0,$.jsx)(`p`,{className:`text-xs font-medium text-secondary`,children:`Classification`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:`Automatic`})]})})]}),r.source===`research`&&(0,$.jsx)(`p`,{className:`mt-4 rounded-md border border-default bg-surface-subtle px-3 py-2 text-sm text-secondary`,children:`Only the saved query is added.`}),(0,$.jsx)(ym,{canReview:o,isPreviewing:s,onCancel:a,onReview:l})]})}function dm({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-xs font-medium text-secondary`,children:`Saved template`}),(0,$.jsxs)(`select`,{id:`tracking-template-source`,"aria-describedby":Zp(n)?`tracking-template-market-required`:void 0,className:`mt-1 h-9 w-full rounded-md border border-default bg-surface px-3 text-sm 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-xs leading-5 text-muted`,children:n.template}):null]}),Zp(n)?(0,$.jsx)(`p`,{id:`tracking-template-market-required`,role:`status`,className:`mt-2 text-sm leading-5 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 fm({id:e,label:t,value:n,options:r,onChange:i}){return(0,$.jsxs)(`label`,{className:`block`,htmlFor:e,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium 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-sm 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 pm(e){return{providers:[...e.providers],models:{...e.models},location:e.location?.label??null}}function mm(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 hm(e){return[...new Map(e.map(e=>[mm(e),e])).values()]}function gm(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 _m({workspace:e,draft:t,onDraftChange:n}){let r=(0,Q.useMemo)(()=>hm([...e.defaultContexts.map(pm),...t.contexts]),[t.contexts,e.defaultContexts]),i=t.contexts.length===1?mm(t.contexts[0]):t.contexts.length>1?`__existing__`:``;return(0,$.jsxs)(`label`,{className:`block`,htmlFor:`tracking-query-context`,children:[(0,$.jsx)(`span`,{className:`text-xs font-medium 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-sm 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=>mm(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:mm(e),children:gm(e)},mm(e)))]}),(0,$.jsx)(`span`,{className:`mt-1 block text-xs leading-5 text-secondary`,children:r.length===0?`No configured measurement context is available.`:`Choose where this query will be measured.`})]})}function vm({workspace:e,draft:t,onDraftChange:n}){let{canWrite:r}=On(),[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 rounded-md border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`legend`,{className:`px-1 text-xs font-medium text-secondary`,children:`Apply to`}),(0,$.jsxs)(`div`,{className:`flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`p`,{className:`text-sm text-strong`,children:[`Property: `,n?.label??t.targetKeys[0]]}),(0,$.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,"aria-label":`Change tracking destination`,onClick:()=>s(!0),children:`Change`})]})]})}return(0,$.jsxs)(`fieldset`,{className:`rounded-md border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`legend`,{className:`px-1 text-xs font-medium text-secondary`,children:`Apply to`}),(0,$.jsx)(`p`,{className:`text-sm leading-6 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-sm 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-sm text-caution`,children:`Choose at least one location, group, or market.`}):null,(0,$.jsx)(`p`,{className:`mt-2 text-sm leading-5 text-secondary`,children:`Group: properties grouped together. Market: search context.`}),(0,$.jsx)(No,{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-sm 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-sm 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-xs text-muted`,children:e.detail})]},`${e.kind}:${e.key}`))})]})}function ym({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)(pa,{type:`button`,size:`sm`,disabled:!e,onClick:r,children:t?`Reviewing…`:`Review changes`}),(0,$.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,onClick:n,children:`Cancel`}),(0,$.jsx)(`p`,{className:`text-sm leading-5 text-secondary`,children:`Publishing does not run a check.`})]})}function bm({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-sm font-medium text-strong`,children:xm(e)}),(0,$.jsx)(`p`,{className:`mt-1 text-sm leading-6 text-secondary`,children:s})]}),(0,$.jsx)(Y,{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)(Sm,{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-sm 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)(Sm,{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)(pa,{type:`button`,size:`sm`,disabled:!o||n||r,onClick:i,children:n?`Confirming…`:`Confirm changes`}),o&&r?(0,$.jsx)(`p`,{role:`status`,className:`text-sm leading-5 text-caution`,children:`A check is queued or running. Publish after it finishes.`}):null]})]})}function xm(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 Sm({label:e,rows:t,workspace:n,tracked:r}){return(0,$.jsxs)(`section`,{"aria-label":`${e} queries`,children:[(0,$.jsxs)(`p`,{className:`text-xs font-medium 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-sm`,children:[(0,$.jsx)(`p`,{className:`font-medium text-strong`,children:t.queryText}),(0,$.jsx)(`p`,{className:`mt-1 text-secondary`,children:e===`Removed`?`${t.assignmentCount} ${t.assignmentCount===1?`assignment`:`assignments`} removed`:wm(t,r,n)}),e===`Added`||e===`Reused`?(0,$.jsx)(Cm,{row:r.find(e=>e.queryId===t.queryId),workspace:n}):null]},`${e}:${t.queryId}`))})]})}function Cm({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 font-medium 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=>gm(pm(e))).join(`; `);return(0,$.jsx)(`li`,{children:[r,i,a].filter(Boolean).join(` · `)},`${e.targetKey}:${n}`)})})]})}function wm(e,t,n){let r=t.find(t=>t.queryId===e.queryId);if(!r)return`${e.assignmentCount} ${e.assignmentCount===1?`assignment`:`assignments`}`;let i=hm(r.assignments.flatMap(e=>e.contexts).map(pm)),a=i.length===1?gm(i[0]):i.length>1?`${i.length} contexts`:null;return[am(r,n),a].filter(e=>e!==null).join(` · `)}function Tm({projectName:e,selection:t={measurementScope:`project`,queryClass:`all`},onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s}){let c=x(),[l,u]=(0,Q.useState)(null),d=C({...jr({client:q,path:{name:e}})}),f=C({...Qr({client:q,path:{name:e}}),staleTime:6e4}),p=S({...Pr(),onSuccess:e=>u(e),onError:async t=>{u(null),await c.invalidateQueries({queryKey:Fr({client:q,path:{name:e}})}),jn({title:`Could not review tracking changes`,detail:t instanceof Error?t.message:`Update the draft and review it again.`,tone:`negative`})}}),m=S({...Ar(),onSuccess:async t=>{u(null),i?.(void 0),await Ln(c,e),jn({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 Ln(c,e),jn({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-sm text-muted`,children:`Loading tracked queries…`})}):d.isError||!d.data?(0,$.jsxs)(Z,{className:`surface-card`,children:[(0,$.jsx)(`p`,{className:`text-sm text-negative`,children:`Could not load tracked queries.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:()=>void d.refetch(),children:`Try again`})]}):(0,$.jsx)(Wp,{workspace:d.data,selection:t,onSelectionChange:n,trackingQueryId:r,onTrackingQueryIdChange:i,pendingTrackingSource:a,onPendingTrackingSourceHandled:o,publishGuard:s,templates:f.data?.templates??[],preview:l,isPreviewing:p.isPending,isCommitting:m.isPending,onPreview:t=>{u(null),p.mutate({client:q,path:{name:e},body:{...t,expectedWorkspaceVersion:d.data.workspaceVersion}})},onCommit:t=>m.mutate({client:q,path:{name:e},body:t})})}function Em({projectName:e,onReviewDiscoveryProbe:t}){let n=x(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(`100`),u=C({...vr({client:q,path:{name:e},query:{limit:`10`}}),refetchInterval:e=>e.state.data?.some(e=>Bp.has(e.status))?3e3:!1}),d=u.data??[];(0,Q.useEffect)(()=>{!r&&d[0]&&i(d[0].id)},[r,d]);let f=d.find(e=>e.id===r)??null,p=C({...Ir({client:q,path:{name:e,id:r??``}}),enabled:!!r,refetchInterval:f&&Bp.has(f.status)?3e3:!1}),m=p.data??null,h=S({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),ot(e,t)},onSuccess:async t=>{i(t.sessionId),o(``),await Nm(n,e,t.sessionId),jn({title:`Discovery started`,detail:`Run ${Mm(t.sessionId)} is testing questions your customers might ask.`,tone:`neutral`,dedupeKey:`discovery:start:${t.sessionId}`,dedupeMode:`replace`})},onError:e=>{jn({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 y(){try{let t=await u.refetch();if(t.error)throw t.error;let n=t.data?.length??0;jn({title:`Discovery sessions refreshed`,detail:`${n} recent session${n===1?``:`s`} loaded.`,tone:`positive`,dedupeKey:`discovery:refresh:${e}`,dedupeMode:`replace`})}catch(t){jn({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-sm leading-6 text-secondary`,children:U()?`Generate customer questions and check whether your site is already visible.`:`Generate customer questions, check current visibility, then choose what to track.`})]}),(0,$.jsxs)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:u.isFetching,onClick:()=>void y(),children:[(0,$.jsx)(v,{className:`size-3.5 ${u.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)(Y,{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-sm 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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,placeholder:`e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.`,value:a,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{className:`block`,children:[(0,$.jsx)(`span`,{className:`text-sm 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-sm text-strong placeholder-mono-600 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-sm text-secondary`,children:`More questions means broader coverage but a longer run. 100 is a good default.`})]}),!U()&&(0,$.jsxs)(pa,{type:`button`,size:`sm`,disabled:h.isPending,onClick:()=>h.mutate(),children:[(0,$.jsx)(l,{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`})]}),u.isFetching&&(0,$.jsx)(Y,{tone:`neutral`,children:`Loading`})]}),d.length===0?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No discovery runs yet. Describe your customer above to start your first one.`}):(0,$.jsx)(`div`,{className:`space-y-2`,children:d.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-sm font-medium text-heading`,children:Mm(e.id)}),(0,$.jsx)(Y,{tone:Om(e.status),children:e.status})]}),(0,$.jsxs)(`div`,{className:`mt-2 grid grid-cols-3 gap-2 text-sm 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?Mm(g.id):`No run selected`})]}),g&&(0,$.jsx)(Y,{tone:Om(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)(Dm,{label:`Questions tested`,value:g.probeCount??0}),(0,$.jsx)(Dm,{label:`Cited queries`,value:g.citedCount??0,tone:`positive`}),(0,$.jsx)(Dm,{label:`Worth tracking`,value:g.aspirationalCount??0,tone:`caution`}),(0,$.jsx)(Dm,{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-sm 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-sm text-caution`,children:g.warning}),g.icpDescription&&(0,$.jsxs)(`div`,{className:`rounded-md border border-default bg-surface px-3 py-2`,children:[(0,$.jsx)(`p`,{className:`text-[10px] uppercase tracking-wide text-muted`,children:`Customer profile`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-neutral`,children:g.icpDescription})]}),g.competitorMap.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`mb-2 text-sm font-medium 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-xs text-neutral`,children:[e.domain,` `,(0,$.jsx)(`span`,{className:`text-muted`,children:e.hits})]},e.domain))})]})]}):(0,$.jsx)(`p`,{className:`text-sm 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-sm leading-6 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-xs leading-5 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)(Y,{tone:`neutral`,children:`Loading`})]}),_.length===0?(0,$.jsx)(`p`,{className:`text-sm 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:`font-medium text-heading`,children:e.query}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{tone:km(e.bucket),children:jm(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:!U()&&t&&(e.bucket===`cited`||e.bucket===`aspirational`)&&(0,$.jsx)(pa,{type:`button`,variant:`ghost`,size:`sm`,onClick:()=>t(e.id),children:`Review for tracking`})})]},e.id))})]})})]})]})]})]})}function Dm({label:e,value:t,tone:n=`neutral`}){return(0,$.jsxs)(`div`,{className:`rounded-md border border-default bg-surface px-4 py-3`,children:[(0,$.jsx)(`p`,{className:`text-[10px] uppercase tracking-wide text-muted`,children:e}),(0,$.jsx)(`p`,{className:`mt-1 text-2xl font-semibold tabular-nums ${n===`positive`?`text-positive`:n===`caution`?`text-caution`:n===`negative`?`text-negative`:`text-heading`}`,children:t})]})}function Om(e){return e===`completed`?`positive`:e===`failed`?`negative`:Bp.has(e)?`caution`:`neutral`}function km(e){return e===`cited`?`positive`:e===`aspirational`?`caution`:e===`wasted-surface`?`negative`:`neutral`}var Am={cited:`Cited queries`,aspirational:`Worth tracking`,"wasted-surface":`Skip`};function jm(e){return e?Am[e]:`Not classified`}function Mm(e){return e.length>8?e.slice(0,8):e}async function Nm(e,t,n){await Promise.all([Mn(e,`discovery`),e.invalidateQueries({queryKey:Mr({client:q})})])}function Pm({projectName:e}){let[t,n]=(0,Q.useState)(`changes`),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(null),s=C({...$n({client:q,path:{name:e},query:{limit:30}}),enabled:t===`health`}),c=C({...Rr({client:q,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=C({...Bn({client:q,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)(zo,{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:He()?Ao:`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:W(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:W(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-xs 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-sm 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-xs 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-sm 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:He()?Ao:`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)(Y,{tone:e.changed?`caution`:`neutral`,children:[e.run1State??`none`,` → `,e.run2State??`none`]})}),(0,$.jsx)(`td`,{children:(0,$.jsxs)(Y,{tone:e.visibilityChanged?`caution`:`neutral`,children:[e.run1MentionState??`none`,` → `,e.run2MentionState??`none`]})})]},e.queryId??e.query??`unknown`))})]})}):null]}):null]})}var Fm={state:`not-connected`,selection:null,snapshotCount:0,evidence:`No stored evidence yet.`,lastSnapshotAt:null},Im={contract:null,assessment:null,googleAds:Fm,gtm:Fm,snapshots:[]};function Lm(e){return e.contractSelectionRequired?`contract-selection-required`:e.assessmentState===`loading`?`assessment-loading`:e.assessmentState===`unavailable`?`assessment-unavailable`:Hm(e)?`static-mismatch`:e.assessment?.status??(e.contract?`configured`:`not-configured`)}function Rm(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 zm(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 Bm(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 Vm(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`&&Um(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 Hm(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome===`fail`)}function Um(e){return e.assessment?.status===`configured`&&e.assessment.findings.some(e=>e.outcome!==`pass`)}function Wm(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 Gm(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 Km(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 qm(e){return e.length<=12?e:`…${e.slice(-10)}`}function Jm(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 Ym(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 Xm={"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 Zm(e){return e.outcome===`pass`?{label:Xm[e.code],tone:`positive`,outcome:`Pass`}:e.outcome===`fail`?{label:Xm[e.code],tone:`negative`,outcome:`Fail`}:{label:Xm[e.code],tone:`caution`,outcome:`Unknown`}}function Qm(e){return e.runtime.productionHosts.length>0?e.runtime.productionHosts.join(`, `):`the declared production site`}function $m(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 eh(e){return e.provider===`google-ads`?`Google Ads`:`Tag Manager`}function th({label:e,connection:t,changeSelectionLabel:n,onChangeSelection:r,actionPending:i}){let a=Wm(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:`font-medium text-heading`,children:e}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{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-sm text-secondary`,children:o}):(0,$.jsxs)(`p`,{className:`mt-1 text-[11px] text-muted`,children:[t.snapshotCount,` stored `,t.snapshotCount===1?`snapshot`:`snapshots`,t.lastSnapshotAt?`, latest ${gn(t.lastSnapshotAt)}`:``]}),t.snapshotError?(0,$.jsx)(`p`,{role:`alert`,className:`mt-1 text-sm text-negative`,children:t.snapshotError}):null]}),(0,$.jsx)(`td`,{children:n&&r?(0,$.jsx)(pa,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:r,children:n}):(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:`Use the next step above`})})]})}var nh=`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.`,rh=`Available once Google Ads and Tag Manager are connected.`,ih=`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 ah({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:zm(e)},{title:`Tag Manager`,state:e.gtm.state,ready:s,summary:e.gtm.selection,changeLabel:`Change Tag Manager container`,onChange:r,action:l?d:Bm(e)}],m=o&&s&&!u?Vm(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-xl font-semibold tracking-[-0.02em] 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-sm leading-6 text-secondary`,children:ih}):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-sm font-semibold text-heading`,children:`Conversion to check`}),(0,$.jsx)(X,{text:nh})]}),m&&t?(0,$.jsx)(pa,{type:`button`,disabled:i,onClick:()=>t(m.id),children:i?`Working…`:m.label}):(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:rh})]}),(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`}:Wm(e.state),r=e.action;return(0,$.jsxs)(`li`,{className:`flex min-w-0 flex-wrap items-center gap-2 text-sm`,children:[(0,$.jsx)(`span`,{className:`font-medium text-heading`,children:e.title}),(0,$.jsx)(Y,{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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):(0,$.jsx)(pa,{type:`button`,variant:`outline`,size:`sm`,disabled:i,onClick:()=>t(r.id),children:i?`Working…`:r.label}):null,e.summary&&e.onChange?(0,$.jsx)(pa,{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-sm text-negative`,children:a}):null]})]})}function oh({workspace:e=Im,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=Lm(e),m=Rm(p),h=Vm(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)(ah,{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-xl font-semibold tracking-[-0.02em] 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)(Y,{tone:m.tone,children:m.label}),e.assessment?.evaluatedAt?(0,$.jsxs)(`span`,{className:`text-[11px] text-muted`,children:[`Assessed `,gn(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-sm leading-6 text-secondary`,children:e.assessmentEvidenceSnapshots.map(e=>(0,$.jsxs)(`li`,{className:`break-words`,children:[eh(e),` `,e.kind,`, captured `,gn(e.capturedAt),(0,$.jsxs)(`span`,{className:`ml-1 font-mono text-[11px] 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)(J,{type:`button`,disabled:n||h.id===`waiting-for-integrity`,onClick:()=>t(h.id),children:n?`Working…`:h.label}):(0,$.jsx)(pa,{type:`button`,disabled:n,onClick:()=>t(h.id),children:n?`Working…`:h.label}):h.id===`review-findings`?(0,$.jsx)(J,{asChild:!0,type:`button`,children:(0,$.jsx)(`a`,{href:`#conversion-integrity-findings`,children:`Review findings`})}):p===`runtime-unverified`?(0,$.jsx)(J,{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-sm leading-5 text-secondary`,children:h.detail}),r?(0,$.jsx)(`p`,{role:`alert`,className:`mt-2 text-sm 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-base font-semibold text-heading`,children:e.contract?.name??(e.contractSelectionRequired?`Choose a conversion`:`No conversion declared`)})]}),i.length>0&&f?(0,$.jsx)(pa,{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-sm font-medium 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-sm 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-[11px] font-medium uppercase tracking-[0.14em] text-muted`,children:`Website event`}),(0,$.jsx)(`dd`,{className:`mt-1 text-sm font-medium text-heading`,children:e.contract.eventName})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-[11px] font-medium uppercase tracking-[0.14em] text-muted`,children:`Google Ads goal`}),(0,$.jsx)(`dd`,{className:`mt-1 text-sm text-secondary`,children:Jm(e.contract)})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`dt`,{className:`text-[11px] font-medium uppercase tracking-[0.14em] text-muted`,children:`Tag Manager`}),(0,$.jsxs)(`dd`,{className:`mt-1 text-sm 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-[11px] font-medium uppercase tracking-[0.14em] text-muted`,children:`Runtime event fields`}),(0,$.jsx)(`dd`,{className:`mt-1 text-sm text-secondary`,children:Ym(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-sm 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:qm(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:qm(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:qm(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:qm(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-sm text-negative`,children:[(0,$.jsx)(`span`,{children:s}),c?(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:c,children:`Retry contracts`}):null]}):null,e.assessmentError?(0,$.jsx)(`p`,{role:`alert`,className:`mt-4 text-sm 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-base font-semibold text-heading`,children:`Checks to review`})]}),(0,$.jsxs)(Y,{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=Zm(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-sm font-medium text-heading`,children:t.label}),(0,$.jsx)(Y,{tone:t.tone,children:t.outcome})]}),(0,$.jsxs)(`p`,{className:`mt-1 break-words text-sm text-secondary`,children:[`Related item: `,e.subject]}),(0,$.jsxs)(`p`,{className:`mt-1 font-mono text-[11px] text-muted`,children:[`Diagnostic: `,e.code]}),e.evidenceIds.length>0?(0,$.jsxs)(`p`,{className:`mt-1 break-words font-mono text-[11px] 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-base font-semibold 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=Gm(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-sm font-medium text-heading`,children:e.title})]}),(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:e.detail}),(0,$.jsx)(Y,{tone:t,children:Km(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-base font-semibold 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:[th({label:`Google Ads`,connection:e.googleAds,...e.googleAds.state===`connected`||e.googleAds.state===`stale`?{changeSelectionLabel:`Change Google Ads account`,onChangeSelection:u}:{},actionPending:n}),th({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-sm leading-6 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)(J,{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-base font-semibold 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:`font-medium 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:gn(e.capturedAt)}),(0,$.jsx)(`td`,{className:`font-mono text-[11px] text-muted`,children:qm(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=Zm(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 font-mono text-[11px] text-muted`,children:[`Diagnostic: `,e.code]}),e.evidenceIds.length>0?(0,$.jsxs)(`p`,{className:`mt-1 break-words font-mono text-[11px] text-muted`,children:[`Evidence: `,e.evidenceIds.join(`, `)]}):null]}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{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-base font-semibold text-heading`,children:`Runtime verification checklist`})]})}),(0,$.jsxs)(`ol`,{className:`max-w-2xl list-decimal space-y-2 pl-5 text-sm leading-6 text-secondary marker:text-muted`,children:[(0,$.jsxs)(`li`,{children:[`Use a controlled browser session on `,Qm(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:qm(e.contract.gtm.tagId)}),` fires with `,$m(e.contract),`.`]}),(0,$.jsxs)(`li`,{children:[`Confirm Google Ads records the matching conversion action `,(0,$.jsx)(`span`,{className:`font-mono text-heading`,children:qm(e.contract.googleAds.conversionActionId)}),`. Do not change the account or publish a Tag Manager version just to verify it.`]})]})]}):null]})}var sh=3e4,ch={name:``,eventName:``,conversionActionId:``,conversionId:``,conversionLabel:``,campaignIds:``,tagId:``,triggerIds:``,variableIds:``,productionHosts:``,requireBiddableGoal:!0,requirePrimaryAction:!0,verificationRequired:!0,requireTransactionId:!0,requireValue:!0,requireCurrency:!0},lh=`mt-1 w-full rounded-md border border-base bg-bg px-3 py-2 text-sm text-heading outline-none transition-colors placeholder-mono-600 focus:border-mono-500 focus:ring-2 focus:ring-mono-500/30`,uh=`text-sm font-medium text-secondary`;function dh(e,t,n,r){return n?{snapshotCount:e,snapshotState:`unavailable`,snapshotError:Xo(r)}:t?{snapshotCount:e,snapshotState:`loading`}:{snapshotCount:e}}function fh(e){return[...new Set(e.split(/[\n,]/).map(e=>e.trim()).filter(Boolean))]}function ph(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 mh(e,t,n){let r=[`Container ${e}`,`account ${t}`];return n&&r.push(`workspace ${n}`),r.join(` · `)}function hh(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:mh(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 gh(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:fh(e.campaignIds),requireBiddableGoal:e.requireBiddableGoal,requirePrimaryAction:e.requirePrimaryAction},gtm:{accountId:n.accountId,containerId:n.containerId,tagId:e.tagId.trim(),triggerIds:fh(e.triggerIds),variableIds:fh(e.variableIds)},runtime:{verificationRequired:e.verificationRequired,requireTransactionId:e.requireTransactionId,requireValue:e.requireValue,requireCurrency:e.requireCurrency,productionHosts:fh(e.productionHosts)}}}function _h(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 vh(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 yh(e,t,n){return e?`no longer accessible`:n?`access not verified`:t?`not in the current result`:`checking access`}function bh({id:e,label:t,value:n,onChange:r,children:i,disabled:a=!1}){return(0,$.jsxs)(`label`,{htmlFor:e,className:uh,children:[t,(0,$.jsx)(`select`,{id:e,className:lh,value:n,onChange:e=>r(e.target.value),disabled:a,children:i})]})}function xh({id:e,checked:t,onChange:n,children:r}){return(0,$.jsxs)(`label`,{htmlFor:e,className:`flex items-start gap-2 text-sm 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 Sh({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(Xo(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-sm font-medium text-heading`,children:`Remove Canonry's stored access and selection?`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm leading-6 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)(J,{ref:u,type:`button`,variant:`outline`,size:`sm`,className:`min-h-11`,disabled:a,onClick:p,children:`Keep connected`}),(0,$.jsx)(pa,{type:`button`,variant:`destructive`,size:`sm`,className:`min-h-11`,disabled:t||a,onClick:()=>void m(),children:a?`Disconnecting…`:`Disconnect ${e}`})]}),s?(0,$.jsx)(`p`,{role:`alert`,className:`mt-2 text-sm text-negative`,children:s}):null]}):(0,$.jsxs)(pa,{type:`button`,variant:`ghost`,size:`sm`,className:`min-h-11 text-negative hover:text-negative`,disabled:t,onClick:f,children:[`Disconnect `,e]})})}function Ch({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:uh,children:t});return i?(0,$.jsxs)(`div`,{children:[m,(0,$.jsx)(`select`,{id:e,className:lh,disabled:!0,children:(0,$.jsx)(`option`,{children:`Loading…`})})]}):a?(0,$.jsxs)(`div`,{children:[m,(0,$.jsx)(`input`,{id:e,required:!0,className:lh,value:c,onChange:e=>l(e.target.value)}),(0,$.jsxs)(`p`,{className:`mt-1 text-xs 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:lh,value:c,onChange:e=>l(e.target.value)}),(0,$.jsx)(`p`,{className:`mt-1 text-xs 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:lh,value:c,onChange:e=>l(e.target.value)}):(0,$.jsxs)(`select`,{id:e,required:!0,className:lh,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-xs text-link`,onClick:()=>{f(!p),l(``)},children:p?`Choose from synced list`:`Enter an ID manually`})]})}function wh({projectId:e,projectName:t}){let n=On(),[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,w]=(0,Q.useState)(``),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(``),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(ch),[N,P]=(0,Q.useState)(null),F=(0,Q.useRef)(null),I=C({...rr({client:q,path:{name:t}}),staleTime:sh}),L=C({...ai({client:q,path:{name:t}}),staleTime:sh}),R=C({...Jr({client:q,path:{name:t}}),staleTime:sh}),z=C({...zr({client:q,path:{name:t}}),staleTime:sh}),ee=z.data,B=C({...nr({client:q,path:{name:t},query:{limit:5}}),staleTime:sh}),V=C({...er({client:q,path:{name:t},query:{limit:5}}),staleTime:sh}),H=R.data??[],te=(N?H.find(e=>e.id===N)??null:null)??(H.length===1?H[0]??null:null),ne=H.length>1&&!te,re=C({...ni({client:q,path:{name:t,contractId:te?.id??``}}),enabled:!!te,staleTime:sh}),ie=C({...zn({client:q,path:{name:t}}),enabled:d===`google-ads`&&I.data?.connected===!0,staleTime:0}),U=C({...Yn({client:q,path:{name:t}}),enabled:d===`gtm`&&L.data?.connected===!0,staleTime:0}),ae=C({...mr({client:q,path:{name:t,accountId:x}}),enabled:d===`gtm`&&!!x,staleTime:0}),oe=C({...fr({client:q,path:{name:t,accountId:x,containerId:T}}),enabled:d===`gtm`&&!!x&&!!T,staleTime:0}),se=S(ei({client:q})),ce=S(Dr({client:q})),le=S(_i({client:q})),ue=S(Ti({client:q})),de=S(li({client:q})),fe=S(qr({client:q})),pe=S(di({client:q})),me=S(Zr({client:q})),he=S(Hr({client:q}));(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;w(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 ge=(0,Q.useMemo)(()=>{let e=B.data?.snapshots??[],t=V.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=re.data?.googleAdsSnapshot,a=re.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:re.data?.assessment.contract??te,assessment:re.data?.assessment??null,contractSelectionRequired:ne,assessmentState:te?re.isError?`unavailable`:re.isLoading?`loading`:void 0:void 0,assessmentError:re.isError?Xo(re.error):null,googleAds:ph(I.data,dh(B.data?.total??0,B.isLoading,B.isError,B.error),I.isError),gtm:hh(L.data,dh(V.data?.total??0,V.isLoading,V.isError,V.error),L.isError),snapshots:n,assessmentEvidenceSnapshots:r}},[te,ne,B.data,B.error,B.isError,B.isLoading,I.data,I.isError,V.data,V.error,V.isError,V.isLoading,L.data,L.isError,re.data,re.error,re.isError,re.isLoading]),_e=(0,Q.useSyncExternalStore)(Gi,Ra,Ra),ve=Object.values(_e.runs).some(t=>t.projectId===e&&(t.kind===ht[`google-ads-sync`]||t.kind===ht[`gtm-sync`])),ye=se.isPending||ce.isPending||le.isPending||ue.isPending||de.isPending||fe.isPending||pe.isPending||me.isPending||he.isPending||ve;async function be(){await Promise.all([I.refetch(),L.refetch(),R.refetch(),B.refetch(),V.refetch(),z.refetch(),te?re.refetch():Promise.resolve()])}async function xe(e){await be();for(let t=0;t<10&&!e();t+=1)await new Promise(e=>setTimeout(e,1500)),await be()}function Se(){let e=document.activeElement;F.current=e instanceof HTMLElement?e:null}function Ce(e){typeof window<`u`&&typeof window.requestAnimationFrame==`function`?window.requestAnimationFrame(e):globalThis.setTimeout(e,0)}function W(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}function we(e){e&&(!e.matches(`a[href], button, input, select, textarea, [contenteditable="true"]`)&&!e.hasAttribute(`tabindex`)&&(e.tabIndex=-1),e.focus({preventScroll:!0}))}function Te(e,t=e){let n=document.getElementById(e);n instanceof HTMLDetailsElement&&(n.open=!0);let r=n?.scrollIntoView;typeof r==`function`&&r.call(n,{behavior:W()?`auto`:`smooth`,block:`start`}),we(document.getElementById(t)??n)}function G(e,t){Se(),Ce(()=>Te(e,t))}function Ee(){let e=F.current;F.current=null,e&&Ce(()=>{e.isConnected&&e.focus({preventScroll:!0})})}function De(){i(null),c(!1),Ee()}function Oe(){i(null),f(null),Ee()}function ke(){i(null),A(!1),Ee()}function Ae(){i(null),f(null),c(!0),G(`google-ads-connect-panel`,`google-ads-connect-title`)}function je(){i(null),v(``),b(``),m(!1),f(`google-ads`),c(!1),G(`google-ads-selection-panel`,`google-ads-selection-title`)}function Me(){i(null),w(``),E(``),O(``),g(!1),f(`gtm`),c(!1),G(`gtm-selection-panel`,`gtm-selection-title`)}function Ne(){i(null),A(!0),G(`conversion-integrity-contract-form`,`conversion-integrity-contract-form-title`)}function Pe(e,n){Ya({id:e.id,projectId:e.projectId,kind:e.kind,projectLabel:t,sourceAction:n}),jn({title:n===`google-ads-sync`?`Google Ads sync queued`:`Tag Manager sync queued`,detail:`${t} will refresh when the sync completes.`,tone:`neutral`,dedupeKey:`google-marketing-sync:${e.id}`,dedupeMode:`replace`})}async function Fe(){Xi(n),i(null);try{let e=await se.mutateAsync({path:{name:t},body:{provider:`google-ads`,...l.trim()?{developerToken:l.trim()}:{}}});u(``),c(!1),o(`Finish the Google Ads consent flow in the new window. Canonry will refresh stored status after it closes.`),_h(e.authorizationUrl,()=>{be(),o(null),Ee()})}catch(e){i(Xo(e))}}async function Ie(){Xi(n),i(null);try{let e=await ce.mutateAsync({path:{name:t},body:{provider:`gtm`}});o(`Finish the Tag Manager consent flow in the new window. Canonry will refresh stored status after it closes.`),_h(e.authorizationUrl,()=>{be(),o(null),Ee()})}catch(e){i(Xo(e))}}async function Le(){if(Xi(n),!_)i(`Select a Google Ads customer before saving.`);else{i(null);try{await le.mutateAsync({path:{name:t},body:{customerId:_,...y.trim()?{loginCustomerId:y.trim()}:{}}}),f(null),Ee(),await xe(()=>I.data?.selectedCustomer!=null)}catch(e){i(Xo(e))}}}async function Re(){if(Xi(n),!x||!T)i(`Select a Tag Manager account and container before saving.`);else{i(null);try{await ue.mutateAsync({path:{name:t},body:{accountId:x,containerId:T,...D?{workspaceId:D}:{}}}),f(null),Ee(),await xe(()=>L.data?.status===`connected`)}catch(e){i(Xo(e))}}}async function ze(){Xi(n),i(null),await pe.mutateAsync({path:{name:t}}),f(null),c(!1),v(``),b(``),m(!1),o(null),await be(),jn({title:`Google Ads disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`google-ads-disconnected:${e}`,dedupeMode:`replace`}),F.current=null,Ce(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Be(){Xi(n),i(null),await me.mutateAsync({path:{name:t}}),f(null),w(``),E(``),O(``),g(!1),o(null),await be(),jn({title:`Tag Manager disconnected`,detail:`Stored evidence and conversion contracts were retained.`,tone:`neutral`,dedupeKey:`gtm-disconnected:${e}`,dedupeMode:`replace`}),F.current=null,Ce(()=>we(document.getElementById(`conversion-integrity-title`)))}async function Ve(){Xi(n),i(null);try{Pe(await de.mutateAsync({path:{name:t}}),`google-ads-sync`)}catch(e){i(Xo(e))}}async function He(){Xi(n),i(null);try{Pe(await fe.mutateAsync({path:{name:t}}),`gtm-sync`)}catch(e){i(Xo(e))}}async function Ue(){Xi(n),i(null);try{let e=await Promise.allSettled([de.mutateAsync({path:{name:t}}),fe.mutateAsync({path:{name:t}})]),[n,r]=e;n.status===`fulfilled`&&Pe(n.value,`google-ads-sync`),r.status===`fulfilled`&&Pe(r.value,`gtm-sync`);let i=e.find(e=>e.status===`rejected`);if(i?.status===`rejected`)throw i.reason}catch(e){i(Xo(e))}}async function We(){Xi(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 he.mutateAsync({path:{name:t},body:gh(j,e,{accountId:r.accountId,containerId:r.containerId})});M(ch),A(!1),Ee(),(await R.refetch()).data?.some(e=>e.id===n.id)&&P(n.id)}catch(e){i(Xo(e))}}}function K(e){switch(e){case`connect-google-ads`:Ae();return;case`connect-gtm`:Se(),Ie();return;case`select-google-ads`:je();return;case`select-gtm`:Me();return;case`sync-google-ads`:Ve();return;case`sync-gtm`:He();return;case`sync-static-evidence`:Ue();return;case`declare-contract`:Ne();return;case`review-findings`:G(`conversion-integrity-findings`,`conversion-integrity-findings`);return;case`review-runtime-verification`:G(`conversion-integrity-runtime-guidance`,`conversion-integrity-runtime-title`);return;case`retry-connection-status`:be();return;case`select-contract`:G(`conversion-integrity-contract-select`,`conversion-integrity-contract-select`);return;case`retry-integrity`:re.refetch();return;case`waiting-for-integrity`:return}}let Ge=ie.data?.customers??[],Ke=U.data?.accounts??[],qe=ae.data?.containers??[],Je=oe.data?.workspaces??[],Ye=!!_&&!Ge.some(e=>e.customerId===_),Xe=!!x&&!Ke.some(e=>e.id===x),Ze=!!T&&!qe.some(e=>e.id===T),Qe=!!D&&!Je.some(e=>e.id===D),$e=Ye&&ie.isSuccess&&ie.data.truncated===!1,et=Xe&&U.isSuccess&&U.data.truncated===!1,tt=Ze&&ae.isSuccess&&ae.data.truncated===!1,nt=Qe&&oe.isSuccess&&oe.data.truncated===!1,rt=et||tt||nt,it=et?`The saved Tag Manager account is no longer accessible. Choose an available account before saving.`:tt?`The saved Tag Manager container is no longer accessible. Choose an available container before saving.`:nt?`The saved draft workspace is no longer accessible. Choose an available workspace or No draft workspace before saving.`:null,at=yh($e,ie.data,ie.isError),ot=yh(et,U.data,U.isError),st=yh(tt,ae.data,ae.isError),ct=yh(nt,oe.data,oe.isError),lt=ie.isError?Xo(ie.error):null,ut=U.isError?Xo(U.error):ae.isError?Xo(ae.error):oe.isError?Xo(oe.error):null,dt=d===`google-ads`?lt:d===`gtm`?ut:null,ft=vh(`customer`,ie.data,Ge.length),pt=vh(`account`,U.data,Ke.length),mt=vh(`container`,ae.data,qe.length),gt=vh(`draft workspace`,oe.data,Je.length),_t=U.isError||ae.isError||oe.isError&&!!D,vt=s||d!==null||k;function yt(){ie.refetch()}function bt(){U.isError?U.refetch():ae.isError?ae.refetch():oe.isError&&oe.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-xl font-semibold tracking-[-0.02em] 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-xl font-semibold tracking-[-0.02em] text-heading`,children:`Conversion Integrity`}),(0,$.jsxs)(`p`,{role:`alert`,className:`mt-3 text-sm text-negative`,children:[`Could not load conversion contracts: `,Xo(R.error)]}),(0,$.jsx)(J,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void R.refetch(),children:`Retry contracts`})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(oh,{workspace:ge,onPrimaryAction:K,actionPending:ye,actionError:vt?null:r,contracts:H,selectedContractId:te?.id??null,onSelectContract:e=>P(e||null),contractError:R.isError?Xo(R.error):null,onRetryContracts:()=>void R.refetch(),onRetryEvidence:()=>{Promise.all([B.refetch(),V.refetch()])},onChangeGoogleAdsSelection:je,onChangeGtmSelection:Me,onAddContract:()=>K(`declare-contract`)}),a?(0,$.jsx)(`p`,{role:`status`,className:`page-section text-sm 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-base font-semibold text-heading`,children:`Connect read-only access`})]})}),r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm text-negative`,children:r}):null,(0,$.jsxs)(`form`,{className:`max-w-xl`,onSubmit:kn(async e=>{e.preventDefault(),await Fe()}),children:[(0,$.jsxs)(`label`,{htmlFor:`google-ads-developer-token`,className:uh,children:[`Developer token`,(0,$.jsx)(`input`,{id:`google-ads-developer-token`,type:`password`,autoComplete:`off`,value:l,onChange:e=>u(e.target.value),className:lh,placeholder:`Required only when this project has no saved token`})]}),(0,$.jsx)(`p`,{className:`mt-2 text-sm leading-6 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)(pa,{type:`submit`,disabled:se.isPending,children:se.isPending?`Starting…`:`Continue to Google`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:De,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-base font-semibold text-heading`,children:`Select customer context`})]})}),dt?(0,$.jsxs)(`div`,{role:`alert`,className:`mb-4 flex flex-wrap items-center gap-3 text-sm text-negative`,children:[(0,$.jsx)(`span`,{children:dt}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:yt,children:`Retry customer list`})]}):null,r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm text-negative`,children:r}):null,$e?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm 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)(bh,{id:`google-ads-customer`,label:`Customer account`,value:_,onChange:e=>{m(!0),v(e);let t=Ge.find(t=>t.customerId===e);b(t?.parentCustomerId??``)},disabled:ie.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:ie.isLoading?`Loading accessible customers…`:`Select a customer`}),Ye?(0,$.jsxs)(`option`,{value:_,disabled:$e,children:[`Saved customer `,_,` (`,at,`)`]}):null,Ge.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:uh,children:[`Manager account ID (optional)`,(0,$.jsx)(`input`,{id:`google-ads-login-customer`,className:lh,value:y,onChange:e=>{m(!0),b(e.target.value)},placeholder:`Use only when a manager context is required`})]})]}),ft?(0,$.jsx)(`p`,{role:`status`,className:`mt-3 text-sm ${ie.data?.truncated?`text-caution`:`text-secondary`}`,children:ft}):null,(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,$.jsx)(pa,{type:`button`,disabled:le.isPending||ie.isLoading||ie.isError||$e||!_,onClick:kn(Le),children:le.isPending?`Saving…`:`Save customer selection`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:Oe,children:`Cancel`})]}),I.data?.connected?(0,$.jsx)(Sh,{providerLabel:`Google Ads`,disabled:ye,onDisconnect:ze}):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-base font-semibold text-heading`,children:`Select container context`})]})}),dt?(0,$.jsxs)(`div`,{role:`alert`,className:`mb-4 flex flex-wrap items-center gap-3 text-sm text-negative`,children:[(0,$.jsx)(`span`,{children:dt}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:bt,children:U.isError?`Retry account list`:ae.isError?`Retry container list`:`Retry workspace list`})]}):null,r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm text-negative`,children:r}):null,it?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm text-negative`,children:it}):null,(0,$.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-3`,children:[(0,$.jsxs)(bh,{id:`gtm-account`,label:`Account`,value:x,onChange:e=>{g(!0),e!==x&&(E(``),O(``)),w(e)},disabled:U.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:U.isLoading?`Loading accounts…`:`Select an account`}),Xe?(0,$.jsxs)(`option`,{value:x,disabled:et,children:[`Saved account `,x,` (`,ot,`)`]}):null,Ke.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,$.jsxs)(bh,{id:`gtm-container`,label:`Container`,value:T,onChange:e=>{g(!0),e!==T&&O(``),E(e)},disabled:!x||ae.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:ae.isLoading?`Loading containers…`:`Select a container`}),Ze?(0,$.jsxs)(`option`,{value:T,disabled:tt,children:[`Saved container `,T,` (`,st,`)`]}):null,qe.map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]}),(0,$.jsxs)(bh,{id:`gtm-workspace`,label:`Draft workspace (optional)`,value:D,onChange:e=>{g(!0),O(e)},disabled:!T||oe.isLoading,children:[(0,$.jsx)(`option`,{value:``,children:oe.isLoading?`Loading workspaces…`:`No draft workspace`}),Qe?(0,$.jsxs)(`option`,{value:D,disabled:nt,children:[`Saved draft workspace `,D,` (`,ct,`)`]}):null,Je.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-sm sm:grid-cols-3`,children:[pt?(0,$.jsx)(`p`,{role:`status`,className:U.data?.truncated?`text-caution`:`text-secondary`,children:pt}):null,mt?(0,$.jsx)(`p`,{role:`status`,className:ae.data?.truncated?`text-caution`:`text-secondary`,children:mt}):null,gt?(0,$.jsx)(`p`,{role:`status`,className:oe.data?.truncated?`text-caution`:`text-secondary`,children:gt}):null]}),(0,$.jsxs)(`div`,{className:`mt-4 flex flex-wrap gap-3`,children:[(0,$.jsx)(pa,{type:`button`,disabled:ue.isPending||U.isLoading||ae.isLoading||oe.isLoading&&!!D||_t||rt||!x||!T,onClick:kn(Re),children:ue.isPending?`Saving…`:`Save container selection`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:Oe,children:`Cancel`})]}),L.data?.connected?(0,$.jsx)(Sh,{providerLabel:`Tag Manager`,disabled:ye,onDisconnect:Be}):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-base font-semibold text-heading`,children:`Declare the expected path`})]})}),r?(0,$.jsx)(`p`,{role:`alert`,className:`mb-4 text-sm text-negative`,children:r}):null,(0,$.jsxs)(`form`,{onSubmit:kn(async e=>{e.preventDefault(),await We()}),children:[(0,$.jsxs)(`div`,{className:`grid max-w-3xl gap-4 sm:grid-cols-2`,children:[(0,$.jsxs)(`label`,{htmlFor:`contract-name`,className:uh,children:[`Conversion name`,(0,$.jsx)(`input`,{id:`contract-name`,required:!0,maxLength:120,className:lh,value:j.name,onChange:e=>M(t=>({...t,name:e.target.value})),placeholder:`Booking completed`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-event-name`,className:uh,children:[`Website event`,(0,$.jsx)(`input`,{id:`contract-event-name`,required:!0,className:lh,value:j.eventName,onChange:e=>M(t=>({...t,eventName:e.target.value})),placeholder:`booking_complete`})]}),(0,$.jsx)(Ch,{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)(Ch,{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:uh,children:[`Google conversion ID (optional)`,(0,$.jsx)(`input`,{id:`contract-conversion-id`,className:lh,value:j.conversionId,onChange:e=>M(t=>({...t,conversionId:e.target.value}))})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-conversion-label`,className:uh,children:[`Google conversion label (optional)`,(0,$.jsx)(`input`,{id:`contract-conversion-label`,className:lh,value:j.conversionLabel,onChange:e=>M(t=>({...t,conversionLabel:e.target.value}))})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-trigger-ids`,className:uh,children:[`Trigger IDs`,(0,$.jsx)(`input`,{id:`contract-trigger-ids`,className:lh,value:j.triggerIds,onChange:e=>M(t=>({...t,triggerIds:e.target.value})),placeholder:`Comma-separated, optional`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-variable-ids`,className:uh,children:[`Variable IDs`,(0,$.jsx)(`input`,{id:`contract-variable-ids`,className:lh,value:j.variableIds,onChange:e=>M(t=>({...t,variableIds:e.target.value})),placeholder:`Comma-separated, optional`})]}),(0,$.jsxs)(`label`,{htmlFor:`contract-campaign-ids`,className:uh,children:[`Campaign IDs`,(0,$.jsx)(`input`,{id:`contract-campaign-ids`,className:lh,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:uh,children:[`Production hosts`,(0,$.jsx)(`input`,{id:`contract-production-hosts`,className:lh,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-sm font-medium text-heading`,children:`Required evidence`}),(0,$.jsxs)(`div`,{className:`mt-3 grid gap-3 sm:grid-cols-2`,children:[(0,$.jsx)(xh,{id:`contract-primary-action`,checked:j.requirePrimaryAction,onChange:e=>M(t=>({...t,requirePrimaryAction:e})),children:`Google Ads action is primary`}),(0,$.jsx)(xh,{id:`contract-biddable-goal`,checked:j.requireBiddableGoal,onChange:e=>M(t=>({...t,requireBiddableGoal:e})),children:`Google Ads goal is biddable`}),(0,$.jsx)(xh,{id:`contract-runtime-verification`,checked:j.verificationRequired,onChange:e=>M(t=>({...t,verificationRequired:e})),children:`Runtime proof is required`}),(0,$.jsx)(xh,{id:`contract-transaction-id`,checked:j.requireTransactionId,onChange:e=>M(t=>({...t,requireTransactionId:e})),children:`Transaction ID is required`}),(0,$.jsx)(xh,{id:`contract-value`,checked:j.requireValue,onChange:e=>M(t=>({...t,requireValue:e})),children:`Conversion value is required`}),(0,$.jsx)(xh,{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-sm leading-6 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)(pa,{type:`submit`,disabled:he.isPending,children:he.isPending?`Saving…`:`Save conversion contract`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:ke,children:`Cancel`})]})]})]}):null]})}var Th=6e4,Eh=[`7d`,`14d`,`30d`],Dh=`not available`,Oh=`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%.`,kh=`No Google Ads snapshot stored yet`,Ah=`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.`,jh=`No closed days yet`,Mh=`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.`,Nh={"insufficient-history":`Period change is hidden: the stored snapshot does not cover a prior period of equal length yet.`},Ph=new Intl.NumberFormat(void 0,{maximumFractionDigits:0}),Fh=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Ih=new Intl.NumberFormat(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Lh(e,t){return e===null||!Number.isFinite(e)?Dh:t===null?Ih.format(e/1e6):ns(e,t)}function Rh(e){return e===null||!Number.isFinite(e)?Dh:W(e)}function zh(e,t){return e===null||!Number.isFinite(e)?`${Dh} vs prior ${t}d`:e===0?`no change vs prior ${t}d`:`${e>0?`↑`:`↓`} ${W(Math.abs(e))} vs prior ${t}d`}function Bh(e){return e===`enabled`?`positive`:e===`paused`?`caution`:`neutral`}function Vh(e){return e===`enabled`?`Enabled`:e===`paused`?`Paused`:e===`removed`?`Removed`:`Unknown`}function Hh(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 Uh({projectName:e}){let[t,n]=(0,Q.useState)(`14d`),[r,i]=(0,Q.useState)(()=>new Set([`costMicros`,`conversions`])),a=C({...Ur({client:q,path:{name:e},query:{window:t}}),staleTime:Th}),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-xl font-semibold tracking-[-0.02em] text-heading`,children:`Ad performance`}),(0,$.jsx)(X,{text:Oh})]}),o?.source?(0,$.jsxs)(`p`,{className:`text-xs text-muted`,children:[Ii(o.startDate),` to `,Ii(o.endDate),` · `,o.days,` closed `,o.days===1?`day`:`days`]}):null]}),(0,$.jsx)(uc,{windows:Eh,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-sm text-negative`,children:[`Could not load Google Ads performance: `,Xo(a.error)]}),(0,$.jsx)(J,{type:`button`,variant:`outline`,className:`mt-3`,onClick:()=>void a.refetch(),children:`Retry performance`})]});let{totals:c,daily:l,campaigns:u,comparison:d,comparisonUnavailableReason:f,source:p}=o;if(!p){let e=f===`insufficient-history`;return(0,$.jsxs)(`section`,{className:`page-section`,"aria-labelledby":`google-ads-performance-title`,children:[s,(0,$.jsxs)(`div`,{className:`mt-4 max-w-2xl rounded-md border border-default bg-surface-subtle p-5`,children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-heading`,children:e?jh:kh}),(0,$.jsx)(`p`,{className:`mt-2 text-sm leading-6 text-secondary`,children:e?Mh:Ah})]})]})}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:Lh(c.costMicros,m),change:d?.change.costMicros??null,direction:`none`,seriesKey:`costMicros`},{key:`conversions`,comparable:!0,label:`Conversions`,value:Fh.format(c.conversions),change:d?.change.conversions??null,direction:`up-good`,seriesKey:`conversions`},{key:`cost-per-conversion`,label:`Cost / conv.`,value:g?`no conversions`:Lh(c.costPerConversionMicros,m),change:null,comparable:!1,direction:`down-good`,seriesKey:null},{key:`conversion-rate`,comparable:!0,label:`Conv. rate`,value:Rh(c.conversionRate),change:d?.change.conversionRate??null,direction:`up-good`,seriesKey:null}],v=[{key:`clicks`,label:`Clicks`,value:Ph.format(c.clicks),seriesKey:`clicks`},{key:`impressions`,label:`Impressions`,value:Ph.format(c.impressions),seriesKey:`impressions`},{key:`ctr`,label:`CTR`,value:Rh(c.ctr),seriesKey:null},{key:`cpc`,label:`CPC`,value:Lh(c.cpcMicros,m),seriesKey:null}],y={costMicros:{label:`Spend`,color:ki[1],axisId:`spend`,formatValue:e=>Lh(e,m)},conversions:{label:`Conversions`,color:ki[0],axisId:`conversions`,formatValue:e=>Fh.format(e)},clicks:{label:`Clicks`,color:ki[2],axisId:`clicks`,formatValue:e=>Ph.format(e)},impressions:{label:`Impressions`,color:ki[3],axisId:`impressions`,formatValue:e=>Ph.format(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-sm text-caution`,children:[`Totals cover `,Ph.format(h.queried),` of`,` `,Ph.format(h.inInventory),` campaigns, so they are a subset of the account.`]}),p.truncated?(0,$.jsx)(`p`,{role:`status`,className:`mt-3 text-sm 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-sm text-secondary`,children:Nh[`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-xs 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-lg tabular-nums text-strong`,children:e.value}),d&&e.comparable?(0,$.jsx)(`span`,{className:`block text-[11px] tabular-nums ${Hh(e.change,e.direction)}`,children:zh(e.change,d.days)}):(0,$.jsx)(`span`,{className:`block text-[11px] text-muted`,children:e.comparable?`no prior ${t} period stored`:`\xA0`})]});return e.seriesKey===null?(0,$.jsx)(`div`,{className:`rounded-md border border-subtle bg-surface-subtle 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-xs 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-sm 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)(Ai,{data:l,xKey:`date`,series:b,xTickFormatter:ji,labelFormatter:Ii}),(0,$.jsx)(`ul`,{className:`sr-only`,children:l.map(e=>(0,$.jsxs)(`li`,{children:[Ii(e.date),`:`,` `,b.map(t=>`${t.label} ${y[t.dataKey].formatValue(e[t.dataKey])}`).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-base font-semibold text-heading`,children:`Campaign performance`})]})}),(0,$.jsx)(`div`,{className:`overflow-x-auto`,children:(0,$.jsxs)(`table`,{className:`data-table w-full text-sm`,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)(Y,{tone:Bh(e.status),children:Vh(e.status)})}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Ph.format(e.totals.impressions)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Ph.format(e.totals.clicks)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-strong`,children:Lh(e.totals.costMicros,m)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Fh.format(e.totals.conversions)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums text-secondary`,children:Rh(e.totals.ctr)}),(0,$.jsx)(`td`,{className:`text-right tabular-nums`,children:e.totals.costMicros>0&&e.totals.conversions===0?(0,$.jsx)(Y,{tone:`caution`,children:`no conversions`}):(0,$.jsx)(`span`,{className:`text-secondary`,children:Lh(e.totals.costPerConversionMicros,m)})})]},e.campaignId))})]})}),(0,$.jsxs)(`p`,{className:`mt-3 text-[11px] text-muted`,children:[`Snapshot `,Mi(Pi(p.capturedAt)),` · `,`customer `,p.customerId,` · `,`latest closed day `,Ii(p.asOfDate),p.openDate?(0,$.jsxs)($.Fragment,{children:[` · `,Ii(p.openDate),` still open, excluded`]}):null,p.timeZone?(0,$.jsxs)($.Fragment,{children:[` · `,`days close in `,p.timeZone]}):null]})]})]})}var Wh=20,Gh=50,Kh=50,qh=50;function Jh(e){return e===`viewer`}function Yh(e){return e?.status===`unavailable`}function Xh(e,t,n){return n?e.includes(t)?[...e]:[...e,t]:e.filter(e=>e!==t)}function Zh(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 Qh(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 $h(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 eg(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 tg(e){return e===`matched`?`positive`:e===`duplicate`?`neutral`:e===`ambiguous`||e===`proposed`||e===`excluded`?`caution`:`negative`}function ng(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 rg(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 ig(e){return e.state===`missing`||e.source===`unavailable-tracked-query`||!e.source}function ag(e){return ig(e)?`Unavailable tracked query`:e.text?.trim()||`Unavailable tracked query`}function og({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,Kh),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-sm font-medium 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-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 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)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:d.length===0,onClick:p,children:`Select all shown`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,disabled:t.length===0,onClick:()=>n([]),children:`Clear selection`})]}):null]}),u.length===0?(0,$.jsx)(`p`,{className:`mt-3 text-sm text-secondary`,children:`No Properties match this search.`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`p`,{className:`mt-3 text-sm 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-sm 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(Xh(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)(J,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 min-h-11`,onClick:()=>c(!0),children:`Show all Properties`}):null]})]})}function sg(){return(0,$.jsxs)(`div`,{className:`flex items-center gap-2 text-sm text-secondary`,children:[(0,$.jsx)(Y,{tone:`neutral`,children:`Viewer access`}),(0,$.jsx)(`span`,{children:`You can inspect this setup.`})]})}function cg({message:e}){return(0,$.jsxs)(`div`,{role:`status`,className:`border-y border-caution-800/40 bg-caution-950/20 py-4 text-sm text-caution`,children:[(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Y,{tone:`caution`,children:`Unavailable`}),(0,$.jsx)(`h4`,{className:`font-medium`,children:`Measurement setup unavailable`})]}),(0,$.jsx)(`p`,{className:`mt-2 max-w-2xl text-secondary`,children:e})]})}function lg({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/Gh)),p=Math.min(t,f-1),m=u.slice(p*Gh,(p+1)*Gh),h=Math.max(1,Math.ceil(d.length/Gh)),g=Math.min(r,h-1),_=d.slice(g*Gh,(g+1)*Gh),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-sm font-medium text-heading`,children:`Import groups from CSV`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm 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-sm font-medium 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-sm text-secondary file:mr-3 file:min-h-11 file:rounded-md file:border file:border-default file:bg-surface file:px-3 file:text-sm file:font-medium file:text-primary`})]}),(0,$.jsxs)(`label`,{className:`block max-w-xl`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium 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
4
- Harbor House,Dallas,https://example.com/harbor-house`,className:`mt-1 block w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:!v,onClick:()=>{e.onReview()},children:e.isReviewing?`Reviewing CSV…`:`Review CSV`}),(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:`Use columns named property and group. URL is optional.`})]}),e.error?(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-negative`,children:e.error}):null,e.notice?(0,$.jsx)(`p`,{role:`status`,className:`text-sm 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-sm font-medium text-heading`,children:`Review group membership`}),(0,$.jsxs)(`p`,{className:`mt-1 text-sm 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:`font-medium 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-sm font-medium 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)(Y,{tone:tg(e.status),children:ng(e.status)}),rg(e)?(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:rg(e)}):null]})]},e.dataRow))})]})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Page `,p+1,` of `,f,` · `,s.rows.length,` rows`]}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:p===0,onClick:()=>n(e=>Math.max(0,e-1)),children:`Previous 50 rows`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`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-sm font-medium text-heading`,children:[`Fix `,c,` row`,c===1?``:`s`,` before applying`]}),(0,$.jsx)(`p`,{className:`mt-2 text-sm text-secondary`,children:`Correct these rows, or explicitly continue with only the reviewed matches. Rows needing attention are not added.`}),(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)(Y,{tone:tg(e.status),children:ng(e.status)}),rg(e)?(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:rg(e)}):null]})]},e.dataRow))})]})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Exception page `,g+1,` of `,h]}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:g===0,onClick:()=>i(e=>Math.max(0,e-1)),children:`Previous 50 exceptions`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`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-sm 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)(J,{type:`button`,size:`sm`,variant:`outline`,className:`mt-3 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)(J,{type:`button`,className:`mt-3 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 ug=`—`;function dg({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:B=!1,onBack:V,onContinue:H}){let[te,ne]=(0,Q.useState)(``),[re,ie]=(0,Q.useState)(!1),[U,ae]=(0,Q.useState)(!1),[oe,se]=(0,Q.useState)(``),[ce,le]=(0,Q.useState)(``),[ue,de]=(0,Q.useState)(null);if(Yh(t))return(0,$.jsx)(`section`,{"aria-label":`Queries`,children:(0,$.jsx)(cg,{message:t.message})});let fe=Jh(e),pe=v,me=y,he=Qh(pe,n,_),ge=he.length,_e=ge>0&&i.length>0&&!a&&!o&&!I&&F!==null&&L===null,ve=u??d,ye=te.trim().toLocaleLowerCase(),be=ye?r.filter(e=>ag(e).toLocaleLowerCase().includes(ye)):r,xe=be.filter(e=>(e.propertyIds?.length??0)===0),Se=U?xe:be,Ce=re?Se:Se.slice(0,qh),W=Ce.filter(e=>!ig(e)),we=[...new Set(oe.split(`
5
- `).map(e=>e.trim()).filter(Boolean))],Te=[...ce.matchAll(/\{([a-z][\w-]*)\}/gi)].map(e=>e[1]),G=n.filter(e=>he.includes(e.id)),Ee=Te.length===0||ce.trim()===``?[]:G.map(e=>({propertyId:e.id,text:Te.reduce((t,n)=>t.replaceAll(`{${n}}`,e.label),ce.trim())})),De=[...new Set(Ee.map(e=>e.text))];function Oe(){let e=new Set([...i,...W.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-sm text-secondary`,children:`Choose queries, then apply them to locations.`})]})}),fe?(0,$.jsx)(sg,{}):null,fe?null:(0,$.jsxs)(`fieldset`,{className:`border-y border-default py-4`,children:[(0,$.jsx)(`legend`,{className:`text-sm font-medium 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-sm font-medium text-heading`,children:`Locations or group`}),(0,$.jsxs)(`select`,{"aria-label":`Apply to`,value:pe.kind===`none`?``:pe.kind===`all`?`all`:pe.kind===`specific`?`specific`:`group:${pe.groupIds[0]??``}`,onChange:e=>{let t=e.currentTarget.value;t===`all`?me({kind:`all`}):t===`specific`?me({kind:`specific`,propertyIds:[]}):t.startsWith(`group:`)&&me({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-sm 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=Qh({kind:`groups`,groupIds:[e.id]},n,_).length;return(0,$.jsx)(`option`,{value:`group:${e.id}`,disabled:t===0,children:eg(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-sm font-medium 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-sm 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-sm text-secondary`,children:`The answer engine is saved on assignments for these locations or groups.`}):null,pe.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:pe.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-sm text-primary`,children:[eg(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=pe.groupIds.filter(e=>e!==t.id);me(e.length>0?{kind:`groups`,groupIds:e}:{kind:`none`})},children:`×`})]},t.id):null})}),_.some(e=>!pe.groupIds.includes(e.id)&&Qh({kind:`groups`,groupIds:[e.id]},n,_).length>0)?(0,$.jsxs)(`label`,{className:`block max-w-sm`,children:[(0,$.jsx)(`span`,{className:`text-sm font-medium text-heading`,children:`Add another group`}),(0,$.jsxs)(`select`,{"aria-label":`Add another group`,value:``,onChange:e=>{e.currentTarget.value&&me({kind:`groups`,groupIds:[...pe.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-sm 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=>!pe.groupIds.includes(e.id)).map(e=>{let t=Qh({kind:`groups`,groupIds:[e.id]},n,_).length;return(0,$.jsx)(`option`,{value:e.id,disabled:t===0,children:eg(e,n)},e.id)})]})]}):null,ge===0?(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-caution`,children:`This group has no included Properties. Add Properties to the group, then try again.`}):null]}):null,pe.kind===`specific`?(0,$.jsx)(`div`,{className:`mt-4`,children:(0,$.jsx)(og,{legend:`Specific locations`,properties:n,selectedPropertyIds:pe.propertyIds,showBulkActions:!1,onSelectedPropertyIdsChange:e=>{me({kind:`specific`,propertyIds:e})}})}):null,(0,$.jsx)(`p`,{className:`mt-3 max-w-2xl text-sm text-secondary`,children:`Groups are shortcuts resolved when you assign. Changing membership later does not rewrite existing assignments, and a Property added later does not receive earlier group queries.`})]}),fe||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-sm font-medium text-heading`,children:`Market routing`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-sm 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-sm font-medium 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-sm 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-sm font-medium 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-sm 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)(J,{type:`button`,size:`sm`,className:`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-sm text-secondary`,children:P}):null]}),(0,$.jsxs)(`div`,{className:`mt-2 min-h-5`,children:[A?(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:`Calculating market impact…`}):null,j?(0,$.jsxs)(`p`,{className:`text-sm 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-sm text-negative`,children:M}),N?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,onClick:N,children:`Retry impact`}):null]}):null]})]}),fe||!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-sm font-medium text-heading`,children:`Add queries`}),(0,$.jsxs)(`div`,{className:`pt-3`,children:[(0,$.jsx)(`h4`,{className:`m-0 text-sm font-medium 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-sm 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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,rows:4,value:oe,onChange:e=>se(e.currentTarget.value),placeholder:`best apartments in dallas
6
- luxury apartments atlanta
7
- pet friendly apartments austin`}),h?(0,$.jsx)(`p`,{role:`alert`,className:`mt-2 text-sm text-negative`,children:h}):null,(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:we.length===0||m||o,onClick:()=>{Promise.resolve(f(we)).then(()=>se(``),()=>{})},children:m?`Adding…`:`Add ${we.length||``} ${we.length===1?`query`:`queries`}`.replace(` `,` `)}),g?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`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-sm font-medium text-heading`,children:`Write one query for every Property`}),(0,$.jsxs)(`p`,{className:`mt-1 mb-2 text-sm 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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,value:ce,onChange:e=>le(e.target.value),placeholder:`apartments near {property}`}),ce.trim()===``?null:Te.length===0?(0,$.jsxs)(`p`,{className:`mt-2 text-sm text-caution`,children:[`Add `,`{property}`,` to the pattern, or use the box above for a single query.`]}):G.length===0?(0,$.jsx)(`p`,{className:`mt-2 text-sm text-caution`,children:`Select at least one Property to write queries for.`}):(0,$.jsxs)(`div`,{className:`mt-2 rounded-md border border-base bg-bg-elevated p-3`,children:[(0,$.jsxs)(`p`,{className:`m-0 text-sm text-secondary`,children:[De.length,` `,De.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:De.slice(0,3).map(e=>(0,$.jsx)(`li`,{className:`text-sm text-strong`,children:e},e))}),De.length>3?(0,$.jsxs)(`p`,{className:`mt-1 mb-0 text-sm text-secondary`,children:[`and `,De.length-3,` more`]}):null]}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`mt-2 min-h-11`,disabled:Ee.length===0||m||o||!p,onClick:()=>{p&&Promise.resolve(p(Ee)).then(()=>le(``),()=>{})},children:m?`Adding…`:`Add ${Ee.length||``} ${Ee.length===1?`query`:`queries`}`.replace(` `,` `)}),Ee.length>0?(0,$.jsxs)(`p`,{className:`mt-2 mb-0 text-sm text-secondary`,children:[`Each query is measured on the one Property it names, so this adds`,` `,Ee.length,` assignment`,Ee.length===1?``:`s`,`.`]}):null]})]})]}),fe?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)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,disabled:W.length===0,onClick:Oe,children:`Select all shown queries`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,disabled:i.length===0,onClick:()=>c([]),children:`Clear query selection`}),(0,$.jsx)(J,{type:`button`,size:`sm`,className:`min-h-11`,disabled:!_e,onClick:()=>{l({queryIds:i,propertyIds:he,...pe.kind===`groups`?{groupIds:pe.groupIds}:{}})},children:a?`Assigning queries…`:`Assign ${i.length||``} ${i.length===1?`query`:`queries`}${pe.kind===`none`?``:` to ${$h(pe,_,ge)}`}`.replace(` `,` `)}),(0,$.jsxs)(`div`,{className:`min-h-[2.75rem]`,children:[I?(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:`Calculating assignment impact…`}):null,F?(0,$.jsxs)(`p`,{className:`text-sm 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`,pe.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-sm text-negative`,children:L}),R?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,onClick:R,children:`Retry impact`}):null,V?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,onClick:V,children:`Back to Groups`}):null]}):pe.kind===`none`?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`Choose where to apply first.`}):(0,$.jsxs)(`p`,{className:`text-sm text-secondary`,children:[i.length,` `,i.length===1?`query`:`queries`,` × `,ge,` Properties = `,i.length*ge,` assignments`]})]}),z?(0,$.jsx)(`p`,{role:`status`,className:`text-sm 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-sm font-medium text-heading`,children:`Search queries`}),(0,$.jsx)(`input`,{type:`search`,value:te,onChange:e=>{ne(e.currentTarget.value),ie(!1)},className:`mt-1 block min-h-11 w-full rounded-md border border-default bg-surface px-3 py-2 text-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400`,placeholder:`Query text`})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,$.jsxs)(`p`,{className:`m-0 text-sm text-secondary`,children:[`Showing `,Ce.length,` of `,Se.length,` queries,`,` `,be.length-xe.length,` of `,be.length,` applied`]}),fe||xe.length===0?null:(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,onClick:()=>{ae(e=>!e),ie(!1)},children:U?`Show all queries`:`Show the ${xe.length} not applied`})]})]}):null,Ce.length>0?(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:[fe?null:(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Select query`})}),(0,$.jsx)(`th`,{children:`Query`}),(0,$.jsx)(`th`,{children:`Properties`}),fe?null:(0,$.jsx)(`th`,{children:(0,$.jsx)(`span`,{className:`sr-only`,children:`Clear query assignments`})})]})}),(0,$.jsx)(`tbody`,{children:Ce.map(e=>{let t=ig(e),r=ag(e),a=i.includes(e.id),s=(e.propertyIds?.length??0)>0;return(0,$.jsxs)(`tr`,{children:[fe?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(Xh(i,e.id,t.currentTarget.checked)),className:`size-6 accent-accent`})})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(`p`,{className:`font-medium text-heading`,children:r})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Zh(e.propertyIds??[],n)}),fe?null:(0,$.jsx)(`td`,{className:`text-right`,children:s?(0,$.jsxs)(`div`,{className:`flex flex-wrap justify-end gap-1`,children:[ee?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,disabled:o||B,onClick:()=>de({queryId:e.id,propertyIds:[...e.propertyIds??[]]}),"aria-label":`Replace query assignments for ${r}`,children:`Replace assignments`}):null,(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`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-sm text-secondary`,children:`No queries match this search.`}):null,fe||!ue?null:(()=>{let e=r.find(e=>e.id===ue.queryId),t=e?ag(e):`this query`,i=ue.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-sm font-medium text-heading`,children:`Replace assigned Properties`}),(0,$.jsxs)(`p`,{className:`mt-1 max-w-2xl text-sm text-secondary`,children:[`This replaces every Property assigned to “`,t,`”.`]}),(0,$.jsx)(`div`,{className:`mt-3`,children:(0,$.jsx)(og,{legend:`Properties for this query`,properties:n,selectedPropertyIds:i,onSelectedPropertyIdsChange:e=>de(t=>t&&{...t,propertyIds:[...e]})})}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3`,children:[(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,disabled:B||o,onClick:()=>de(null),children:`Keep current assignments`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:i.length===0||B||o||!ee,onClick:()=>{ee&&Promise.resolve(ee({queryId:ue.queryId,propertyIds:i}))},children:B?`Replacing assignments…`:`Replace with ${i.length} ${i.length===1?`Property`:`Properties`}`})]})]})})(),Ce.length<Se.length?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,onClick:()=>ie(!0),children:`Show all queries`}):null,fe?null:(0,$.jsxs)($.Fragment,{children:[s?null:(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-caution`,children:`Apply at least one query to a Property before continuing.`}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 ${V?`justify-between`:`justify-end`}`,children:[V?(0,$.jsx)(J,{type:`button`,variant:`outline`,className:`min-h-11`,disabled:o,onClick:V,children:`Back`}):null,(0,$.jsx)(J,{type:`button`,variant:_e?`outline`:`default`,className:`min-h-11`,disabled:!s||o,onClick:H,children:`Continue`})]})]})]})}function fg({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(Yh(t))return(0,$.jsx)(`section`,{"aria-label":`Groups`,children:(0,$.jsx)(cg,{message:t.message})});let m=Jh(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-sm text-secondary`,children:`Use groups to organize Properties, apply queries in bulk, and compare competitors.`})]})}),m?(0,$.jsx)(sg,{}):null,m||!d?null:(0,$.jsx)(lg,{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-sm font-medium 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-sm text-strong placeholder-mono-600 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-sm font-medium text-heading`,children:[g,` of `,n.length,` Properties selected`]}),(0,$.jsx)(`div`,{className:`pt-3`,children:(0,$.jsx)(og,{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-sm font-medium 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-sm text-strong placeholder-mono-600 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)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,disabled:!h,onClick:()=>{s(i)},children:a?`Saving group…`:`Save group`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,disabled:!_,onClick:y,children:`Clear form`}),(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`Competitor domains are used only in this group's competitor report. Membership changes affect future assignments only.`})]}),_?(0,$.jsx)(`p`,{role:`status`,className:`text-sm 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:`font-medium text-heading`,children:e.name}),(0,$.jsx)(`td`,{className:`text-secondary`,children:Zh(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)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,"aria-label":`Edit ${e.name}`,onClick:()=>c(e),children:`Edit`}):null,l?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`ghost`,className:`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-sm 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)(J,{type:`button`,variant:`outline`,className:`min-h-11`,onClick:f,children:`Back`}):null,(0,$.jsx)(J,{type:`button`,className:`min-h-11`,disabled:_,onClick:p,children:r.length===0&&!_?`Continue without groups`:`Continue`})]})]})}function pg({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)(Wh),[_,v]=(0,Q.useState)(Wh),[y,b]=(0,Q.useState)(Wh);if(Yh(t))return(0,$.jsx)(`section`,{"aria-label":`Review and publish`,children:(0,$.jsx)(cg,{message:t.message})});let x=Jh(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-sm text-secondary`,children:`Confirm the setup details before publishing.`})]})}),x?(0,$.jsx)(sg,{}):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-sm font-medium text-heading`,children:`Sitemap changes need review`}),i.exceptionCount>0?(0,$.jsxs)(`p`,{className:`mt-1 text-sm 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-sm 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-sm font-medium text-heading`,children:[`URLs not added to Properties (`,i.exceptionCount,`)`]}),S.length>0?(0,$.jsx)(`ul`,{className:`mt-3 space-y-3 text-sm`,children:w.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`p`,{className:`font-medium 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-sm text-secondary`,children:`Review the affected sitemap URLs before confirming.`}),(0,$.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-3 text-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,w.length,` of `,S.length]}),w.length<S.length?(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`min-h-11`,onClick:()=>g(e=>e+Gh),children:`Show next 50 URLs`}):null]})]}):null,x?(0,$.jsx)(`p`,{className:`text-sm 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-sm font-medium text-heading`,children:`For changed Property URLs`}),(0,$.jsxs)(`p`,{className:`text-sm 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-sm font-medium 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-sm font-medium text-primary`,children:e.property}),(0,$.jsxs)(`div`,{className:`mt-2 grid gap-3 text-sm md:grid-cols-2`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{className:`font-medium 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:`font-medium 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-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,T.length,` of `,C.length]}),T.length<C.length?(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`min-h-11`,onClick:()=>v(e=>e+Gh),children:`Show next 50 URL changes`}):null]})]}):(0,$.jsx)(`p`,{className:`mt-2 text-sm text-secondary`,children:`Review the affected Properties before confirming.`})]}),(0,$.jsxs)(`label`,{className:`flex min-h-11 items-center gap-2 text-sm 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-sm 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)(J,{type:`button`,className:`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??ug})]})})]})}),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-sm font-medium text-heading`,children:l.title}),l.items.length>0?(0,$.jsx)(`ul`,{className:`mt-3 list-disc space-y-2 pl-5 text-sm 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-sm font-medium text-heading`,children:`Flagged exceptions`}),r.length===0?(0,$.jsx)(`p`,{className:`text-sm 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:`font-medium text-heading`,children:e.title}),e.detail?(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:e.detail}):null]}),(0,$.jsx)(Y,{tone:e.tone??`caution`,children:`Needs attention`})]},e.id))}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3 text-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,E.length,` of `,r.length]}),E.length<r.length?(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`min-h-11`,onClick:()=>b(e=>e+Gh),children:`Show next 50 exceptions`}):null]})]})]}),x?null:(0,$.jsxs)($.Fragment,{children:[D&&u?(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-negative`,children:u}):null,f?(0,$.jsx)(`p`,{role:`status`,className:`text-sm 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)(J,{type:`button`,variant:`outline`,className:`min-h-11`,onClick:a,children:`Back`}):null,o!==void 0&&!O?(0,$.jsx)(J,{type:`button`,className:`min-h-11`,disabled:s||!c,onClick:()=>{o()},children:s?`Reviewing changes…`:`Review changes`}):(0,$.jsx)(J,{type:`button`,className:`min-h-11`,disabled:!d||p,onClick:()=>{m()},children:p?`Publishing setup…`:`Publish setup`})]})]})]})}var mg={proposed:{label:`New`,tone:`caution`},confirmed:{label:`Included`,tone:`positive`},excluded:{label:`Excluded`,tone:`neutral`}};function hg(e){return e.trim().toLocaleLowerCase()}function gg(e,t){return!t||`${e.name} ${(e.urls??[e.url]).join(` `)}`.toLocaleLowerCase().includes(t)}function _g({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-xs font-medium 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 font-mono text-xs text-secondary`,children:e},e))})]})}function vg({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-lg font-semibold text-heading`,children:`Import Properties`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-sm 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-sm text-secondary`,children:[(0,$.jsx)(Y,{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-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-example-property-url`,className:`text-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-secondary`,children:`This shows Canonry the Property URL pattern. Or enter the pattern under More import options.`})]}),(0,$.jsxs)(`details`,{className:`rounded-md border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium 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-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-property-path-pattern`,className:`text-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(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-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-additional-path-pattern`,className:`text-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`})]}),(0,$.jsx)(`p`,{className:`text-sm text-secondary md:col-span-2`,children:`Use both fields when each Property also has a matching page on another domain.`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{htmlFor:`advanced-measurement-excluded-paths`,className:`text-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 focus:border-strong focus:ring-2 focus:ring-mono-400 disabled:cursor-not-allowed disabled:opacity-60`}),(0,$.jsx)(`p`,{className:`mt-1 text-xs text-secondary`,children:`One path per line. Use * at the beginning or end to match similar pages.`})]})]})]}),(0,$.jsx)(J,{type:`submit`,disabled:o,children:i===`reviewing`?`Reviewing sitemap…`:`Review sitemap`})]})]})}function yg({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=hg(r),m=t.filter(e=>gg(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-lg font-semibold text-heading`,children:`Properties`}),(0,$.jsx)(`p`,{className:`mt-1 max-w-2xl text-sm text-secondary`,children:`Choose the Properties to include, then continue.`})]}),e?null:(0,$.jsx)(`p`,{className:`mt-4 text-sm text-secondary`,children:`Viewing only. Property changes are unavailable.`}),n===`loading`?(0,$.jsxs)(`div`,{className:`mt-5 rounded-md border border-default bg-surface-subtle p-4`,children:[(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:`Loading Properties…`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:`If this does not finish, refresh the list.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,onClick:l,children:`Refresh Properties`})]}):null,n===`error`?(0,$.jsxs)(`div`,{className:`mt-5 rounded-md border border-default bg-surface-subtle p-4`,children:[(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-negative`,children:`Could not load Properties. Retry to request the current list.`}),(0,$.jsx)(J,{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 rounded-md border border-default bg-surface-subtle p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No Properties were found.`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:`Check the sitemap and review it again.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,className:`mt-3`,disabled:!e,onClick:u,children:`Review sitemap`})]}):null,n===`ready`&&t.length>0?(0,$.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-sm font-medium 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-sm text-primary outline-none placeholder-mono-600 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)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:c,onClick:S,children:`Select all shown`}),(0,$.jsx)(J,{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 rounded-md border border-default bg-surface-subtle p-4`,children:[(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:`No Properties match this search.`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:`Clear the search or review the sitemap again.`}),(0,$.jsx)(J,{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-sm 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-sm`,"aria-label":`Properties to review`,children:[(0,$.jsx)(`thead`,{className:`bg-surface-subtle text-xs font-medium uppercase tracking-wide 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=mg[t.state];return(0,$.jsxs)(`tr`,{className:`border-t border-subtle`,children:[(0,$.jsx)(`td`,{className:`px-3 py-3 font-medium text-heading`,children:t.name}),(0,$.jsx)(`td`,{className:`max-w-96 px-3 py-3 font-mono text-xs text-secondary`,children:(0,$.jsx)(_g,{property:t})}),(0,$.jsx)(`td`,{className:`px-3 py-3`,children:(0,$.jsx)(Y,{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)(J,{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)(J,{type:`button`,variant:`ghost`,disabled:c,onClick:u,children:`Back`}),(0,$.jsx)(J,{type:`button`,disabled:c||v.length===0,onClick:w,children:c?`Saving Properties…`:`Continue`})]}):null]}):null]})}function bg(e){return e.activeStep===`import`?(0,$.jsx)(vg,{canEdit:e.canEdit,draft:e.importDraft,onDraftChange:e.onImportDraftChange,onReviewSitemap:e.onReviewSitemap,reviewState:e.reviewState}):(0,$.jsx)(yg,{...e})}var xg=[{id:`import`,label:`Import`},{id:`properties`,label:`Properties`},{id:`groups`,label:`Groups`},{id:`queries`,label:`Queries`},{id:`review`,label:`Review and publish`}];function Sg({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-sm 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)(Y,{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-sm text-secondary`,children:`Discard all unpublished changes?`}),(0,$.jsx)(J,{ref:c,type:`button`,size:`sm`,variant:`ghost`,className:`min-h-11`,onClick:()=>f(!1),children:`Keep editing`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`min-h-11`,onClick:r,children:`Discard unpublished changes`})]}):(0,$.jsx)(J,{ref:l,type:`button`,size:`sm`,variant:`ghost`,className:`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:xg.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-sm font-medium 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-sm font-medium ${e===t.id?`border-strong text-heading`:`border-transparent text-secondary`}`,children:t.label})},t.id))})}),(0,$.jsx)(`div`,{ref:s,children:a})]})}function Cg(e){let t=e.canEdit?`editor`:`viewer`;return e.currentStep===`import`||e.currentStep===`properties`?(0,$.jsx)(bg,{...e.importProperties,activeStep:e.currentStep,canEdit:e.canEdit}):e.currentStep===`queries`?(0,$.jsx)(dg,{...e.queries,access:t,onManageProjectQueries:e.onManageProjectQueries}):e.currentStep===`groups`?(0,$.jsx)(fg,{...e.groups,access:t}):`review`in e?(0,$.jsx)(pg,{...e.review,access:t}):null}function wg(e){return(0,$.jsx)(Sg,{currentStep:e.currentStep,hasDraft:e.hasDraft,canEdit:e.canEdit,onDiscard:e.onDiscard,onStepChange:e.onStepChange,children:Cg(e)})}var Tg={sitemapUrl:``,examplePropertyUrl:``,preferredHost:``,propertyPathPattern:``,additionalHost:``,additionalPathPattern:``,excludedPaths:``},Eg={name:``,propertyIds:[],competitorDomains:``},Dg=50,Og=[],kg={};function Ag(e){let t=e.trim();if(!t)return null;try{return new URL(t.includes(`://`)?t:`https://${t}`).hostname.toLocaleLowerCase()}catch{return null}}function jg(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 Mg(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 Ng(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 Pg(e){let t=jg(e.sitemapUrl),n=e.examplePropertyUrl.trim()?Ag(e.examplePropertyUrl):null,r=Ag(e.preferredHost)??n??Ag(t);if(!r)throw Error(`Add a valid sitemap or Property page URL.`);let i=Ag(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=Ng(e.excludedPaths);return{sitemapUrl:t,rule:{primary:{host:r,pathTemplate:Mg(e)},...i?{aliases:[{host:i,pathTemplate:Mg({...e,examplePropertyUrl:``,propertyPathPattern:e.additionalPathPattern})}]}:{},...o.length>0?{excludedSlugPatterns:o}:{}}}}function Fg(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 Ig(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 Lg(e){return[...new Set([...e.discoveredUrl?[e.discoveredUrl]:[],...e.urlMatchers])]}function Rg(e){return e===`included`?`confirmed`:e===`excluded`?`excluded`:`proposed`}function zg(e){return e?.authoring.targets.filter(e=>e.status!==`excluded`).map(e=>e.stableKey)??[]}function Bg(e,t){return`${t}-${e.trim().toLocaleLowerCase().replace(/[^a-z0-9._~-]+/g,`-`).replace(/^-+|-+$/g,``)||`item`}`.slice(0,128)}function Vg(e){return Ag(e)}function Hg(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 Ug(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 Wg(e,t){return t[0]===`assignments`&&typeof t[1]==`number`?e?.assignments[t[1]]:void 0}function Gg(e,t){return e?.targets.find(e=>e.stableKey===t)?.label??`a Property`}function Kg(e,t){let n=Hg(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 qg(e,t){let n=Ug(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=Gg(e.authoring,n.targetKeys[i]);return`${n.label} — ${t}`}return n.label}function Jg(e,t){let n=Wg(e.authoring,t.path);if(!n)return;let r=e.queries.find(e=>e.id===n.queryId)?.query??`an unavailable query`;return`${Gg(e.authoring,n.targetKey)} — ${r}`}function Yg(e,t){return t.path[0]===`identities`?`Project domain`:Kg(e,t)??qg(e,t)??Jg(e,t)}function Xg(e,t,n){let r=Wg(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 Zg(e,t){let n=Yg(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,Xg(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,Xg(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 Qg(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function $g(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 e_(e,t,n,r){return`${(()=>{switch(e){case`execution-context-no-provider`:return`${t} ${Qg(n,`query assignment`)} need${n===1?`s`:``} a provider.`;case`target-without-aliases`:return`${t} ${Qg(n,`Property`,`Properties`)} need${n===1?`s`:``} aliases.`;case`target-without-assignments`:return`${t} ${Qg(n,`Property`,`Properties`)} need${n===1?`s`:``} queries.`;default:return n>1?`${t} ${Qg(n,`item`)} need review.`:t}})()}${$g(r)}`}function t_(e,t){let n=new Map;for(let r of e){let e=Zg(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:e_(e.ruleId,e.meaning.detail,e.paths.size,e.affected),tone:e.meaning.tone}))}function n_(e){if(!e)return;let t=e.discoveredUrl??e.urlMatchers[0];return t?`${e.label} — ${t}`:e.label}function r_(e,t,n){let r=Hg(n,e.path),i=Ug(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=$g(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=n_(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=n_(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=n_(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 i_(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 a_(e){return[...new Set(e)]}function o_(e){return a_(e).sort()}function s_(e,t,n,r){return e.kind===`groups`?{groupKeys:o_(e.groupIds),queryIds:o_(n),...r?{contextOverride:r}:{}}:{targetKeys:o_(e.kind===`all`?t:e.kind===`specific`?e.propertyIds:[]),queryIds:o_(n),...r?{contextOverride:r}:{}}}function c_(e,t){return t===void 0?e:JSON.stringify([e,t])}function l_(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 u_(e){return e.kind===`exact`?e.url??``:e.kind===`prefix`?`https://${e.host??``}${e.pathPrefix===`/`?``:e.pathPrefix??``}/*`:e.host??``}function d_(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(u_).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(u_).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:Bg(e,`competitor`),label:e,domain:e,aliases:[]}))}))}}function f_({projectName:e,queries:t,isQueryLoading:n,isQueryError:r,onRetryQueries:i,publishedPlan:a,canEdit:o=!0,sweepActive:s=!1,executionProviders:c=Og,executionProviderModels:l=kg,onCreateQueries:u,onManageProjectQueries:d,onPublished:f,service:p=qo}){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)({...Tg}),[A,j]=(0,Q.useState)(`idle`),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(Dg),[I,L]=(0,Q.useState)([]),[R,z]=(0,Q.useState)([]),[ee,B]=(0,Q.useState)({kind:`none`}),[V,H]=(0,Q.useState)(``),[te,ne]=(0,Q.useState)(``),[re,ie]=(0,Q.useState)(``),[U,ae]=(0,Q.useState)(null),[oe,se]=(0,Q.useState)(null),[ce,ue]=(0,Q.useState)(!1),[de,fe]=(0,Q.useState)(null),[pe,me]=(0,Q.useState)(0),[he,ge]=(0,Q.useState)(null),[_e,ve]=(0,Q.useState)(null),[be,xe]=(0,Q.useState)(null),[Se,Ce]=(0,Q.useState)(!1),[W,we]=(0,Q.useState)(null),[Te,G]=(0,Q.useState)(0),[Ee,De]=(0,Q.useState)(null),[Oe,ke]=(0,Q.useState)({...Eg}),[Ae,je]=(0,Q.useState)(null),[Me,Ne]=(0,Q.useState)(``),[Pe,Fe]=(0,Q.useState)(null),[Ie,Le]=(0,Q.useState)(!1),[Re,ze]=(0,Q.useState)(!1),[Be,Ve]=(0,Q.useState)(null),[He,Ue]=(0,Q.useState)(null),[We,K]=(0,Q.useState)(null),[Ge,Ke]=(0,Q.useState)(null),[qe,Je]=(0,Q.useState)(null),Ye=(0,Q.useRef)(0),Xe=(0,Q.useRef)(0),Ze=(0,Q.useRef)(0),Qe=g?.draft??null,$e=g?.etag??null,et=(0,Q.useMemo)(()=>!o&&a?{baseActiveRevision:a.revision,authoring:d_(a)}:null,[o,a]),tt=Qe??et;async function nt(t){let n=++Ye.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!==Ye.current)return;h(r),_(i),y(Fg(i.draft));let a=zg(i.draft);L(a)}catch(e){if(n!==Ye.current)return;C(Ho(e,`Could not load advanced measurement setup.`))}finally{n===Ye.current&&x(!1)}}(0,Q.useEffect)(()=>(nt(!0),()=>{Ye.current+=1}),[e,o,p]),(0,Q.useEffect)(()=>{!b&&!Qe&&et&&y(`properties`)},[Qe,b,et]);async function rt(){let t=await p.loadDraft(e);return _(t),t}async function it(t){Je(null);try{let[n,r]=await Promise.all([p.loadSetup(e),p.loadDraft(e)]);h(n),_(r);let i=zg(r.draft);L(i),y(e=>Ig(r.draft,e)),T(t)}catch(e){T(Ho(e,t))}}async function at(e,t,n,r={}){let{preserveBusyAction:i=!1}=r;if(!o||!$e||We&&!i)return null;i||K(e),T(null),Je(null);try{let e=await t($e),n=await rt();return D((e.warnings??[]).map((e,t)=>r_(e,t,n.draft?.authoring))),n}catch(e){return Ko(e)?await it(`This setup changed in another session. The latest draft is loaded; review your changes again.`):T(Ho(e,n)),null}finally{i||K(null)}}let ot=(0,Q.useMemo)(()=>(tt?.authoring.targets??[]).map(e=>{let t=Lg(e);return{id:e.stableKey,name:e.label,url:t[0]??`No URL`,urls:t,state:Rg(e.status)}}),[tt]),st=(0,Q.useMemo)(()=>tt?.authoring.targets.filter(e=>e.status===`included`)??[],[tt]),ct=(0,Q.useMemo)(()=>st.map(e=>({id:e.stableKey,label:e.label,urlCount:Lg(e).length})),[st]),lt=tt?.authoring.assignments.length??0,ut=(0,Q.useMemo)(()=>{if(!tt)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:a_(tt.authoring.assignments.filter(t=>t.queryId===e.id).map(e=>e.targetKey))})),r=a_(tt.authoring.assignments.map(e=>e.queryId).filter(t=>!e.has(t))).map(e=>({id:e,source:`unavailable-tracked-query`,state:`missing`,propertyIds:a_(tt.authoring.assignments.filter(t=>t.queryId===e).map(e=>e.targetKey))}));return[...n,...r]},[t,tt]),dt=(0,Q.useMemo)(()=>(tt?.authoring.groups??[]).map(e=>({id:e.stableKey,name:e.label,propertyIds:e.targetKeys,competitors:e.competitors.map(e=>e.domain)})),[tt]),ft=(0,Q.useMemo)(()=>(tt?.authoring.reportingScopes??[]).map(e=>({id:e.stableKey,label:e.label,measurementCount:e.usageEdges.length})),[tt]),pt=(0,Q.useMemo)(()=>{let e=new Map,t=(t,n={})=>{for(let r of t){if(!ye(r))continue;let t=le(r)?void 0:n[r],i=c_(r,t);e.has(i)||e.set(i,{id:i,provider:r,label:t?`${ra(r)} · ${t}`:ra(r),...t?{model:t}:{}})}};t(c,l);let n=tt?.authoring.defaultContext;n&&t(n.providers,n.models);for(let e of tt?.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,tt]),mt=(0,Q.useMemo)(()=>{if(!V)return;let e=pt.find(e=>e.id===V);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[V,pt]),ht=(0,Q.useMemo)(()=>{if(!re)return;let e=pt.find(e=>e.id===re);if(e)return{providers:[e.provider],models:e.model?{[e.provider]:e.model}:{}}},[pt,re]),gt=(0,Q.useMemo)(()=>te&&ht?{marketKeys:[te],contextOverride:ht}:null,[ht,te]),_t=gt?JSON.stringify(gt):``,vt=(0,Q.useMemo)(()=>!U||oe!==_t||U.draftEtag!==$e?null:{matchedMeasurements:U.matchedEdges,changedMeasurements:U.changedEdges,addedProviderCalls:U.execution.addedProviderCalls,fullRunProviderCalls:U.execution.fullRunProviderCalls},[$e,U,oe,_t]);(0,Q.useEffect)(()=>{V&&!pt.some(e=>e.id===V)&&H(``)},[V,pt]),(0,Q.useEffect)(()=>{re&&!pt.some(e=>e.id===re)&&ie(``)},[pt,re]),(0,Q.useEffect)(()=>{te&&!ft.some(e=>e.id===te)&&ne(``)},[te,ft]);let yt=(0,Q.useMemo)(()=>{if(R.length===0)return null;let e=s_(ee,ct.map(e=>e.id),R,mt);return(e.groupKeys?.length??e.targetKeys?.length??0)>0?e:null},[mt,ee,ct,R]),bt=yt?JSON.stringify(yt):``;(0,Q.useEffect)(()=>{let t=yt,n=++Xe.current;if(!o||!Qe||!$e||!t){ve(null),xe(null),we(null),Ce(!1);return}ve(null),xe(null),we(null),Ce(!0);let r=window.setTimeout(()=>{p.previewAssignments(e,t).then(e=>{n===Xe.current&&(e.draftEtag===$e?(ve(e),xe(bt)):(ve(null),xe(null),we(`The setup changed while calculating assignment impact. Refresh the draft and try again.`)))}).catch(e=>{n===Xe.current&&(ve(null),xe(null),we(Wo(e)))}).finally(()=>{n===Xe.current&&Ce(!1)})},250);return()=>{window.clearTimeout(r),Xe.current+=1}},[yt,bt,Te,o,Qe,$e,e,p]),(0,Q.useEffect)(()=>{let t=gt,n=++Ze.current;if(!o||!Qe||!$e||!t){ae(null),se(null),fe(null),ue(!1);return}ae(null),se(null),fe(null),ue(!0);let r=window.setTimeout(()=>{p.previewMarketRouting(e,t).then(e=>{n===Ze.current&&(e.draftEtag===$e?(ae(e),se(_t)):fe(`The setup changed while calculating market impact. Refresh the draft and try again.`))}).catch(e=>{n===Ze.current&&fe(Ho(e,`Could not calculate market routing impact.`))}).finally(()=>{n===Ze.current&&ue(!1)})},250);return()=>{window.clearTimeout(r),Ze.current+=1}},[o,Qe,$e,gt,pe,_t,e,p]);let xt=(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`}]:[],...tt?.authoring.assignments.some(e=>e.queryClass===`unclassified`)&&!(et&&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,et,a,E,tt]),St=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 Ct(t){let n;try{n=Pg(t)}catch(e){T(Ho(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(Dg),y(`properties`),j(`idle`)}else j(`error`)}async function wt(e){if(!u||e.length===0||We)return[];K(`create-queries`),Ke(null);try{return await u(e)}catch(e){throw Ke(Xo(e)),e}finally{K(null)}}async function Tt(t){if(!Qe||!$e||We)return;let n=new Set(t),r=Qe.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||Qe.authoring.targets.some(e=>e.status!==`proposed`&&e.status===`included`!==n.has(e.stableKey));K(`properties`),T(null),Je(null);try{if(!i){L([...n]),B({kind:`none`}),y(`groups`);return}await p.applySitemapSelection(e,$e,r,[...n]);let t=zg((await rt()).draft);L(t),B({kind:`none`}),y(`groups`)}catch(e){Ko(e)?await it(`This setup changed in another session. The latest Properties are loaded.`):T(Ho(e,`Could not save the selected Properties.`))}finally{K(null)}}async function Et(t){let n=t.groupIds&&t.groupIds.length>0?{groupKeys:o_(t.groupIds),queryIds:o_(t.queryIds),...mt?{contextOverride:mt}:{}}:{targetKeys:o_(t.propertyIds),queryIds:o_(t.queryIds),...mt?{contextOverride:mt}:{}};!_e||be!==JSON.stringify(n)||!$e||_e.draftEtag!==$e?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 Dt(t){t.propertyIds.length!==0&&await at(`replace-assignments`,n=>p.replaceAssignments(e,n,{targetKeys:a_(t.propertyIds),queryIds:[t.queryId],...mt?{contextOverride:mt}:{}}),`Could not replace this query assignment.`)&&(z(e=>e.filter(e=>e!==t.queryId)),De(`Query assignments replaced.`))}async function Ot(){if(!gt||!U||oe!==JSON.stringify(gt)||!$e||U.draftEtag!==$e){T(`Review the latest market routing impact before saving.`);return}let t=ft.find(e=>e.id===te);await at(`route-markets`,t=>p.routeMarkets(e,t,gt),`Could not save this market routing.`)&&ge(`${t?.label??`Market`} routing saved. Existing locations were preserved.`)}async function kt(t,n=!1){if(t.length!==0&&!await at(`paired-assignments`,n=>mt?p.applyPairedAssignments(e,n,[...t],mt):p.applyPairedAssignments(e,n,[...t]),`Could not assign these queries.`,{preserveBusyAction:n}))throw Error(`Could not assign these queries.`)}async function At(e){if(o&&u&&e.length!==0&&!We){K(`create-and-pair-questions`),Ke(null);try{let t;try{t=await u(a_(e.map(e=>e.text)))}catch(e){throw Ke(Xo(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 Ke(`The queries were added, but could not be paired with every Property. Try again to pair them.`),e}try{await kt(r,!0)}catch(e){throw Ke(`The queries were added, but could not be assigned to their Properties. Try again to pair them.`),e}}finally{K(null)}}}async function jt(t){if(!Qe)return;let n=a_(Qe.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 Mt(t){if(!Qe||!$e||We)return;let n=t.name.trim();if(!n)return;let r=Ae??Bg(n,`group`),i=Qe.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=>Vg(e)===null);if(o){T(`"${o}" is not a valid competitor domain.`);return}let s=a_(a.map(e=>Vg(e)));K(`group`),T(null),Je(null);try{let a=await p.upsertGroup(e,$e,{stableKey:r,label:n,targetKeys:a_(t.propertyIds),competitors:s.map(e=>i?.competitors.find(t=>t.domain===e)??{stableKey:Bg(e,`competitor`),label:e,domain:e,aliases:[]})}),o=await rt();D(a.warnings.map((e,t)=>r_(e,t,o.draft?.authoring))),ke({...Eg}),je(null)}catch(e){Ko(e)?await it(`This setup changed in another session. The latest groups are loaded.`):T(Ho(e,`Could not save this group.`))}finally{K(null)}}function Nt(e){let t=Qe?.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 Pt(t){await at(`remove-group`,n=>p.removeGroup(e,n,t),`Could not remove this group.`)&&(B(e=>e.kind===`groups`&&e.groupIds.includes(t)?{kind:`none`}:e),Ae===t&&(je(null),ke({...Eg})))}function Ft(e){Ne(e),Fe(null),Ve(null),Ue(null)}async function It(){if(o&&Me.trim()&&!Ie&&!Re){Le(!0),Ve(null),Ue(null);try{Fe(await p.previewGroupMembership(e,{csv:Me}))}catch(e){Fe(null),Ve(Ho(e,`Could not review this CSV.`))}finally{Le(!1)}}}async function Lt(t){if(o&&$e&&Pe&&t.length!==0&&!We){if(Pe.draftEtag!==$e)Ve(`The setup changed while this CSV was open. Review the latest CSV before applying it.`);else{ze(!0),K(`group-import`),Ve(null),Ue(null),Je(null);try{let n=await p.applyGroupMembership(e,$e,{csv:Me,sourceChecksum:Pe.sourceChecksum,previewChecksum:Pe.previewChecksum,acceptedRows:a_(t.map(String)).map(Number)}),r=await rt();D(n.warnings.map((e,t)=>r_(e,t,r.draft?.authoring))),Ne(``),Fe(null),Ue(`${n.addedMemberships} membership${n.addedMemberships===1?``:`s`} added${n.unchangedMemberships>0?`; ${n.unchangedMemberships} already present`:``}.`)}catch(e){Ko(e)?(await it(`This setup changed in another session. The latest draft is loaded; review the CSV again.`),Ve(`The setup changed while this CSV was open. Review the latest CSV before applying it.`)):Ve(Ho(e,`Could not apply this CSV.`))}finally{K(null),ze(!1)}}}}async function Rt(){if(Qe&&$e&&!We&&lt!==0){K(`review`),T(null),Je(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(t_(i.filter(e=>e.ruleId!==`active-revision-schema-v1`),{authoring:tt?.authoring,queries:t})),!n.ok||!r.ok)return;if(r.diff.activeRevision!==Qe.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}Je({etag:$e,baseActiveRevision:Qe.baseActiveRevision,compiledChecksum:n.compiledChecksum,changes:i_(r.diff,a),providerCalls:n.plan.executionNodes.reduce((e,t)=>e+t.expectedSnapshots,0)})}catch(e){T(Ho(e,`Could not review this setup.`))}finally{K(null)}}}async function zt(){if(Qe&&$e&&qe&&!We){if($e!==qe.etag||Qe.baseActiveRevision!==qe.baseActiveRevision)Je(null),T(`The setup changed after review. Review the latest changes before publishing.`);else{K(`publish`),T(null);try{await p.publish(e,$e,{expectedActiveRevision:qe.baseActiveRevision,expectedCompiledChecksum:qe.compiledChecksum}),_({draft:null,etag:null}),Je(null),f?.()}catch(e){Ko(e)?await it(`The setup changed before it could be published. Review the latest draft and publish again.`):T(Ho(e,`Could not publish this setup.`))}finally{K(null)}}}}async function Bt(){if($e&&!We){K(`discard`),T(null);try{await p.discard(e,$e),_({draft:null,etag:null}),Je(null),f?.()}catch(e){Ko(e)?await it(`This setup changed in another session. The latest draft is loaded.`):T(Ho(e,`Could not discard these changes.`))}finally{K(null)}}}async function Vt(){if(Qe&&$e&&m&&!We){K(`restart`),T(null),Je(null);try{await p.discard(e,$e),await p.createDraft(e,m.activeRevision),k({...Tg}),N(``),L([]),z([]),B({kind:`none`}),ve(null),we(null),De(null),ke({...Eg}),je(null),Ne(``),Fe(null),Ve(null),Ue(null),await nt(!1)}catch(e){Ko(e)?await it(`The setup changed again. Reloaded the latest draft and published setup.`):T(Ho(e,`Could not restart this setup.`))}finally{K(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-sm text-negative`,children:[(0,$.jsx)(`p`,{children:S}),(0,$.jsx)(J,{className:`mt-3 min-h-11`,type:`button`,size:`sm`,variant:`outline`,onClick:()=>{nt(!0)},children:`Try again`})]})]});if(!tt||o&&!$e)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-sm text-secondary`,children:o?`Start setup from the project Overview.`:`No advanced setup is available to review.`})]});if(o&&Qe&&m&&Qe.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-sm font-medium text-heading`,children:`This draft is based on an older published setup.`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:`Restart from the latest setup before making more changes.`}),(0,$.jsx)(J,{className:`mt-3 min-h-11`,type:`button`,size:`sm`,variant:`outline`,disabled:We===`restart`,onClick:()=>{Vt()},children:We===`restart`?`Restarting…`:`Discard draft and restart`})]}),w?(0,$.jsx)(`p`,{role:`alert`,className:`text-sm text-negative`,children:w}):null]});let Ht=r&&i?(0,$.jsx)(`div`,{className:`flex justify-end`,children:(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,className:`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-sm 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-sm text-negative`,children:w}):null,Ht,v===`import`||v===`properties`?(0,$.jsx)(wg,{currentStep:v,hasDraft:Qe!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Bt()},importProperties:{importDraft:O,onImportDraftChange:e=>{k(e),j(`idle`),T(null)},onReviewSitemap:e=>{Ct(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=>{Tt(e)},isContinuing:We===`properties`,onRetryProperties:()=>{rt()},onReturnToImport:()=>y(`import`)}}):v===`queries`?(0,$.jsx)(wg,{currentStep:`queries`,hasDraft:Qe!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Bt()},onManageProjectQueries:d,queries:{onCreateQueries:u?e=>wt(e):void 0,isCreatingQueries:We===`create-queries`||We===`create-and-pair-questions`,isBusy:We!==null,createQueriesError:Ge,availability:St,properties:ct,queries:ut,selectedQueryIds:R,isApplying:We===`assignments`||We===`paired-assignments`,onSelectedQueryIdsChange:e=>z([...e]),onApplySelectedQueries:e=>Et(e),groups:dt,audience:ee,onAudienceChange:e=>{B(e),De(null)},executionOptions:pt,executionOptionId:V,onExecutionOptionChange:e=>{H(e),De(null)},markets:ft,marketId:te,onMarketChange:e=>{ne(e),ge(null)},marketExecutionOptionId:re,onMarketExecutionOptionChange:e=>{ie(e),ge(null)},onRouteMarket:Ot,isRoutingMarket:We===`route-markets`,isPreviewingMarketRouting:ce,marketRoutingImpact:vt,marketRoutingError:de,onRetryMarketRouting:()=>me(e=>e+1),marketRoutingNotice:he,assignmentImpact:_e&&be===bt&&_e.draftEtag===$e?l_(_e):null,isPreviewingAssignmentImpact:Se,assignmentImpactError:W,onRetryAssignmentImpact:()=>G(e=>e+1),assignmentNotice:Ee,onReplaceAssignments:Dt,isReplacingAssignments:We===`replace-assignments`,onCreateAndPairQuestions:o&&u?At:void 0,onClearQueryAssignments:jt,onRemoveQuery:jt,canContinue:lt>0,onBack:()=>y(`groups`),onContinue:()=>y(`review`)}}):v===`groups`?(0,$.jsx)(wg,{currentStep:`groups`,hasDraft:Qe!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Bt()},groups:{properties:ct,groups:dt,groupDraft:Oe,isSaving:We===`group`,onGroupDraftChange:ke,onSaveGroup:Mt,onEditGroup:e=>Nt(e.id),onRemoveGroup:Pt,onClearGroupDraft:()=>{je(null),ke({...Eg})},membershipImport:{csv:Me,preview:Pe,isReviewing:Ie,isApplying:Re,error:Be,notice:He,onCsvChange:Ft,onReview:It,onApply:Lt},onBack:()=>{y(`properties`)},onContinue:()=>y(`queries`)}}):(0,$.jsx)(wg,{currentStep:`review`,hasDraft:Qe!==null,canEdit:o,onStepChange:o?void 0:y,onDiscard:()=>{Bt()},review:{counts:{properties:st.length,queries:new Set(tt.authoring.assignments.map(e=>e.queryId)).size,groups:tt.authoring.groups.length,assignments:tt.authoring.assignments.length,providerCalls:qe?.providerCalls},flaggedExceptions:xt,reviewedChanges:qe?.changes,isReviewing:We===`review`,canReviewChanges:lt>0&&!We,onReviewChanges:Rt,onBack:()=>y(`queries`),canPublish:qe!==null&&!We&&!s,sweepActive:s,isPublishing:We===`publish`,onPublish:zt}})]})}var p_=`Mentioned = the property’s name in the answer. Cited = one of the property’s own pages in the sources. Neither implies the other.`,m_=[{key:`label`,label:`Property`,numeric:!1},{key:`mentionCoverage`,label:`Mention`,numeric:!0},{key:`citationCoverage`,label:`Citation`,numeric:!0}];function h_(e){return e.label!==`Complete`}var g_=`__all_properties__`,__=50,v_=50,y_=20,b_=50,x_=250,S_=5,C_=[{value:`all`,label:`All queries`},{value:`non-brand`,label:`Non-brand`},{value:`branded`,label:`Branded`}],w_={"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`},T_={plan_v1:`Setup update required.`,no_completed_run:`Not measured yet.`,no_population:`No matching queries.`,evidence_incomplete:`Evidence incomplete.`,identity_ambiguous:`${pn}.`,"identity-ambiguous":`${pn}.`,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.`},E_={numerator:null,denominator:null,reason:`plan_v1`};function D_(e){return e.numerator!==null&&Number.isFinite(e.numerator)&&Number.isFinite(e.denominator)&&e.numerator>=0&&e.denominator>0&&e.numerator<=e.denominator}function O_(e){return D_(e)?`${e.numerator} of ${e.denominator} (${W(e.numerator/e.denominator)})`:`N/A`}function k_(e){if(D_(e))return``;let t=e.reason??`unavailable`;return T_[t]??t}function A_(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 j_(e,t){return!Number.isFinite(e)||!Number.isFinite(t)||e<0||t<=0||e>t?null:`${e} of ${t}`}function M_(e){let t=e.trim();return t&&!t.toLocaleLowerCase().includes(`unavailable`)?t:null}function N_(e){return e?.closest?.(`button, a, input, select, textarea, [role="button"]`)!=null}function P_({metric:e,signal:t,compact:n=!1}){let r=n?D_(e)?`text-sm font-medium text-primary`:`text-sm font-medium text-secondary`:D_(e)?`text-lg font-semibold text-heading`:`text-lg font-semibold text-secondary`,i=D_(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`,...D_(e)?{}:{title:k_(e)},children:[(0,$.jsx)(`span`,{className:r,children:O_(e)}),i?(0,$.jsx)(X,{tone:`caution`,placement:`bottom`,label:i.label,text:i.text}):null]})}function F_({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-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,e,` of `,t]}),(0,$.jsxs)(J,{size:`sm`,variant:`outline`,onClick:n,children:[`Show all `,t,` `,r]})]})}function I_({title:e,values:t,emptyLabel:n,valueClassName:r=`text-secondary`}){let[i,a]=(0,Q.useState)(v_),o=t.slice(0,i);return(0,$.jsxs)(`section`,{"aria-label":e,children:[(0,$.jsx)(`h4`,{className:`text-sm font-medium text-heading`,children:e}),t.length===0?(0,$.jsx)(`p`,{className:`mt-2 text-sm text-secondary`,children:n}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`ul`,{className:`mt-2 space-y-1.5 text-sm`,children:o.map((e,t)=>(0,$.jsx)(`li`,{className:r,children:e},`${e}:${t}`))}),(0,$.jsx)(F_,{shown:o.length,total:t.length,itemLabel:e.toLocaleLowerCase(),onShowAll:()=>a(2**53-1)})]})]})}function L_({evidence:e,state:t=`ready`,onRetry:n}){let[r,i]=(0,Q.useState)(v_),a=e.slice(0,r);return(0,$.jsxs)(`section`,{"aria-label":`Evidence`,children:[(0,$.jsx)(`h4`,{className:`text-sm font-medium text-heading`,children:`Evidence`}),t===`loading`?(0,$.jsx)(`p`,{className:`mt-2 text-sm text-secondary`,children:`Loading evidence…`}):t===`error`?(0,$.jsxs)(`div`,{className:`mt-2 flex flex-wrap items-center gap-3 text-sm text-secondary`,children:[(0,$.jsx)(`span`,{children:`Evidence could not be loaded.`}),n?(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:n,children:`Retry evidence`}):null]}):e.length===0?(0,$.jsx)(`p`,{className:`mt-2 text-sm 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)(Y,{tone:e.tone,children:w_[e.kind]}),e.historical?(0,$.jsx)(Y,{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-xs 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)(F_,{shown:a.length,total:e.length,itemLabel:`evidence items`,onShowAll:()=>i(2**53-1)})]})]})}function R_({property:e,onRetryEvidence:t}){return(0,$.jsxs)(`div`,{className:`space-y-5 py-2`,children:[(0,$.jsx)(I_,{title:`Assigned queries`,values:e.assignedQueries,emptyLabel:`No queries are assigned.`}),(0,$.jsx)(I_,{title:`URLs`,values:e.urls,emptyLabel:`No URLs are assigned.`,valueClassName:`break-all text-secondary`}),(0,$.jsx)(L_,{evidence:e.evidence,state:e.evidenceState,onRetry:t})]})}function z_({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-sm font-medium 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:`font-medium text-heading`,children:e.name}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(P_,{metric:e.coverage,signal:`mentioned`,compact:!0})})]},e.name))})]})})]})}function B_({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 V_({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-xl font-semibold leading-none tabular-nums ${e.tone}`,children:e.count}),(0,$.jsxs)(`p`,{className:`mt-1 text-[13px] 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 H_({report:e,canEdit:t,onRunMeasurement:n,onRepublishSetup:i,isRunningMeasurement:a=!1,isRepublishingSetup:o=!1,isViewLoading:s=!1,isLoadingMore:c=!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??g_),[S,C]=(0,Q.useState)(u??``),[w,T]=(0,Q.useState)(__),[E,D]=(0,Q.useState)(y_),[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===g_?`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&&!s&&(y(e.currentView.queryClass),x(e.currentView.scope.key??g_),e.currentView.sort&&k(e.currentView.sort))},[s,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}),x_);return()=>window.clearTimeout(e)},[d,F,S,g]);let I=e.availableGroups??P.groups;(0,Q.useEffect)(()=>{b===g_||I.some(e=>e.id===b)||x(g_)},[I,b]);let L=g?void 0:P.groups.find(e=>e.id===b),R=L?.aggregate??P.aggregate,z=e=>_?e:E_,ee=O,B=S.trim().toLocaleLowerCase(),V=(0,Q.useMemo)(()=>!g&&B?R.properties.filter(e=>e.name.toLocaleLowerCase().includes(B)):R.properties,[R.properties,B,g]),H=g?V:V.slice(0,w),te=(g?e.currentView?.scope.kind===`group`:L!=null)&&v===`non-brand`&&_&&(g||L.confirmedCompetitorCount>0)&&(R.shareOfVoice?.length??0)>0,ne=_?R.unavailablePropertyCount??0:0,re=e.flaggedResults.reduce((e,t)=>e+(t.count??1),0),ie=e.flaggedResultsTotal??re,U=[z(R.metrics.propertiesMentioned),z(R.metrics.mentionCoverage),z(R.metrics.citationCoverage)].map(k_).find(Boolean),ae=_?e.nextActionText??U??(ne>0?`${ne} ${ne===1?`property is`:`properties are`} unavailable.`:ie>0?`${ie} flagged ${ie===1?`result needs`:`results need`} review.`:null):T_.plan_v1,oe=e.latestMeasurement.status.tone!==`negative`&&e.latestMeasurement.completedSlots<e.latestMeasurement.totalSlots?j_(e.latestMeasurement.completedSlots,e.latestMeasurement.totalSlots):null,se=M_(e.latestMeasurement.date),ce=[{value:g_,label:`All properties`},...I.map(e=>({value:e.id,label:e.label}))],le=I.length>S_;function ue(e){x(e),F(e===g_?{scope:`all`}:{scope:`group`,groupKey:e})}function de(e){y(e),F({queryClass:e})}function fe(e){let t=A!==e;j(t?e:null),t&&p?.(e)}return(0,$.jsxs)(`section`,{"aria-label":`Advanced measurement overview`,"aria-busy":s,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:s?(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:`Updating results…`}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Y,{tone:e.latestMeasurement.status.tone,children:e.latestMeasurement.status.label}),e.latestMeasurement.includesBridgedHistory?(0,$.jsx)(Y,{tone:`caution`,children:`Includes historical data`}):null,oe?(0,$.jsx)(`span`,{className:`text-sm text-secondary tabular-nums`,children:oe}):null,se?(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:se}):null,ae?(0,$.jsx)(`span`,{className:`text-sm text-secondary`,children:ae}):null,t&&_&&n?(0,$.jsx)(J,{className:`ml-auto`,size:`sm`,onClick:()=>{n()},disabled:a,children:a?`Starting measurement…`:`Run measurement`}):t&&!_?(0,$.jsx)(J,{className:`ml-auto`,size:`sm`,onClick:()=>{i?.()},disabled:!i||o,children:o?`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:le?`advanced-measurement-group`:void 0,className:`block text-sm font-medium text-heading`,children:`Group`}),le?(0,$.jsx)(`select`,{id:`advanced-measurement-group`,value:b,onChange:e=>ue(e.target.value),className:`h-9 rounded-md border border-default bg-surface px-3 text-sm text-primary focus:outline-none focus:ring-2 focus:ring-mono-400`,children:ce.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))}):(0,$.jsx)(B_,{ariaLabelledBy:`advanced-measurement-group-label`,value:b,options:ce,onChange:ue})]}),(0,$.jsxs)(`div`,{className:`space-y-1`,children:[(0,$.jsx)(`label`,{id:`advanced-measurement-class-label`,className:`block text-sm font-medium text-heading`,children:`Query type`}),(0,$.jsx)(B_,{ariaLabelledBy:`advanced-measurement-class-label`,value:v,options:C_,onChange:de,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-sm font-medium 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-sm text-primary placeholder-mono-600 focus:outline-none focus:ring-2 focus:ring-mono-400`})]})]}),!s&&te?(0,$.jsx)(z_,{values:R.shareOfVoice??[]}):null,s?(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-base font-semibold text-heading`,children:[`Properties`,(0,$.jsx)(X,{text:p_})]}),(0,$.jsxs)(`span`,{className:`text-sm text-secondary`,children:[e.currentView?.propertyTotal??V.length,` `,(e.currentView?.propertyTotal??V.length)===1?`property`:`properties`]})]}),e.currentView?.outcomes?(0,$.jsx)(V_,{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:[m_.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)(r,{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:[H.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=>{N_(t.target)||fe(e.id)},children:[(0,$.jsxs)(`td`,{className:`font-medium text-heading`,children:[h?h({id:e.id,name:e.name}):e.name,h_(e.status)||e.historical?(0,$.jsxs)(`span`,{className:`ml-2 inline-flex flex-wrap items-center gap-1 align-middle`,children:[h_(e.status)?(0,$.jsx)(Y,{tone:e.status.tone,children:e.status.label}):null,e.historical?(0,$.jsx)(Y,{tone:`caution`,children:`Historical`}):null]}):null,A_(e)?(0,$.jsx)(`div`,{className:`mt-0.5 text-xs font-normal text-faint`,children:A_(e)}):null]}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(P_,{metric:e.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(P_,{metric:e.citationCoverage,signal:`cited`,compact:!0})}),(0,$.jsx)(`td`,{className:`text-right`,children:(0,$.jsx)(J,{size:`icon`,variant:`ghost`,"aria-expanded":t,"aria-label":t?`Hide details for ${e.name}`:`Show details for ${e.name}`,onClick:()=>fe(e.id),children:(0,$.jsx)(r,{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:ra(t.provider)}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(P_,{metric:t.mentionCoverage,signal:`mentioned`,compact:!0})}),(0,$.jsx)(`td`,{className:`text-secondary`,children:(0,$.jsx)(P_,{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)(R_,{property:e,onRetryEvidence:m})})},`${e.id}:details`):null]},e.id)}),H.length===0?(0,$.jsx)(`tr`,{children:(0,$.jsx)(`td`,{colSpan:4,className:`py-8 text-center text-sm 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-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing `,H.length,` of `,e.currentView.propertyTotal]}),l?(0,$.jsx)(`span`,{role:`alert`,children:`Could not load more properties.`}):null,(0,$.jsx)(J,{size:`sm`,variant:`outline`,disabled:c,onClick:()=>f(e.currentView.nextCursor),children:c?`Loading…`:l?`Retry loading more properties`:`Show 50 more`})]}):g?H.length<e.currentView.propertyTotal?(0,$.jsxs)(`p`,{className:`mt-2 text-sm text-secondary`,children:[`Showing `,H.length,` of `,e.currentView.propertyTotal]}):null:(0,$.jsx)(F_,{shown:H.length,total:V.length,itemLabel:`properties`,onShowAll:()=>T(2**53-1)})]}),!s&&!B&&ie>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-sm font-medium text-heading`,children:[`Flagged results (`,ie,`)`]}),(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-sm`,children:[(0,$.jsx)(Y,{tone:e.tone,children:`Flagged`}),(0,$.jsx)(`span`,{className:`font-medium 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-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing details for `,e.flaggedResults.slice(0,E).reduce((e,t)=>e+(t.count??1),0),` of `,ie,` flagged results`]}),(0,$.jsx)(J,{size:`sm`,variant:`outline`,onClick:()=>D(t=>Math.min(e.flaggedResults.length,t+b_)),children:`Show 50 more`})]}):re<ie?(0,$.jsxs)(`div`,{className:`mt-3 flex items-center gap-3 text-sm text-secondary`,children:[(0,$.jsxs)(`span`,{children:[`Showing details for `,re,` of `,ie,` flagged results`]}),g&&e.currentView.nextCursor&&f?(0,$.jsx)(J,{size:`sm`,variant:`outline`,disabled:c,onClick:()=>f(e.currentView.nextCursor),children:c?`Loading…`:l?`Retry loading more Properties`:`Load more Properties`}):null]}):null]})}):null]})}function U_(e){return e===`continue`?`Continue setup`:e===`edit`?`Edit setup`:e===`republish`?`Republish setup`:`Set up advanced measurement`}function W_(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 G_(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 K_({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)(J,{type:`button`,size:`sm`,disabled:m,onClick:a,children:m?`Opening setup…`:U_(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-sm text-negative`,children:[(0,$.jsx)(`p`,{children:`Could not load the advanced measurement report.`}),s?(0,$.jsx)(J,{className:`mt-3`,type:`button`,size:`sm`,variant:`outline`,onClick:s,children:`Retry report`}):null]}):r?(0,$.jsx)(H_,{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-sm text-secondary`,children:`No advanced measurement report is available yet.`})]})}var q_={numerator:null,denominator:null,reason:`plan_v1`};function J_(e){return e.kind===`exact`?e.url:e.kind===`prefix`?`https://${e.host}${e.pathPrefix}`:`https://${e.host}`}function Y_(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 X_(e){return e===`assigned`?`this-property`:e===`sibling`?`another-property`:e===`ownedUnmapped`?`owned-unassigned`:e===`external`?`external`:e===`ambiguous`?`multiple-properties`:`invalid-url`}function Z_(e){return e===`assigned`?`positive`:e===`external`?`neutral`:e===`invalid`?`negative`:`caution`}function Q_(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 $_(e){return e.usageEdgeType!==`target`||!e.usageEdgeId.startsWith(`target:`)?null:e.usageEdgeId.slice(7).split(`:`,1)[0]??null}function ev(e){let t=new Map;for(let n of e){let e=$_(n);if(!e)continue;let r=t.get(e)??[];r.push(n),t.set(e,r)}return t}function tv(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=ev(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:X_(e.classification),query:e.queryText,url:e.sourceUrl,tone:Z_(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:Y_(e.mentionCoverage),citationCoverage:Y_(e.citationCoverage),status:l,assignedQueries:a.get(e.id)??[],urls:n?.urls.map(J_)??[],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:Q_(t.run?.finishedAt??t.run?.createdAt??null),includesBridgedHistory:t.diagnostics.bridgedObservationIds.length>0||t.diagnostics.historicalObservationIds.length>0},overall:{aggregate:{metrics:{propertiesMentioned:q_,mentionCoverage:q_,citationCoverage:q_},properties:d},groups:t.groups.map(e=>({id:e.id,label:e.label,confirmedCompetitorCount:p.get(e.id)?.competitors?.length??0,aggregate:{metrics:{propertiesMentioned:q_,mentionCoverage:q_,citationCoverage:q_},properties:e.targetIds.map(e=>f.get(e)).filter(e=>!!e)}}))},flaggedResults:[]}}function nv({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,B]=(0,Q.useState)(null),[H,te]=(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 ne(){r(!1),s(null),l(e.displayName),d(e.canonicalDomain),p(e.country),h(e.language),_(e.ownedDomains??[]),x(e.aliases??[]),y(``),C(``)}function re(){let e=v.trim();e&&(g.includes(e)||_([...g,e]),y(``))}function ie(e){_(g.filter(t=>t!==e))}function ae(){let e=S.trim();if(!e)return;let t=e.toLowerCase();b.some(e=>e.toLowerCase()===t)||x([...b,e]),C(``)}function oe(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),jn({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 ce(){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 Vt(e.name,a),j(``),N(``),F(``),L(``),z(``),k(!1),jn({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 le(t){D(!0),T(null);try{await Ne(e.name,t),jn({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 ue(t){D(!0),T(null);try{await he(e.name,t),jn({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 de(t){B(t),te(null);try{await V(e.name,t),jn({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){te(e instanceof Error?e.message:`Could not download tracking results.`)}finally{B(null)}}let fe=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??[]),pe=!U()&&!an(),me=`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,ge=`mb-1 block text-sm font-medium text-secondary`,_e=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`})]}),pe&&!n&&(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>r(!0),children:`Edit settings`})]}),o&&(0,$.jsxs)(`div`,{className:`mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative`,children:[o,(0,$.jsx)(`button`,{type:`button`,className:`ml-2 text-negative-400 hover:text-negative-200`,onClick:()=>s(null),children:`×`})]}),pe&&n?(0,$.jsxs)(`div`,{className:`rounded-lg border border-base bg-bg-elevated/40 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:ge,children:`Display name`}),(0,$.jsx)(`input`,{className:me,type:`text`,value:c,onChange:e=>l(e.target.value),placeholder:`My Project`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:ge,children:`Canonical domain`}),(0,$.jsx)(`input`,{className:me,type:`text`,value:u,onChange:e=>d(e.target.value),placeholder:`example.com`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:ge,children:`Country`}),(0,$.jsx)(`input`,{className:me,type:`text`,value:f,onChange:e=>p(e.target.value),placeholder:`US`,maxLength:2})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:ge,children:`Language`}),(0,$.jsx)(`input`,{className:me,type:`text`,value:m,onChange:e=>h(e.target.value),placeholder:`en`})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:ge,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-xs text-neutral`,children:[e,(0,$.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>ie(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`input`,{className:`${me} flex-1`,type:`text`,placeholder:`docs.example.com`,value:v,onChange:e=>y(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),re())}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:!v.trim(),onClick:re,children:`Add`})]})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:ge,children:`Aliases`}),(0,$.jsx)(`p`,{className:`mb-1.5 text-sm 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-xs text-neutral`,children:[e,(0,$.jsx)(`button`,{type:`button`,className:`ml-0.5 text-muted hover:text-strong transition-colors`,onClick:()=>oe(e),"aria-label":`Remove ${e}`,children:`×`})]},e))}),(0,$.jsxs)(`div`,{className:`flex gap-2`,children:[(0,$.jsx)(`input`,{className:`${me} flex-1`,type:`text`,placeholder:`Facebook`,value:S,onChange:e=>C(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),ae())}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:!S.trim(),onClick:ae,children:`Add`})]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 pt-2 border-t border-default`,children:[(0,$.jsx)(J,{type:`button`,disabled:i||!fe||!c.trim()||!u.trim(),onClick:kn(se),children:i?`Saving...`:`Save changes`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,disabled:i,onClick:ne,children:`Cancel`})]})]}):(0,$.jsx)(`div`,{className:`rounded-lg border border-default bg-surface overflow-hidden`,children:(0,$.jsx)(`table`,{className:`w-full text-sm`,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 font-medium 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 font-medium`,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 font-medium`,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-xs 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 font-medium`,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-xs 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 font-medium`,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 font-medium`,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 font-medium`,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-xs text-neutral`,children:e},e))})})]}):null,(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`px-4 py-2.5 text-muted font-medium 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-xs 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-xs mb-2`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`text-faint`,children:[(0,$.jsx)(`th`,{className:`text-left pb-1 font-medium pr-3`,children:`Label`}),(0,$.jsx)(`th`,{className:`text-left pb-1 font-medium pr-3`,children:`City`}),(0,$.jsx)(`th`,{className:`text-left pb-1 font-medium pr-3`,children:`Region`}),(0,$.jsx)(`th`,{className:`text-left pb-1 font-medium pr-3`,children:`Country`}),(0,$.jsx)(`th`,{className:`text-left pb-1 font-medium 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-xs font-medium ${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:[pe&&t.label!==e.defaultLocation&&(0,$.jsx)(`button`,{type:`button`,disabled:E,onClick:()=>{ue(t.label)},className:`text-sm text-secondary hover:text-positive-400 transition-colors disabled:opacity-40`,"aria-label":`Set ${t.label} as default search location`,children:`Set default`}),pe&&(0,$.jsx)(`button`,{type:`button`,disabled:E,onClick:()=>{le(t.label)},className:`text-sm 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-xs mb-2`,children:`No search locations configured`}),pe?O?(0,$.jsxs)(`div`,{className:`mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2`,children:[(0,$.jsx)(`p`,{className:`text-sm font-medium 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-sm text-secondary`,children:`Label *`}),(0,$.jsx)(`input`,{className:me,type:`text`,value:A,onChange:e=>j(e.target.value),placeholder:`nyc`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`mb-1 block text-sm text-secondary`,children:`City *`}),(0,$.jsx)(`input`,{className:me,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-sm text-secondary`,children:`Region *`}),(0,$.jsx)(`input`,{className:me,type:`text`,value:P,onChange:e=>F(e.target.value),placeholder:`NY`})]}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`label`,{className:`mb-1 block text-sm text-secondary`,children:`Country *`}),(0,$.jsx)(`input`,{className:me,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-sm text-secondary`,children:`Timezone (optional)`}),(0,$.jsx)(`input`,{className:me,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)(J,{type:`button`,size:`sm`,disabled:E||!_e,onClick:kn(ce),children:E?`Adding...`:`Add search location`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,disabled:E,onClick:()=>{k(!1),T(null)},children:`Cancel`})]})]}):(0,$.jsx)(J,{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-sm text-muted`,children:`Download historical citation and mention observations for this project. Each row is one query and provider result, including stored answer text and source URLs.`})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface 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-xs leading-5 text-muted`,children:`Includes completed, partial, and failed answer-visibility runs with stored results. Test runs are excluded. Provider credentials and raw provider payloads are never included.`}),(0,$.jsxs)(`div`,{className:`flex shrink-0 flex-wrap gap-2`,children:[(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ee!==null,onClick:kn(()=>de(`csv`)),children:ee===`csv`?`Preparing CSV...`:`Download CSV`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:ee!==null,onClick:kn(()=>de(`json`)),children:ee===`json`?`Preparing JSON...`:`Download JSON`})]})]}),H&&(0,$.jsx)(`p`,{className:`mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative`,children:H})]})]})]})}function rv(e,t,n){return C({...Vr({client:q,path:{name:e},query:{selection:n}}),enabled:t&&!!e,staleTime:An,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:An},retry:!1})}function iv(e){switch(e){case Tt.PROVIDER_BILLING:return{sentence:e=>`${e.name} ran out of credit`,label:`out of credit`};case Tt.PROVIDER_AUTH:return{sentence:e=>`${e.possessive} key was rejected or access was denied`,label:`key rejected or access denied`};case Tt.RATE_LIMITED:case Tt.PROVIDER_UNAVAILABLE:case Tt.NETWORK:case Tt.TIMEOUT:case Tt.PARSE_ERROR:case Tt.UNKNOWN:return{sentence:t=>`${t.name} failed with ${e}`,label:e}}}function av({iso:e}){return(0,$.jsx)(`time`,{dateTime:e,children:hn(e)})}function ov({admission:e,canFix:t,selection:n}){let r=(0,Q.useId)(),i=Object.entries(e.providers),a=C({...fi({client:q}),enabled:t&&i.length>0,retry:!1}).data?.providerCatalog??[],o=Ga(a),s=e=>ra(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===Tt.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=iv(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===Tt.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)(av,{iso:n}),r]}):(0,$.jsxs)($.Fragment,{children:[t,` in each of its last `,f,` runs. Checks run without it until `,(0,$.jsx)(av,{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)(av,{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-sm ${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-sm font-medium ${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),`: `,iv(t.code).label,`, until `,(0,$.jsx)(av,{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)(J,{asChild:!0,variant:`outline`,size:`sm`,className:`h-11 md:h-8`,children:(0,$.jsx)(O,{to:`/settings`,hash:`provider-${un(p[0],o)}`,children:d?`Update ${s(un(c,o))} key`:`Open provider settings`})}):null]})}var sv={edit:`Edit schedule`,pause:`Pause`,resume:`Resume`,save:`Save schedule`},cv=[{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`}],lv=[`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 uv(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 dv({projectName:e}){let t=He(),n=!U()&&!an()&&!t,r=x(),[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,S]=(0,Q.useState)(!1),[w,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=Ei({client:q,path:{name:e}}),F=C({...vi({client:q,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})},B=e=>{if(e){if(e.recurrence)s(`calendar`),p(e.recurrence.everyDays),h(e.recurrence.startDate),_(e.recurrence.time);else{let t=bn(e.preset??null,e.cronExpr);s(t.freq),l(t.hour),d(t.customCron)}let t=lv.includes(e.timezone);y(t?e.timezone:`Other`),S(!t),T(t?``:e.timezone)}else s(`daily`),l(6),d(``),p(14),h(``),_(`00:00`),y(`UTC`),S(!1),T(``);N(e?.updatedAt??null)},V=()=>{n&&(B(R),j(null),a(!0))},H=()=>{B(R),j(null)},te=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.`)},ne=async(e,t)=>{e instanceof at&&e.code===`SCHEDULE_VERSION_CONFLICT`?await te():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)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:V,children:R?sv.edit:`+ Set schedule`})]}),I&&(0,$.jsx)(`p`,{className:`supporting-copy`,children:`Loading...`}),A&&!i&&(0,$.jsx)(`p`,{className:`mt-2 text-sm 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)(J,{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-sm text-secondary`,children:`AI Visibility checks are run by your Canonry team`}),(0,$.jsx)(`p`,{className:`text-sm font-medium text-strong`,children:R.recurrence?uv(R.recurrence,R.timezone):vn(R.preset??null,R.cronExpr,R.timezone)}),!R.recurrence&&(0,$.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Cron: `,(0,$.jsx)(`span`,{className:`font-mono`,children:R.cronExpr})]}),R.enabled&&R.nextRunAt&&(0,$.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Next run: `,$e(R.nextRunAt,R.timezone)]}),R.lastRunAt&&(0,$.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Last run: `,new Date(R.lastRunAt).toLocaleString()]})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,$.jsx)(Y,{tone:R.enabled?`positive`:`neutral`,children:R.enabled?`Active`:`Paused`}),n&&(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,disabled:E,onClick:kn(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 Ye(e,i);ee(a),jn({title:a.enabled?`Schedule resumed`:`Schedule paused`,detail:a.recurrence?uv(a.recurrence,a.timezone):vn(a.preset??null,a.cronExpr,a.timezone),tone:`positive`,dedupeKey:`schedule:toggle:${e}`,dedupeMode:`replace`})}catch(e){await ne(e,`Failed to update schedule`)}finally{D(!1)}}),children:R.enabled?sv.pause:sv.resume}),n&&(0,$.jsx)(J,{type:`button`,variant:`ghost`,size:`sm`,disabled:O,onClick:kn(async()=>{if(!n||!R)return;let t=R.updatedAt;k(!0),j(null);try{await xe(e,t),ee(null),a(!1),N(void 0),jn({title:`Schedule removed`,detail:`${e} will no longer run automatically.`,tone:`positive`,dedupeKey:`schedule:remove:${e}`,dedupeMode:`drop`})}catch(e){await ne(e,`Failed to remove schedule`)}finally{k(!1)}}),children:O?`Removing...`:`Remove`})]})]})}),n&&i&&(0,$.jsxs)(`div`,{className:`rounded-lg border border-base bg-bg-elevated/40 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-sm text-caution`,role:`alert`,children:[(0,$.jsx)(`p`,{children:`This schedule changed elsewhere. Load the latest version before saving.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:H,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-xs font-medium text-secondary`,children:`Frequency`}),(0,$.jsx)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Frequency`,value:o,onChange:e=>s(e.target.value),children:cv.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-xs font-medium text-secondary`,children:`Time`}),(0,$.jsx)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none disabled:opacity-40`,value: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:mn(t)},t))})]})]}),o===`custom`&&(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-secondary`,children:`Cron expression`}),(0,$.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 font-mono focus:border-mono-500 focus:outline-none`,type:`text`,placeholder:`0 9 * * 1-5`,value: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-xs font-medium text-secondary`,children:`Repeat every`}),(0,$.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none`,"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-xs text-muted`,children:`days`})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-secondary`,children:`Start date`}),(0,$.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none`,"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-xs font-medium text-secondary`,children:`Time`}),(0,$.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none`,"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-xs font-medium text-secondary`,children:`Timezone`}),(0,$.jsxs)(`select`,{className:`w-full rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none`,"aria-label":`Timezone`,value:b?`Other`:v,onChange:e=>{e.target.value===`Other`?(S(!0),y(`Other`)):(S(!1),y(e.target.value))},children:[lv.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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`text`,placeholder:`e.g. America/New_York`,value:w,onChange:e=>T(e.target.value)})]}),A&&(0,$.jsx)(`p`,{className:`text-negative-400 text-sm`,role:`alert`,children:A}),(0,$.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{a(!1),N(void 0),j(null)},children:`Cancel`}),(0,$.jsx)(J,{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:kn(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?w.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=yn(o,c);let i=await Ye(e,r);a(!1),N(void 0),ee(i),jn({title:`Schedule saved`,detail:i.recurrence?uv(i.recurrence,i.timezone):vn(i.preset??null,i.cronExpr,i.timezone),tone:`positive`,dedupeKey:`schedule:${e}`,dedupeMode:`replace`})}catch(e){await ne(e,`Failed to save schedule`)}finally{D(!1)}}}),children:E?`Saving...`:sv.save})]})]})]})}var fv=[{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 pv({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),_=!U()&&!an();(0,Q.useEffect)(()=>{se(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 Jt(e,{channel:`webhook`,url:a.trim(),events:s});n(e=>e===`loading`?[t]:[...e,t]),o(``),c([`citation.lost`,`citation.gained`]),i(!1),jn({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 Le(e,t),n(e=>e===`loading`?e:e.filter(e=>e.id!==t)),jn({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 Ke(e,t);m(e=>({...e,[t]:{state:n.ok?`ok`:`fail`,status:n.status}})),n.ok&&jn({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)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!r),f(null)},children:r?`Cancel`:`+ Add webhook`})]}),_&&r&&(0,$.jsxs)(`div`,{className:`mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3`,children:[(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-secondary`,children:`Webhook URL`}),(0,$.jsx)(`input`,{className:`w-full rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,type:`url`,placeholder:`https://hooks.example.com/canonry`,value:a,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`space-y-1.5`,children:[(0,$.jsx)(`label`,{className:`text-xs font-medium text-secondary`,children:`Trigger on`}),(0,$.jsx)(`div`,{className:`flex flex-wrap gap-3`,children:fv.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-sm text-neutral`,children:e.label})]},e.value))})]}),d&&(0,$.jsx)(`p`,{className:`text-negative-400 text-sm`,children:d}),(0,$.jsxs)(`div`,{className:`flex gap-2 justify-end`,children:[(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>{i(!1),f(null)},children:`Cancel`}),(0,$.jsx)(J,{type:`button`,size:`sm`,disabled:l||!a.trim()||s.length===0,onClick:kn(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:`font-mono text-xs 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-[10px] font-medium text-secondary uppercase tracking-wide`,children:e.replace(`.`,` `)},e))})}),(0,$.jsx)(`td`,{children:(0,$.jsx)(Y,{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)(Y,{tone:t.state===`ok`?`positive`:t.state===`fail`?`negative`:`neutral`,children:n})})(),_&&(0,$.jsx)(J,{variant:`ghost`,size:`sm`,type:`button`,disabled:p[e.id]?.state===`testing`,onClick:()=>{x(e.id)},children:`Test`}),_&&(0,$.jsx)(J,{variant:`ghost`,size:`sm`,type:`button`,disabled:h.has(e.id),onClick:()=>{b(e.id)},children:h.has(e.id)?`Removing…`:`Remove`})]})})]},e.id))})]}),d&&(0,$.jsx)(`p`,{className:`text-negative-400 text-sm mt-2`,children:d})]})]})}function mv({open:e,projectLabel:t,onOpenChange:n,onConfirm:r,onClosed:i,disabled:a,leftOut:o=[]}){return U()||He()?null:(0,$.jsx)(xo,{open:e,onOpenChange:n,children:(0,$.jsxs)(qa,{onCloseAutoFocus:e=>{i&&(e.preventDefault(),i())},children:[(0,$.jsxs)(Co,{children:[(0,$.jsx)(Ja,{children:`Run AI Visibility check for the whole project?`}),(0,$.jsxs)(so,{children:[`Runs all tracked queries for `,t,`. View filters do not limit the check. Provider charges apply.`,o.length>0?` ${o.map(e=>ra(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)(J,{variant:`outline`,onClick:()=>n(!1),children:`Cancel`}),(0,$.jsx)(pa,{disabled:a,onClick:r,children:`Run project-wide check`})]})]})})}var hv=2e3,gv=3e5;function _v(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`competitor-draft-${Date.now()}-${Math.random().toString(36).slice(2)}`}function vv(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 yv({projectName:e,refreshNonce:t}){let n=x(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)([]),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)([]),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(``),[y,b]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(!0),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(null),[O,k]=(0,Q.useState)(`performance`);(0,Q.useEffect)(()=>{A()},[e,t]);async function A(){C(!0),D(null);try{let t=await n.fetchQuery({...kr({client:q,path:{name:e}}),staleTime:Nn});if(i(t),t.connected){let[r,i,a,s]=await Promise.all([n.fetchQuery({...ci({client:q,path:{name:e}}),staleTime:Nn}).catch(()=>null),n.fetchQuery({...Er({client:q,path:{name:e}}),staleTime:Nn}).catch(()=>[]),n.fetchQuery({...Kr({client:q,path:{name:e}}),staleTime:Nn}).catch(()=>[]),t.siteUrl?Promise.resolve([]):n.fetchQuery({...pi({client:q,path:{name:e}}),staleTime:Nn}).then(e=>e.sites).catch(()=>[])]);c(r),u(i),f(a),o(s)}else c(null),u([]),f([]),o([])}catch(e){D(e instanceof Error?e.message:`Failed to load Bing data`)}finally{C(!1)}}async function j(){if(_.trim()){D(null);try{let t=await _t(e,_.trim());await Mn(n,`bing`),v(``),t.availableSites.length>0&&o(t.availableSites),await A()}catch(e){D(e instanceof Error?e.message:`Failed to connect`)}}}async function M(){try{await Wt(e),await Mn(n,`bing`),i(null),o([]),c(null),u([]),f([]),m(null),b(``),D(null)}catch(e){D(e instanceof Error?e.message:`Failed to disconnect`)}}async function N(){if(y)try{await wt(e,y),await Mn(n,`bing`),await A()}catch(e){D(e instanceof Error?e.message:`Failed to set site`)}}async function P(){if(h.trim())try{let t=await Dt(e,h.trim());await Mn(n,`bing`),m(t),u(e=>[t,...e])}catch(e){D(e instanceof Error?e.message:`Inspection failed`)}}async function F(t){T(!0),D(null);try{let{succeeded:n,failed:r,total:i}=(await Ft(e,{urls:[t]})).summary;jn({title:`Bing submission requested`,detail:r===0?`${n} URL submitted to Bing.`:`${n}/${i} submitted successfully, ${r} failed.`,tone:r===0?`positive`:`caution`,dedupeKey:`bing:indexing:${e}:${t}`,dedupeMode:`replace`})}catch(n){let r=n instanceof Error?n.message:`Submission failed`;D(r),jn({title:`Bing submission failed`,detail:r,tone:`negative`,dedupeKey:`bing:indexing:${e}:${t}`,dedupeMode:`replace`})}finally{T(!1)}}async function I(){T(!0),D(null),jn({title:`Submitting URLs to Bing`,detail:`Requesting indexing for all currently unindexed URLs.`,tone:`neutral`,dedupeKey:`bing:indexing-all:${e}`,dedupeMode:`replace`});try{let{succeeded:t,failed:n,total:r}=(await Ft(e,{allUnindexed:!0})).summary;jn({title:`Bing submissions requested`,detail:n===0?`${t}/${r} URL${r===1?``:`s`} submitted to Bing.`:`${t}/${r} submitted successfully, ${n} failed.`,tone:n===0?`positive`:`caution`,dedupeKey:`bing:indexing-all:${e}`,dedupeMode:`replace`})}catch(t){let n=t instanceof Error?t.message:`Batch submission failed`;D(n),jn({title:`Bing submissions failed`,detail:n,tone:`negative`,dedupeKey:`bing:indexing-all:${e}`,dedupeMode:`replace`})}finally{T(!1)}}if(S)return(0,$.jsx)(Z,{className:`surface-card`,children:(0,$.jsx)(`div`,{className:`text-sm text-secondary`,children:`Loading Bing data...`})});if(!r?.connected)return U()?(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)(Y,{tone:`caution`,children:`Not connected`})]}),(0,$.jsx)(`p`,{className:`text-sm text-neutral`,children:`Bing Webmaster Tools is not connected for this project.`})]}):(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)(Y,{tone:`caution`,children:`Not connected`})]}),(0,$.jsx)(`p`,{className:`text-sm 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-xs text-muted`,htmlFor:`bing-api-key`,children:`API Key`}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2 mt-1`,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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,placeholder:`Bing Webmaster Tools API key`,value:_,onChange:e=>v(e.target.value),onKeyDown:e=>{e.key===`Enter`&&j()}}),(0,$.jsx)(pa,{size:`sm`,disabled:!_.trim(),onClick:kn(j),children:`Connect`})]}),(0,$.jsxs)(`p`,{className:`mt-1 text-sm 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 hover:text-neutral underline underline-offset-2`,children:`Bing Webmaster Tools`})]})]}),E&&(0,$.jsx)(`p`,{className:`mt-3 text-xs text-negative-400`,children:E})]});if(!r.siteUrl)return(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)(Y,{tone:`positive`,children:`Connected`}),!U()&&(0,$.jsx)(pa,{size:`sm`,variant:`ghost`,onClick:kn(M),children:`Disconnect`})]})]}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface 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-sm text-strong`,children:`Authorized for this project domain`}),(0,$.jsx)(`span`,{className:`text-xs text-muted`,children:r.domain})]}),(0,$.jsx)(`p`,{className:`mt-2 text-xs text-muted`,children:`The API key is connected, but no Bing site is selected yet. Pick the verified site that should receive inspections and indexing requests.`})]}),(0,$.jsxs)(`div`,{className:`grid gap-3 lg:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Registered domain`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:r.domain})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Last auth update`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:r.updatedAt?gn(r.updatedAt):`—`})]})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Select site`}),a.length>0?(0,$.jsxs)(`div`,{className:`mt-3 flex flex-col gap-2 lg:flex-row`,children:[(0,$.jsxs)(`select`,{className:`flex-1 rounded border border-strong bg-bg-elevated px-2 py-1.5 text-sm text-strong focus:border-mono-500 focus:outline-none`,value:y,onChange:e=>b(e.target.value),children:[(0,$.jsx)(`option`,{value:``,children:`Select a site...`}),a.map(e=>(0,$.jsxs)(`option`,{value:e.url,children:[e.url,e.verified?` (verified)`:``]},e.url))]}),!U()&&(0,$.jsx)(pa,{size:`sm`,disabled:!y,onClick:kn(N),children:`Set Site`})]}):(0,$.jsx)(`p`,{className:`mt-3 text-xs text-muted`,children:`No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything.`})]})]}),E&&(0,$.jsx)(`p`,{className:`mt-3 text-xs text-negative-400`,children:E})]});let L=[{key:`performance`,label:`Performance`,eyebrow:`Performance`,title:`Search performance`},{key:`coverage`,label:`Coverage`,eyebrow:`Coverage`,title:`Index monitoring`},{key:`inspections`,label:`Inspections`,eyebrow:`Inspection`,title:`URL inspection history`}],R=L.find(e=>e.key===O)??L[0];return(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:`Connection`}),(0,$.jsx)(`h3`,{children:`Domain authorization`})]}),(0,$.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,$.jsx)(Y,{tone:`positive`,children:`Connected`}),!U()&&(0,$.jsx)(pa,{size:`sm`,variant:`ghost`,onClick:kn(M),children:`Disconnect`})]})]}),E&&(0,$.jsx)(`p`,{className:`mb-3 text-xs text-negative-400`,children:E}),(0,$.jsxs)(`div`,{className:`space-y-3`,children:[(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface 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-sm text-strong`,children:`Authorized for this project domain`}),(0,$.jsx)(`span`,{className:`text-xs text-muted`,children:r.domain})]}),(0,$.jsxs)(`p`,{className:`mt-2 text-sm text-secondary`,children:[`This project uses `,(0,$.jsx)(`code`,{children:r.siteUrl}),`.`]})]}),(0,$.jsxs)(`div`,{className:`grid gap-3 lg:grid-cols-2`,children:[(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Selected site`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:r.siteUrl})]}),(0,$.jsxs)(`div`,{className:`rounded-lg border border-default bg-surface-subtle p-3`,children:[(0,$.jsx)(`p`,{className:`text-xs uppercase tracking-wide text-muted`,children:`Last auth update`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-strong`,children:r.updatedAt?gn(r.updatedAt):`—`})]})]})]})]}),(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:R.eyebrow}),(0,$.jsx)(`h3`,{children:R.title})]}),(0,$.jsx)(`p`,{className:`text-xs text-muted`,children:s?.lastInspectedAt?`Last inspected ${gn(s.lastInspectedAt)}`:`No inspection history yet`})]}),(0,$.jsx)(`div`,{className:`flex gap-1 border-b border-base`,children:L.map(e=>(0,$.jsx)(`button`,{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${O===e.key?`border-mono-200 text-strong`:`border-transparent text-muted hover:text-neutral`}`,onClick:()=>k(e.key),children:e.label},e.key))}),O===`coverage`&&s&&(0,$.jsxs)(`div`,{className:`mt-4 space-y-4`,children:[(0,$.jsxs)(`div`,{className:`grid gap-3 sm:grid-cols-4`,children:[(0,$.jsx)(lc,{label:`Indexed`,value:s.summary.indexed,tone:`positive`}),(0,$.jsx)(lc,{label:`Not in index`,value:s.summary.notIndexed+(s.summary.unknown??0),tone:`negative`}),(0,$.jsx)(lc,{label:`Status unknown`,value:s.summary.unknown??0,tone:`neutral`}),(0,$.jsx)(lc,{label:`Coverage`,value:W(s.summary.percentage,oe.percent),tone:`neutral`})]}),s.notIndexed.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`h4`,{className:`text-xs font-medium text-secondary`,children:[`Not Indexed (`,s.notIndexed.length,`)`]}),!U()&&(0,$.jsx)(pa,{size:`sm`,variant:`ghost`,disabled:w,onClick:kn(I),children:w?`Submitting…`:`Submit all to Bing`})]}),(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-lg border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base`,children:[(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium w-16`,children:`HTTP`}),!U()&&(0,$.jsx)(`th`,{className:`text-right py-1.5 px-3 text-muted font-medium w-20`,children:`Action`})]})}),(0,$.jsx)(`tbody`,{children:s.notIndexed.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-neutral truncate max-w-[480px]`,children:e.url}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-secondary`,children:e.httpCode??`—`}),!U()&&(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-right`,children:(0,$.jsx)(`button`,{className:`text-sm text-secondary hover:text-strong underline underline-offset-2`,disabled:w,onClick:()=>{F(e.url)},children:`Submit`})})]},e.id))})]})})]}),(s.unknown??[]).length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`mb-2 flex items-center justify-between gap-3`,children:[(0,$.jsxs)(`h4`,{className:`text-sm font-medium text-secondary`,children:[`Unknown, not yet confirmed (`,(s.unknown??[]).length,`)`]}),!U()&&(0,$.jsx)(pa,{size:`sm`,variant:`ghost`,disabled:w,onClick:kn(I),children:w?`Submitting…`:`Submit all to Bing`})]}),(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-lg border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base`,children:[(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium w-32`,children:`Last Crawled`}),!U()&&(0,$.jsx)(`th`,{className:`text-right py-1.5 px-3 text-muted font-medium w-20`,children:`Action`})]})}),(0,$.jsx)(`tbody`,{children:(s.unknown??[]).map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-neutral truncate max-w-[480px]`,children:e.url}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-secondary`,children:e.lastCrawledDate?gn(e.lastCrawledDate):`—`}),!U()&&(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-right`,children:(0,$.jsx)(`button`,{className:`text-sm text-secondary hover:text-strong underline underline-offset-2`,disabled:w,onClick:()=>{F(e.url)},children:`Submit`})})]},e.id))})]})})]}),s.indexed.length>0&&(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h4`,{className:`mb-2 text-xs font-medium text-secondary`,children:[`Indexed (`,s.indexed.length,`)`]}),(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-lg border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base`,children:[(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium w-32`,children:`Last Crawled`})]})}),(0,$.jsx)(`tbody`,{children:s.indexed.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-neutral truncate max-w-[480px]`,children:e.url}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-secondary`,children:e.lastCrawledDate?gn(e.lastCrawledDate):`—`})]},e.id))})]})})]})]}),O===`coverage`&&!s&&(0,$.jsx)(`p`,{className:`mt-4 text-xs text-muted`,children:`No coverage data yet. Inspect URLs to build coverage data.`}),O===`inspections`&&(0,$.jsxs)(`div`,{className:`mt-4 space-y-3`,children:[!U()&&(0,$.jsxs)(`div`,{className:`flex flex-col gap-2 lg:flex-row`,children:[(0,$.jsx)(`input`,{type:`text`,className:`flex-1 rounded border border-strong bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,placeholder:`URL to inspect`,value:h,onChange:e=>g(e.target.value),onKeyDown:e=>{e.key===`Enter`&&P()}}),(0,$.jsx)(pa,{size:`sm`,disabled:!h.trim(),onClick:kn(P),children:`Inspect`})]}),p&&(0,$.jsxs)(`div`,{className:`rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1`,children:[(0,$.jsx)(`div`,{className:`font-medium text-strong`,children:p.url}),(0,$.jsxs)(`div`,{className:`text-secondary`,children:[`In Index: `,(0,$.jsx)(`span`,{className:p.inIndex?`text-positive-400`:`text-negative-400`,children:p.inIndex?`Yes`:`No`}),` · `,`HTTP: `,p.httpCode??`—`,` · `,`Crawled: `,p.lastCrawledDate??`—`]})]}),l.length>0&&(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-lg border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base`,children:[(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium`,children:`URL`}),(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium w-16`,children:`Index`}),(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium w-14`,children:`HTTP`}),(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium w-32`,children:`Inspected`})]})}),(0,$.jsx)(`tbody`,{children:l.map(e=>(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-neutral truncate max-w-[480px]`,children:e.url}),(0,$.jsx)(`td`,{className:`py-1.5 px-3`,children:(0,$.jsx)(Y,{tone:e.inIndex?`positive`:`negative`,children:e.inIndex?`Yes`:`No`})}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-secondary`,children:e.httpCode??`—`}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-secondary`,children:gn(e.inspectedAt)})]},e.id))})]})})]}),O===`performance`&&(0,$.jsx)(`div`,{className:`mt-4`,children:d.length===0?(0,$.jsx)(`p`,{className:`text-xs text-muted`,children:`No Bing performance data available.`}):(0,$.jsx)(`div`,{className:`overflow-x-auto rounded-lg border border-default`,children:(0,$.jsxs)(`table`,{className:`w-full text-xs`,children:[(0,$.jsx)(`thead`,{children:(0,$.jsxs)(`tr`,{className:`border-b border-base`,children:[(0,$.jsx)(`th`,{className:`text-left py-1.5 px-3 text-muted font-medium`,children:`Query`}),(0,$.jsx)(`th`,{className:`text-right py-1.5 px-3 text-muted font-medium w-16`,children:xn[Cn.Clicks]}),(0,$.jsx)(`th`,{className:`text-right py-1.5 px-3 text-muted font-medium w-16`,children:xn[Cn.Impressions]}),(0,$.jsx)(`th`,{className:`text-right py-1.5 px-3 text-muted font-medium w-14`,children:xn[Cn.CTR]}),(0,$.jsx)(`th`,{className:`text-right py-1.5 px-3 text-muted font-medium w-14`,children:xn[Cn.Position]})]})}),(0,$.jsx)(`tbody`,{children:d.map((e,t)=>(0,$.jsxs)(`tr`,{className:`border-b border-subtle`,children:[(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-neutral truncate max-w-[480px]`,children:e.query}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-right text-strong`,children:e.clicks}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-right text-secondary`,children:e.impressions}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-right text-secondary`,children:W(e.ctr)}),(0,$.jsx)(`td`,{className:`py-1.5 px-3 text-right text-secondary`,children:e.averagePosition.toFixed(1)})]},t))})]})})})]})]})}function bv({projectName:e}){let t=x(),[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),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0);async function _(n=!1){n||a(!0),l(null);try{let[n,r]=await Promise.all([t.fetchQuery({...or({client:q,path:{name:e}}),staleTime:Nn}).catch(()=>[]),t.fetchQuery({...kr({client:q,path:{name:e}}),staleTime:Nn}).catch(()=>null)]),i=n.find(e=>e.connectionType===`gsc`)??null;f(i),m(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),jn({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(!d)return;let t=await Yt(e);if(!t?.id)return;let n=Date.now()+gv;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,hv)),r.aborted))return;let e=await Se(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(!p?.connected)return;let t=await Rt(e).catch(()=>null);if(!t?.id){i.push(`Bing check could not be started`);return}let n=Date.now()+gv;for(;Date.now()<n;){if(r.aborted||(await new Promise(e=>setTimeout(e,hv)),r.aborted))return;let e=await Se(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.`)}let c=await Promise.allSettled([n(),o()]);for(let e of c)e.status===`rejected`&&i.push(e.reason instanceof Error?e.reason.message:`Sync failed`);if(await Promise.all([Mn(t,`gsc`),Mn(t,`bing`)]),r.aborted)return;if(s(`reloading`),await _(!0),g(e=>e+1),i.length>0){let t=`Partial refresh: ${[...i,...a].join(`; `)}`;l(t),jn({title:`Search coverage partially refreshed`,detail:t,tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`})}else a.length>0?jn({title:`Search coverage refresh incomplete`,detail:a.join(`; `),tone:`caution`,dedupeKey:`search-console-refresh:${e}`,dedupeMode:`replace`}):jn({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),jn({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)(()=>(_(),()=>{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))}),!U()&&(0,$.jsxs)(pa,{type:`button`,variant:`outline`,size:`sm`,"aria-label":`Refresh search data`,disabled:i||o!==`idle`,onClick:()=>void y(),children:[(0,$.jsx)(v,{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-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative`,children:c}),n===`google`&&(0,$.jsx)(Ul,{projectName:e,refreshNonce:h}),n===`bing`&&(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 engine`}),(0,$.jsx)(`h2`,{children:`Bing Webmaster Tools`})]})}),(0,$.jsx)(yv,{projectName:e,refreshNonce:h})]})]})}function xv({label:e,summary:t,displayValue:n,tooltip:r}){let{figure:i,sign:a}=dn(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 ${lo[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 Sv({id:e,title:t,meta:n,defaultOpen:i=!1,children:a}){return(0,$.jsxs)(`details`,{id:e,className:`overview-disclosure page-section-divider scroll-mt-24`,open:i||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)(r,{className:`overview-disclosure-icon`,size:16,"aria-hidden":`true`})]})]}),(0,$.jsx)(`div`,{className:`overview-disclosure-body`,children:a})]})}function Cv({insights:e,suggestedQueries:t,onManageQueries:n,siteDomain:r}){let{openEvidence:i}=Fa(),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-sm font-medium text-heading`,children:e.title}),e.detail?(0,$.jsx)(`p`,{className:`mt-1 max-w-3xl text-sm leading-6 text-secondary`,children:e.detail}):null]}),(0,$.jsx)(Y,{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-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[`Evidence · `,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)(us,{state:t.citationState,...r&&t.siteCitation!==!1?{label:_n(r,t.citationState)}:{}}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 text-sm text-strong`,children:t.query}),t.provider?(0,$.jsx)(mo,{provider:t.provider}):null,!U()&&t.evidenceId?(0,$.jsx)(J,{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-xs font-medium uppercase tracking-wide text-muted`,children:`Suggested query`}),(0,$.jsx)(`p`,{className:`mt-1 text-sm font-medium text-strong`,children:e.query}),(0,$.jsx)(`p`,{className:`mt-1 text-sm text-secondary`,children:e.reason})]}),n?(0,$.jsx)(J,{type:`button`,variant:`outline`,size:`sm`,onClick:n,children:`Review in Queries`}):null]},e.query),c=e.slice(0,1),l=a.slice(0,1),u=e.slice(1),d=a.slice(1),f=u.length+d.length;return(0,$.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-sm font-medium text-secondary transition-colors hover:text-heading focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60`,children:[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 wv(e){let{projectName:t}=D({from:`/projects/$projectName`}),n=Xa()?.dashboard.projects.find(e=>e.project.name===t||e.project.id===t)?.project.name??null,r=C({...gr({client:q}),enabled:!n}),i=n??r.data?.find(e=>e.name===t||e.id===t)?.name??null,a=ct(),o=Ka(e.tab,po(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}=La(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)(J,{asChild:!0,children:(0,$.jsx)(O,{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)(J,{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)(kv,{model:d,refetch:v,latestVisibilityRevision:g,competitorHistoryRevision:_,overviewLoading:p,overviewError:m,overviewRequested:l,onRequestOverview:u,...e})}function Tv({items:e,overflowItems:t,settingsItem:n,activeTab:i}){let a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),[s,c]=(0,Q.useState)(null);(0,Q.useLayoutEffect)(()=>{let r=a.current,s=o.current;if(!r||!s)return;let l=()=>{let a=r.getBoundingClientRect().width;if(!a)return;let o=Number.parseFloat(getComputedStyle(r).columnGap)||0,l=new Map([...s.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)*o,f=[...e.map(e=>e.key),...t.length?[`more`]:[],...n?[n.key]:[]],p=e.map(e=>e.key),m=!1;if(d(f)>a){let t=e.find(e=>e.key===i),r=t?[t.key]:[];m=!!(n&&d([...r,`more`,n.key])>a);let o=[`more`,...n&&!m?[n.key]:[]];for(let n of e)if(n.key!==t?.key){if(d([...r,n.key,...o])>a)break;r.push(n.key)}p=e.filter(e=>r.includes(e.key)).map(e=>e.key)}c(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(r),u.observe(s),()=>u.disconnect()},[e,t,n,i]);let l=s?e.filter(e=>s.visibleKeys.includes(e.key)):e,u=[...e.filter(e=>!l.includes(e)),...t,...s?.settingsInMore&&n?[n]:[]];return(0,$.jsxs)(`nav`,{className:`project-subnav`,"aria-label":`Project sections`,ref:a,children:[(0,$.jsx)(`div`,{className:`project-subnav-measure`,"aria-hidden":`true`,children:(0,$.jsxs)(`div`,{className:`project-subnav-measure-row`,ref:o,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)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]})]})}),l.map(e=>(0,$.jsx)(O,{to:e.href,search:e=>({...e,onboarding:void 0}),className:`project-subnav-link ${e.key===i?`project-subnav-link-active project-subnav-current`:``}`,"aria-current":e.key===i?`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)(Ev,{items:u,activeTab:i}),n&&!s?.settingsInMore&&(0,$.jsx)(O,{to:n.href,search:e=>({...e,onboarding:void 0}),className:`project-subnav-link ${i===`settings`?`project-subnav-link-active`:``}`,"aria-current":i===`settings`?`page`:void 0,children:n.label})]})]})}function Ev({items:e,activeTab:t}){let[n,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),s=(0,Q.useRef)(`first`),c=(0,Q.useId)(),l=e.map(e=>e.key).join();if((0,Q.useEffect)(()=>{i(!1)},[l]),(0,Q.useEffect)(()=>{if(!n)return;let e=a.current?.querySelectorAll(`[role="menuitem"]`);(s.current===`last`?e?.[e.length-1]:e?.[0])?.focus()},[n]),(0,Q.useEffect)(()=>{if(!n)return;let e=e=>{a.current&&!a.current.contains(e.target)&&i(!1)},t=e=>{e.key===`Escape`&&(i(!1),o.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:a,children:[(0,$.jsxs)(`button`,{type:`button`,ref:o,className:`project-subnav-link project-subnav-more-trigger ${u?`project-subnav-link-active`:``}`,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?c:void 0,onClick:()=>{s.current=`first`,i(e=>!e)},onKeyDown:e=>{(e.key===`ArrowDown`||e.key===`ArrowUp`)&&(e.preventDefault(),s.current=e.key===`ArrowUp`?`last`:`first`,i(!0))},children:[`More`,(0,$.jsx)(r,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})]}),n?(0,$.jsx)(`div`,{className:`project-subnav-menu`,role:`menu`,id:c,"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=>{a.current?.contains(e.relatedTarget)||i(!1)},children:e.map(e=>(0,$.jsx)(O,{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:()=>i(!1),children:e.label},e.key))}):null]})}var Dv=20,Ov=5;function kv({tab:e,model:t,refetch:n,latestVisibilityRevision:r,competitorHistoryRevision:i,overviewLoading:a,overviewError:o,overviewRequested:s,onRequestOverview:c}){let l=w(),u=x(),{account:d,canWrite:f,isAdmin:p}=On(),[m,h]=(0,Q.useState)(null),_=(0,Q.useRef)(null),v=Xa(),y=t.project.name,b=v?.dashboard.projects.some(e=>e.project.name===y)??!1,D=T({strict:!1}),A=ia(D),j=cs(A),M=C({...ti({client:q,path:{name:y}}),enabled:!U()&&!!y&&(f||e===`portfolio`||e===`overview`||e===`settings`||j),staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`}),N=v?v.dashboard.settings.providerStatuses.filter(e=>e.state===`ready`).map(e=>_o(e.name)):void 0,P=M.data?.answerVisibilityProviderReady,F=N,I=t.project.providers.map(_o),L=F?.some(e=>I.length===0||I.includes(e))===!0,R=I.length===0||I.includes(`cdp:chatgpt`),z=C({...oi({client:q}),enabled:!U()&&f&&P===void 0&&R&&!L,staleTime:6e4,retry:!1}),ee=R?z.isSuccess?typeof z.data.browserVersion==`string`:!z.isError&&void 0:!1,B=P??$a({projectProviders:I,configuredApiProviders:F,cdpConfigured:ee}),V=(0,Q.useMemo)(()=>po(ct()),[]),H=Ka(e,V),ne=(0,Q.useMemo)(()=>t.competitors.map(e=>e.domain),[t.competitors]),re=(0,Q.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.aliases??[]])),[t.competitors]),ie=(0,Q.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,e.autoAliases??[]])),[t.competitors]),ae=(0,Q.useMemo)(()=>Object.fromEntries(t.competitors.map(e=>[e.domain,[...e.aliases??[],...e.autoAliases??[]]])),[t.competitors]),[oe,se]=(0,Q.useState)(!1),[ce,le]=(0,Q.useState)(!1),ue=za(),fe=(0,Q.useCallback)((e,t)=>{l({to:`.`,search:t=>da(t,e),replace:t?.replace===!0})},[l]),pe=D.queryWorkspace===`research`||H===`discovery`&&D.queryWorkspace===void 0?`research`:`tracked`,me=as(pe,is(d?.role,d?.role===`viewer`?mt():null)),he=C({...jr({client:q,path:{name:y}}),enabled:!U()&&(H===`queries`||H===`discovery`)&&me===`tracked`}),ge=D.manageQueries===!0,_e=(0,Q.useCallback)(()=>{l({to:`.`,replace:!0,search:e=>({...e,siteHealthRunId:void 0})})},[l]),[ve,ye]=(0,Q.useState)(ge),[be,xe]=(0,Q.useState)(``),[Se,Ce]=(0,Q.useState)(!1),[W,we]=(0,Q.useState)(null),[Te,G]=(0,Q.useState)(`30d`),[Ee,De]=(0,Q.useState)(void 0),[Oe,ke]=(0,Q.useState)(``),[je,Me]=(0,Q.useState)(!1),[Ne,Fe]=(0,Q.useState)(null),[Ie,Le]=(0,Q.useState)(!1),Re=Ma(D),[Be,Ve]=(0,Q.useState)(void 0),[Ue,We]=(0,Q.useState)(void 0),K=(0,Q.useCallback)(e=>{Ve(e.search),e.sort&&We(e.sort),l({to:`.`,search:t=>({...t,...Oa(e)}),replace:!1})},[l]),[Ge,Ke]=(0,Q.useState)(!1),qe=t?.project.displayName||t?.project.name||y,Je=Eo(),Ye=C({...Or({client:q,path:{name:y}}),enabled:H===`portfolio`&&!!y,staleTime:0,refetchOnMount:`always`}),Xe=C({...Rn({client:q,path:{name:y}}),enabled:!U()&&!!y&&(f||an()||H===`portfolio`||H===`overview`||H===`settings`),staleTime:0,refetchOnMount:`always`}),Ze=Xe.data?.active??null,Qe=Xe.data!==void 0,$e=new Set(Ze&&Number(Ze.plan.schemaVersion)===2?Ze.plan.groups?.map(e=>e.stableKey)??[]:[]),et={...Re.scope===`group`&&Re.groupKey&&Qe&&!$e.has(Re.groupKey)?{scope:`all`,queryClass:Re.queryClass}:Re,...Be?{search:Be}:{}},tt=Ze===null?null:Number(Ze.plan.schemaVersion),nt=Ze?.revision??0,rt=Qe?`${y}:${nt}`:null,it=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=it.current;rt!==null&&(it.current=rt),ho(e,rt)&&(K({scope:`all`,queryClass:`all`}),Ke(!1))},[rt,K]);let at={client:q,path:{name:y},query:{scope:et.scope,...et.groupKey?{groupKey:et.groupKey}:{},queryClass:et.queryClass,...et.search?{search:et.search}:{},...Ue?{sort:Ue}:{},limit:50}},ot=E({...hr(at),enabled:!1,initialPageParam:at,getNextPageParam:(e,t)=>{if(!e.properties.nextCursor)return;let n=t[0]?.measurement.displayedRunId;return{path:at.path,query:{...at.query,cursor:e.properties.nextCursor,...n?{runId:n}:{}}}},placeholderData:k,staleTime:0,refetchOnMount:`always`}),st=ot.data?.pages[0]?.measurement.displayedRunId,lt=C({...Sr({client:q,path:{name:y},query:{revision:nt,...st?{runId:st}:{}}}),enabled:H===`overview`&&!!y&&Ze!==null&&tt===1,staleTime:0,refetchOnMount:`always`}),ut=Xe.data!==void 0,dt=Ye.data!==void 0,pt=Xe.isPending&&!ut,gt=Xe.isError&&!ut,_t=Ye.isPending&&!dt,bt=Ye.isError&&!dt,St=lt.data!==void 0,Ct=W_({activePlanSchemaVersion:M.data?.activeSchemaVersion??tt,hasDraft:M.data?.draft!==null&&M.data?.draft!==void 0}),wt=Ct.surface===`simple-overview`,Tt=an()&&Ze?.plan.schemaVersion===2?G_(Ze.plan):null,Et=M.data===void 0&&Xe.data===void 0&&(Xe.isLoading||M.isLoading);(0,Q.useEffect)(()=>{H===`overview`&&wt&&!Et&&c()},[Et,wt,c,H]);let Dt=ls({tab:H,surface:Et?`unresolved`:Ct.surface,embedded:U(),scoped:j,queryWorkspace:me,tracking:he.isError?{state:`error`}:he.data?{state:`ready`,mode:he.data.mode,scopeUnavailable:os(he.data,A)}:{state:`pending`}}),Ot=Pf(y,A,{enabled:Dt.kind===`report-picker`}),kt=H===`overview`&&wt&&!Et,At=La(y,{evidence:kt}),jt=At.commandCenter?.visibilityEvidence??t.visibilityEvidence,Mt=(0,Q.useMemo)(()=>{let e=new Map(jt.map(e=>[yt(e.query),e.queryClass??null])),n=cn(te(t.project));return t=>{let r=e.get(yt(t));return r===void 0?n?.classify(t)??null:r}},[jt,t.project]),Pt=(0,Q.useMemo)(()=>[...new Set([...jt.map(e=>e.query),...t.movementComparison.addedQueries,...t.movementComparison.removedQueries])],[jt,t.movementComparison]),Ft=(0,Q.useMemo)(()=>{if(!cn(te(t.project)))return!1;let e=new Set(jt.map(e=>Mt(e.query)));return e.has(`branded`)&&e.has(`non-brand`)},[t.project,jt,Mt]),It=(0,Q.useMemo)(()=>t.visibilitySweeps.map(e=>e.createdAt),[t.visibilitySweeps]),Lt=f&&!U()&&!He()&&H!==`overview`,Rt=C({...Or({client:q,path:{name:y}}),enabled:Lt,staleTime:Pn,refetchOnWindowFocus:`always`}),zt=tt===2&&A.measurementScope===`group`?A.measurementScopeKey:void 0,Bt=tt===2&&A.measurementScope===`project`,Vt=(0,Q.useMemo)(()=>{if(Ze?.plan.schemaVersion===2&&zt)return Ze.plan.groups.find(e=>e.stableKey===zt)},[Ze,zt]),Ht={client:q,path:{name:y},query:{window:Te,queryClass:tt===2&&A.queryClass!==`unknown`?A.queryClass:`non-brand`,...zt?{groupKey:zt}:{},...Bt?{scope:`all-markets`}:{}}},Ut=H===`overview`&&!A.marketKey&&!!y&&(wt||Qe)&&!Et&&(wt||(A.measurementScope===`project`||tt===2&&A.measurementScope===`group`)&&A.queryClass!==`unknown`&&(tt===2||A.queryClass!==`branded`)),[Wt,Gt]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{Ut||Gt(null)},[Ut]),(0,Q.useEffect)(()=>{Gt(null)},[y]);let Kt=Wt===y,Jt=Ut&&Kt,Yt=C({...$r(Ht),enabled:Jt,staleTime:0,refetchOnMount:`always`,refetchOnWindowFocus:`always`});Ca(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,nt,M.data?.draft?.etag??null]),Jt);let Xt=Yt.isError?Yt.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,Y=(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]),Zt=(0,Q.useMemo)(()=>{if(Ze?.plan.schemaVersion!==2)return Y;let e=zt?Vt?.competitors??[]:Ze.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 Y){let n=e.domain.trim().toLowerCase();n&&!t.has(n)&&t.set(n,e)}return[...t.values()]},[Ze,zt,Y,Vt]),Qt=tt===2?Zt:Y,en=S({...mi({client:q}),meta:{skipGlobalErrorToast:!0}}),tn=M.data===void 0?M.isError?`error`:`pending`:`success`,nn=(0,Q.useMemo)(()=>{let e=ot.data?.pages;return e?!Go(e):!1},[ot.data]),rn=(0,Q.useMemo)(()=>{let e=ot.data?.pages,t=e?.[0],n=e?.at(-1);if(t&&n&&!nn)return{...t,properties:{...t.properties,items:e.flatMap(e=>e.properties.items),nextCursor:n.properties.nextCursor}}},[nn,ot.data]),on=(0,Q.useMemo)(()=>{if(Ze)return Ze.plan.schemaVersion===1?lt.data?tv(Ze,lt.data):void 0:rn?Bo({overview:rn,activePlan:Ze,sort:Ue,report:lt.data,reportState:rn.measurement.displayedRunId===void 0?`ready`:lt.isFetching&&lt.data===void 0?`loading`:lt.isError&&lt.data===void 0?`error`:lt.data?`ready`:`loading`}):void 0},[Ze,lt.data,lt.isError,lt.isFetching,rn]),sn=tt===2?nn?`error`:ot.isPending?`loading`:ot.isError&&on===void 0?`error`:`ready`:lt.isPending&&!St?`loading`:lt.isError&&!St?`error`:`ready`,ln=(t?.recentRuns??[]).some(e=>e.kind===ht[`answer-visibility`]&&(e.status===vt.running||e.status===vt.queued)),un=rv(y,!U()&&!He(),`manual`).data,dn=rv(y,!U(),`scheduled`).data,fn=un&&dn&&JSON.stringify(un)!==JSON.stringify(dn),pn=un?.refused===!0,mn=un&&!un.refused?Object.keys(un.providers):[],hn=t.queryCounts.total>0,_n=(0,Q.useMemo)(()=>(t?.project.locations??[]).map(e=>e.label),[t?.project.locations]),vn=(0,Q.useMemo)(()=>new Set(jt.map(e=>e.location??``)),[jt]),yn=vn.has(``),bn=(0,Q.useMemo)(()=>[...new Set(jt.map(e=>e.query))].sort((e,t)=>e.localeCompare(t)),[jt]),xn=bn.length>0||t.queryCounts.total>0||(Rt.data?.length??0)>0||Ze!==null,Sn=f&&!xn&&(Xe.data===void 0&&Xe.isPending||Rt.isLoading||kt&&At.evidenceLoading),Cn=f&&(M.isError&&!M.isFetching||Lt&&Rt.isError&&!Rt.isFetching),wn=f&&!Cn&&(Sn||B===void 0||M.isFetching),Tn=!wn&&!Cn&&xn&&B===!0,En=f&&!wn&&!Tn,Dn=!U()&&H===`overview`&&En&&!xn,An=C({...Zn({client:q,path:{name:y},query:{limit:Dv}}),enabled:Dn&&!!y,retry:!1}),Mn=An.isSuccess&&An.data.scans.some(e=>e.status===`completed`||e.status===`partial`),Nn=Dn&&An.isSuccess&&!Mn,Fn=Dn&&Mn,In=C({...vi({client:q,path:{name:y}}),enabled:!U()&&!He()&&!!y,retry:!1}).data?.find(e=>e.kind===ht[`answer-visibility`]),Ln=In?.enabled&&In.nextRunAt?Aa(In.nextRunAt,In.timezone):null,zn=Ln?`Next AI Visibility check ${Ln}`:null,Bn=(0,Q.useMemo)(()=>{let e=[...vn].filter(Boolean);return e.length>1?e:_n},[vn,_n]);(0,Q.useEffect)(()=>{!kt||Ee===void 0||Ee===``||!y?(Fe(null),Le(!1)):(Le(!0),qt(y,Ee,20).then(e=>{Fe(e),Le(!1)}).catch(()=>{Fe(null),Le(!1)}))},[Ee,y,kt]);let Vn=(0,Q.useMemo)(()=>{if(!Ne)return null;let e=new Map;for(let t of Ne){for(let[n,r]of Object.entries(t.providerRuns??{}))e.set(`${t.query}::${n}`,r.map(e=>({runId:e.runId,citationState:e.citationState,createdAt:e.createdAt,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:e.visibilityTransition,mentionState:e.mentionState,mentionTransition:e.mentionTransition})));(!t.providerRuns||Object.keys(t.providerRuns).length===0)&&e.set(`${t.query}::`,t.runs.map(e=>({runId:e.runId,citationState:e.citationState,createdAt:e.createdAt,answerMentioned:e.answerMentioned,visibilityState:e.visibilityState,visibilityTransition:e.visibilityTransition,mentionState:e.mentionState,mentionTransition:e.mentionTransition})))}return e},[Ne]),Hn=(0,Q.useMemo)(()=>{let e=Ee===void 0?jt:jt.filter(e=>Ee===``?!e.location:e.location===Ee);return Vn?e.map(e=>{let t=Vn.get(`${e.query}::${e.provider}`)??Vn.get(`${e.query}::`);return t?{...e,runHistory:t}:e}):e},[jt,Ee,Vn]);async function Un(){if(!(m!==y||!f||U()||He()||Je.isPending||ln||pn||!Tn))try{await Je.mutateAsync({projectName:y,projectLabel:qe,sourceAction:`project-run`}),h(null)}catch{}}function Wn(){l({to:`/setup`,search:{experience:`legacy`,setupProject:y}})}function Gn(){l({to:`/projects/$projectName/technical-aeo`,params:{projectName:y}})}async function Kn(){le(!0);try{await Pe(y),jn({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{le(!1)}}async function qn(){let e=be.split(`
8
- `).map(e=>e.trim()).filter(Boolean);if(e.length!==0){Ce(!0);try{await $t(y,e),xe(``)}finally{Ce(!1)}}}async function Jn(e){we(e);try{await de(y,[e])}catch(t){jn({title:`Could not remove query`,detail:t instanceof Error?t.message:`Failed to remove "${e}"`,tone:`negative`,dedupeKey:`query:remove`,dedupeMode:`replace`})}finally{we(null)}}async function Yn(e){let t=e.trim();if(!t)return!1;try{return await Nt(y,[t]),!0}catch(e){let n=e,r=ft(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 Nt(y,[t],{acknowledgeBulkAdd:!0}),!0}catch(e){n=e}}return jn({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 Xn(e){let n=t.competitors.find(t=>t.domain===e);if(!n)return jn({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 Ae(y,n.id),!0}catch(e){return jn({title:`Could not remove competitor`,detail:e instanceof Error?e.message:`Failed to remove ${n.domain}`,tone:`negative`,dedupeKey:`competitor:remove`,dedupeMode:`replace`}),!1}}async function Qn(e){let t=e.trim();if(!t||!zt||tt!==2||!f||U()||en.isPending)return!1;try{let e=await en.mutateAsync({client:q,path:{name:y},headers:{"Idempotency-Key":_v()},body:{expectedActiveRevision:nt,groupKey:zt,domain:t}});return Promise.allSettled([M.refetch()]),jn({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:${zt}:${t}`,dedupeMode:`replace`}),!0}catch(e){return jn({title:`Could not add market competitor`,detail:e instanceof Error?e.message:`Failed to add ${t} to the market draft.`,tone:`negative`,dedupeKey:`competitor:market-pin:error`,dedupeMode:`replace`}),!1}}async function $n(e,t){let n=await xt(e,t);return u.setQueryData(hi({client:q,path:{name:e}}),n),vv(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`},{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=>bo(e.key,V)),ir=nr.filter(e=>bo(e.key,V)),ar=f||U()||an(),or=ar&&bo(`settings`,V)?{key:`settings`,label:`Settings`,href:`${er}/settings`}:null;function sr(e){let n=wt?e:(0,$.jsx)(Lf,{projectName:y,selection:A,showUnmeasuredFallback:!Ze&&!hn&&A.measurementScope===`project`&&A.queryClass===`all`&&!A.provider&&!A.model&&!A.location&&!A.from&&!A.to&&!A.revision&&!A.measurementRunId&&!A.queryKey&&!A.marketKey,onSelectionChange:fe,onManageQueries:U()?void 0:()=>{l({to:`/projects/$projectName/queries`,params:{projectName:y},search:e=>({...e,queryWorkspace:`tracked`,trackingQueryId:void 0,measurementMarketKey:void 0})})},renderPropertyLink:U()?void 0:({id:e,label:t})=>(0,$.jsx)(O,{to:`/projects/$projectName/properties/$targetKey`,params:{projectName:y,targetKey:e},search:oa,"aria-label":`Property details for ${t}`,className:`inline-flex min-h-11 items-center text-sm text-link hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400`,children:`Property details`}),trackingChangedAt:U()||He()?void 0:Ze?.createdAt,nextSweepDate:U()||He()||ln?void 0:Ln??void 0,fallback:e});if(U())return n;let r=na(A,wt?`simple`:`advanced`,typeof D.sentimentEvaluationDefinitionId==`string`?D.sentimentEvaluationDefinitionId:void 0);return wt&&(r.location=Ee===``?`none`:Ee,r=xa(r,Hn,Oe)),(0,$.jsx)(no,{hasSourceEvidence:!wt||!!(r.runId||r.runIds?.length),evidenceReady:!wt||!(At.isLoading||At.evidenceLoading||At.evidenceError),waitForResolvedRun:!wt,projectName:y,runOptions:t.visibilitySweeps.slice(0,Ov).map(e=>({id:e.id,label:gn(e.finishedAt??e.createdAt)})),selection:r,children:n})}function cr(){switch(Dt.kind){case`report-picker`:{if(Ot.error)return ze(ft(Ot.error))?(0,$.jsx)(`p`,{className:`text-[13px] text-secondary`,children:rs.savedScopeUnavailable}):null;let e=Ot.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=ss(e.scopeOptions,A)??e.selection.scope;return(0,$.jsx)(Uo,{labelVisibility:`sr-only`,options:e.scopeOptions,selected:t,marketKey:A.marketKey,onSelect:(e,t)=>fe({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id,measurementMarketKey:t})})}case`tracking-picker`:{let e=he.data?.scopeOptions??[],t=ss(e,A);return t?(0,$.jsx)(Uo,{labelVisibility:`sr-only`,options:e,selected:t,onSelect:e=>fe({measurementScope:e.kind,measurementScopeKey:e.kind===`project`?void 0:e.id})}):null}case`scope-unavailable`:return(0,$.jsx)(`p`,{className:`text-[13px] text-secondary`,children:rs.savedScopeUnavailable});case`project-wide`:return(0,$.jsxs)(`span`,{className:`flex items-center gap-1`,children:[(0,$.jsx)(`span`,{className:`text-[13px] text-secondary`,children:rs.projectWide}),(0,$.jsx)(X,{text:rs.projectWideHelp})]});case`none`:return null}}let lr=H===`overview`&&!wt&&(A.from||A.to)?`${A.from?.slice(0,10)??`First measurement`} to ${A.to?.slice(0,10)??`Latest measurement`}`:null,ur=cr(),dr=Ut?(0,$.jsx)(Vs,{window:Te,landscape:Yt.data,pinnedFallback:Qt,competitorAliases:re,competitorAutoAliases:ie,canWrite:f,isEmbed:U(),onWindowChange:G,onPin:zt&&f&&!U()?Qn:!Bt&&f&&!U()?Yn:void 0,onUnpin:zt||Bt||!f||U()?void 0:Xn,onAddCompetitor:zt&&f&&!U()?Qn:!Bt&&f&&!U()?Yn:void 0,error:Xt,onRetry:Jt?()=>{Yt.refetch()}:void 0,isLoading:Jt&&Yt.isPending&&Yt.data===void 0,scopeLabel:zt?`${Vt?.label??zt} group`:Bt?`All markets`:`Project-wide`,advancedPortfolio:!wt}):null,fr=U()?null:(0,$.jsx)($.Fragment,{children:(0,$.jsx)(pa,{type:`button`,variant:`outline`,size:`sm`,onClick:()=>ye(!ve),children:ve?`Done`:`Manage queries`})}),pr=!U()&&ve?(0,$.jsxs)(`div`,{className:`mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3`,children:[bn.length>0?(0,$.jsx)(`ul`,{className:`mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default`,children:bn.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-sm text-strong`,title:e,children:e}),(0,$.jsx)(`button`,{type:`button`,className:`shrink-0 rounded px-1.5 py-0.5 text-xs text-muted transition-colors hover:text-negative-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-negative-500 disabled:opacity-50`,"aria-label":`Remove query ${e}`,title:`Stop tracking "${e}"`,disabled:W!==null,onClick:()=>{Jn(e)},children:W===e?`Removing…`:`Remove`})]},e))}):(0,$.jsx)(`p`,{className:`mb-3 text-xs 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-sm text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none`,rows:3,placeholder:`Enter queries to add, one per line`,value:be,onChange:e=>xe(e.target.value)}),(0,$.jsxs)(`div`,{className:`mt-2 flex items-center justify-between`,children:[(0,$.jsxs)(`p`,{className:`text-xs text-muted`,children:[be.split(`
9
- `).filter(e=>e.trim()).length,` to add`]}),(0,$.jsx)(pa,{type:`button`,size:`sm`,disabled:!be.trim()||Se,onClick:kn(qn),children:Se?`Adding...`:`Add queries`})]})]}):null;return(0,$.jsxs)(`div`,{className:`page-container`,children:[U()?(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:He()?`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-sm 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,Tt===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:Tt})]}),(0,$.jsx)(`div`,{className:`project-context-actions`,"data-project-actions":!0,children:He()?(0,$.jsx)(Ji,{projectName:y,running:ln,portfolio:!wt}):(0,$.jsxs)($.Fragment,{children:[zn?(0,$.jsx)(`p`,{className:`text-sm text-secondary`,children:zn}):null,Nn?(0,$.jsx)(pa,{type:`button`,onClick:Gn,children:`Map site`}):Fn?(0,$.jsx)(pa,{type:`button`,onClick:Gn,children:`View Page Health`}):null,(0,$.jsx)(pa,{type:`button`,variant:`outline`,disabled:Je.isPending||ln||wn||pn&&!Cn&&!En,onClick:Cn?()=>{Promise.all([M.refetch(),...Lt?[Rt.refetch()]:[]])}:En?Wn:e=>{_.current=e.currentTarget,h(y)},children:Je.isPending?`Starting…`:ln?`AI Visibility check running…`:wn?`Checking AI readiness…`:Cn?`Retry AI readiness`:En?`Set up AI Visibility`:pn?`AI Visibility checks on hold`:`Run AI Visibility check`})]})})]}),!U()&&!He()&&(0,$.jsx)(mv,{open:m===y,projectLabel:qe,onOpenChange:e=>h(e?y:null),onConfirm:kn(Un),onClosed:()=>_.current?.focus(),disabled:Je.isPending||ln||pn||!Tn,leftOut:mn}),(0,$.jsx)(Tv,{items:rr,overflowItems:ir,settingsItem:or,activeTab:H}),H===`portfolio`&&!U()?(0,$.jsx)(f_,{projectName:y,canEdit:f,queries:Ye.data??[],isQueryLoading:_t,isQueryError:bt,onRetryQueries:()=>{Ye.refetch()},publishedPlan:Ze,sweepActive:ln,executionProviders:t.project.providers,executionProviderModels:t.project.providerModels,onCreateQueries:async e=>(await ue.mutateAsync({projectName:y,queries:[...e]}),(await Ye.refetch({throwOnError:!0})).data??[]),onManageProjectQueries:()=>{l({to:`/projects/$projectName`,params:{projectName:y},search:{manageQueries:!0}})},onPublished:()=>{Promise.all([M.refetch(),Xe.refetch()]).finally(()=>{l({to:`/projects/$projectName`,params:{projectName:y}})})}},y):H===`overview`?(0,$.jsxs)($.Fragment,{children:[U()?null:(0,$.jsxs)($.Fragment,{children:[dn?(0,$.jsx)(ov,{admission:dn,canFix:f&&p,selection:fn||!un?`scheduled`:void 0}):null,un&&(fn||!dn)?(0,$.jsx)(ov,{admission:un,canFix:f&&p,selection:`manual`}):null]}),Et||wt&&!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`})]}):wt&&o?(0,$.jsxs)(`div`,{role:`alert`,className:`page-section-divider`,children:[(0,$.jsx)(`p`,{children:`Could not load AI visibility.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,$.jsxs)($.Fragment,{children:[gt?(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-sm text-negative`,children:[(0,$.jsx)(`span`,{children:`Could not check the advanced measurement setup. Existing project-wide results remain available.`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{Xe.refetch()},children:`Retry setup check`})]}):null,sr((0,$.jsx)(K_,{mode:Ct,canEdit:f&&!U()&&!pt&&!gt,simpleOverview:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`section`,{className:`page-section-divider`,children:(0,$.jsx)(bp,{projectName:t.project.name,competitorDomains:ne,competitorAliases:ae,analyticsRevision:r,queryTexts:Pt,classifyQuery:Mt,sweepTimes:It,queryClassSplit:Ft})}),(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`}),hn?(0,$.jsx)(`p`,{className:`av-card-meta`,children:`Latest check`}):null]}),hn?(0,$.jsxs)(`div`,{className:`competitive-summary`,children:[(0,$.jsx)(_s,{summary:t.mentionShareSummary,projectLabel:t.project.displayName||t.project.name,competitorDomains:ne},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)(xv,{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)(xv,{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-sm 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)(Hd,{projectName:t.project.name,classify:Mt,hasCompetitors:ne.length>0,providerScores:t.providerScores})}),(0,$.jsxs)(Sv,{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 ${Ee===void 0?`filter-chip-active`:``}`,type:`button`,"aria-pressed":Ee===void 0,onClick:()=>{De(void 0)},children:`All locations`}),t.project.locations.map(e=>(0,$.jsx)(`button`,{className:`filter-chip ${Ee===e.label?`filter-chip-active`:``}`,type:`button`,"aria-pressed":Ee===e.label,onClick:()=>{De(e.label),Me(!1)},children:e.label},e.label)),yn&&(0,$.jsx)(`button`,{className:`filter-chip ${Ee===``?`filter-chip-active`:``}`,type:`button`,"aria-pressed":Ee===``,onClick:()=>{De(``),Me(!1)},children:`No location`}),Bn.length>1&&Ee===void 0&&(0,$.jsx)(`button`,{className:`filter-chip filter-chip-compare ${je?`filter-chip-active`:``}`,type:`button`,"aria-pressed":je,onClick:()=>Me(e=>!e),title:`Side-by-side location comparison`,children:`Compare`})]}),At.evidenceLoading||At.evidenceError?(0,$.jsxs)($.Fragment,{children:[fr&&(0,$.jsx)(rc,{actions:fr}),pr,At.evidenceLoading?(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:`Loading query evidence…`}):(0,$.jsxs)(`div`,{role:`alert`,className:`text-sm text-secondary`,children:[(0,$.jsx)(`p`,{children:`Could not load query evidence.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{At.refetch()},children:`Retry`})]})]}):(0,$.jsx)(ic,{evidence:Hn,compareLocations:je,providerSelection:Oe,onProviderSelectionChange:ke,addedQueries:t.movementComparison.addedQueries,actions:fr,actionPanel:pr})]}),!U()&&(0,$.jsx)(`div`,{className:`page-section-divider`,children:(0,$.jsx)(Wd,{runs:t.recentRuns,projectName:t.project.name,collapsed:!0})})]}),report:on,reportState:sn,onOpenSetup:U()?void 0:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:y}})},onRetryReport:()=>{tt===2?Promise.all([ot.refetch(),lt.refetch()]):lt.refetch()},onViewChange:e=>{K({scope:e.scope,...e.groupKey?{groupKey:e.groupKey}:{},queryClass:e.queryClass,...e.search?.trim()?{search:e.search.trim()}:{}})},onLoadMore:e=>{e===rn?.properties.nextCursor&&ot.fetchNextPage()},onPropertyExpand:()=>{Ge&&lt.isError&&lt.refetch(),Ke(!0)},onRetryEvidence:()=>{lt.refetch()},isViewLoading:ot.isPlaceholderData,isLoadingMore:ot.isFetchingNextPage,isLoadMoreError:ot.isFetchNextPageError,viewSearch:et.search??``},`${y}:${nt}`)),!wt&&A.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-sm text-secondary`,children:`Loading project signals…`}):o?(0,$.jsxs)(`div`,{role:`alert`,className:`text-sm text-secondary`,children:[(0,$.jsx)(`p`,{children:`Could not load project signals.`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{n()},children:`Retry`})]}):(0,$.jsx)(Cv,{insights:t.insights,suggestedQueries:t.suggestedQueries,siteDomain:t.project.canonicalDomain||void 0,onManageQueries:U()?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${wt?` page-section-divider`:``}`,open:Kt,onToggle:e=>Gt(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})]})]})]}):H===`settings`?ar?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(nv,{project:{...t.project,displayName:t.project.displayName??t.project.name,defaultLocation:t.project.defaultLocation??null},onUpdateProject:async(e,t)=>{await $n(e,t)}}),(0,$.jsx)(Va,{project:t.project,onSave:async e=>{await $n(t.project.name,e)}}),(0,$.jsx)(fo,{project:t.project,onSave:async e=>{await $n(t.project.name,{siteAuditMaxPages:e})}},t.project.id),f&&!U()?(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold 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.`}),tn===`pending`?(0,$.jsx)(`p`,{role:`status`,className:`text-sm text-secondary`,children:`Loading setup…`}):tn===`error`?(0,$.jsxs)(`div`,{role:`alert`,className:`flex flex-wrap items-center gap-3 text-sm text-negative`,children:[(0,$.jsx)(`span`,{children:`Could not load advanced measurement setup.`}),(0,$.jsx)(J,{type:`button`,size:`sm`,variant:`outline`,onClick:()=>{M.refetch()},children:`Retry`})]}):(0,$.jsx)(J,{type:`button`,variant:`outline`,onClick:()=>{l({to:`/projects/$projectName/portfolio`,params:{projectName:y}})},children:U_(Ct.setupAction)})]}):null,(0,$.jsx)(dv,{projectName:t.project.name}),(0,$.jsx)(pv,{projectName:t.project.name}),f&&!U()?(0,$.jsxs)(`section`,{className:`page-section-divider`,children:[(0,$.jsx)(`h2`,{className:`text-lg font-semibold 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.`}),oe?(0,$.jsxs)(Z,{className:`surface-card p-6 border-negative-800/60`,children:[(0,$.jsx)(`h3`,{className:`text-base font-semibold text-negative-400 mb-2`,children:`Delete project?`}),(0,$.jsxs)(`p`,{className:`text-sm 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)(J,{type:`button`,variant:`destructive`,disabled:ce,onClick:kn(Kn),children:ce?`Deleting...`:`Yes, delete project`}),(0,$.jsx)(J,{type:`button`,variant:`outline`,disabled:ce,onClick:()=>se(!1),children:`Cancel`})]})]}):(0,$.jsxs)(pa,{type:`button`,variant:`outline`,onClick:()=>se(!0),children:[(0,$.jsx)(g,{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)(J,{asChild:!0,children:(0,$.jsx)(O,{to:`/projects/$projectName`,params:{projectName:y},children:`Return to overview`})})]}):H===`queries`||H===`discovery`?(0,$.jsx)(Vp,{projectName:y,queryWorkspace:pe,onQueryWorkspaceChange:e=>fe({queryWorkspace:e,trackingQueryId:void 0}),researchMode:D.researchMode===`test`?`test`:`find`,onResearchModeChange:e=>fe({researchMode:e}),selection:A,onSelectionChange:fe,trackingQueryId:typeof D.trackingQueryId==`string`?D.trackingQueryId:void 0,onTrackingQueryIdChange:e=>fe({trackingQueryId:e}),publishGuard:{sweepActive:ln}}):H===`technical-aeo`?(0,$.jsx)(Lo,{projectName:t.project.name,projectId:t.project.id,initialRunId:D.siteHealthRunId,onReleaseInitialRun:_e}):H===`conversions`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Uh,{projectName:t.project.name},`${t.project.id}:performance`),(0,$.jsx)(wh,{projectId:t.project.id,projectName:t.project.name},t.project.id)]}):H===`history`?(0,$.jsx)(Pm,{projectName:t.project.name}):H===`activity`?(0,$.jsx)(cl,{projectName:t.project.name}):H===`backlinks`?(0,$.jsx)(Eu,{projectName:t.project.name}):H===`seo-data`?(0,$.jsx)($u,{projectName:t.project.name},t.project.id):H===`local`?(0,$.jsx)(Gl,{projectName:t.project.name,projectId:t.project.id}):H===`search-console`?(0,$.jsx)(bv,{projectName:t.project.name}):null]})}export{wv as ProjectPage,Tv as ProjectSubnav,mv as ProjectSweepConfirmation,vv as patchProjectDashboardCache};