@canonry/canonry 4.134.0 → 4.135.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/agent-workspace/skills/canonry/references/aeo-analysis.md +3 -2
- package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +34 -6
- package/assets/assets/{AuditHistoryPanel-DBUWbfNk.js → AuditHistoryPanel-BS0dmlrQ.js} +1 -1
- package/assets/assets/{BacklinksPage-BFm0VdUO.js → BacklinksPage-CPpWLVfa.js} +1 -1
- package/assets/assets/{ChartPrimitives-oV_nduTH.js → ChartPrimitives-Dv--2i87.js} +1 -1
- package/assets/assets/{HistoryPage-IF2FMem3.js → HistoryPage-BO4Fv-9q.js} +1 -1
- package/assets/assets/ProjectPage-Di_nDqtH.js +8 -0
- package/assets/assets/{RunRow-De5zdch5.js → RunRow-BE8zdGJ8.js} +1 -1
- package/assets/assets/{RunsPage-xtRF78r8.js → RunsPage-CbGanhaz.js} +1 -1
- package/assets/assets/{SettingsPage-B_GAxaWu.js → SettingsPage-odOpsOuf.js} +1 -1
- package/assets/assets/{TrafficPage-E8I5ineJ.js → TrafficPage-DK7oc0DK.js} +1 -1
- package/assets/assets/{TrafficSourceDetailPage-DGk2MqSp.js → TrafficSourceDetailPage-CEFjQVuF.js} +1 -1
- package/assets/assets/{arrow-left-D-4QMxi9.js → arrow-left-DgzLEzZB.js} +1 -1
- package/assets/assets/{extract-error-message-DuqIFU8Z.js → extract-error-message-vlMjpZb2.js} +1 -1
- package/assets/assets/{index-De1MKbc7.js → index-BMlTgq7D.js} +72 -72
- package/assets/assets/{trash-2-BVh__r6G.js → trash-2-DX33Ys-K.js} +1 -1
- package/assets/index.html +1 -1
- package/dist/{chunk-TKXWTDV6.js → chunk-3PFRVEWP.js} +99 -31
- package/dist/{chunk-ZUQPHGEN.js → chunk-PAR6P5H6.js} +35 -3
- package/dist/{chunk-PC7AYXND.js → chunk-PXEEWJRV.js} +74 -20
- package/dist/{chunk-LIXWDIDR.js → chunk-TPVMHYHD.js} +188 -97
- package/dist/cli.js +63 -26
- package/dist/index.js +4 -4
- package/dist/{intelligence-service-4XOFUN5E.js → intelligence-service-BMEJ5GFZ.js} +2 -2
- package/dist/mcp.js +2 -2
- package/package.json +9 -9
- package/assets/assets/ProjectPage-ClwxX9Ga.js +0 -8
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{j as e,r as o,L as ft,n as At,u as ve,o as vs,A as wi,B as Si,h as ki}from"./vendor-tanstack-Be8JdV5M.js";import{c as Vs,T as ae,t as Ci,a as Ai,u as $a,C as $i,b as Ws,P as Xt,B as R,h as Pi,d as Li,e as Di,f as et,g as V,i as T,j as de,I as Te,k as xs,l as Ri,m as W,n as Ii,o as Ti,p as Mi,q as Ei,r as Pa,s as Oi,v as Bi,S as Mt,w as Fi,x as _i,y as qi,z as It,A as Gi,D as Hn,E as La,G as qe,F as $n,H as Ui,J as Qi,K as zi,L as Ki,M as Hi,N as Y,O as Vn,Q as Da,R as Vi,U as Wi,V as Yi,W as Ji,X as Xi,Y as Zi,Z as er,_ as tr,$ as sr,a0 as nr,a1 as ar,a2 as ir,a3 as rr,a4 as or,a5 as lr,a6 as cr,a7 as Ft,a8 as dr,a9 as Ra,aa as Gs,ab as ur,ac as mr,ad as xr,ae as hr,af as Us,ag as pr,ah as gr,ai as fr,aj as br,ak as bn,al as jr,am as yr,an as jn,ao as vr,ap as en,aq as Ot,ar as Ia,as as Ta,at as Nr,au as wr,av as Ma,aw as Sr,ax as kr,ay as Cr,az as Ar,aA as Ea,aB as $r,aC as Pr,aD as Lr,aE as js,aF as Et,aG as Dr,aH as Rr,aI as Ir,aJ as Tr,aK as Oa,aL as Mr,aM as Er,aN as Or,aO as Br,aP as Fr,aQ as Ba,aR as _r,aS as Ys,aT as qr,aU as Gr,aV as Ur,aW as Qr,aX as zr,aY as Kr,aZ as Hr,a_ as Vr,a$ as Wr,b0 as Yr,b1 as Jr,b2 as Xr,b3 as Zr,b4 as eo,b5 as to,b6 as so,b7 as no,b8 as ao,b9 as io,ba as tn,bb as ro,bc as oo,bd as Wn,be as lo,bf as co,bg as uo,bh as mo,bi as xo,bj as ho,bk as po,bl as go,bm as fo,bn as bo,bo as jo,bp as yo,bq as Yn,br as vo,bs as sn,bt as No,bu as Jn,bv as Xn,bw as wo,bx as So,by as ko,bz as Co,bA as Ao,bB as $o,bC as Po,bD as Lo,bE as Fa,bF as _a,bG as Do,bH as qa,bI as Ro,bJ as Ga,bK as Io,bL as To,bM as Is,bN as Mo,bO as Eo,bP as Oo,bQ as Zn}from"./index-De1MKbc7.js";import{R as Bo}from"./RunRow-De5zdch5.js";import{f as yn,C as jt,a as st,b as Qs,c as Bt,d as Ve,e as He,g as bt,h as Fo,i as Pn,j as Ln,k as Ct,o as lt,p as _o}from"./ChartPrimitives-oV_nduTH.js";import{u as qo,t as Go,R as gt,e as ea}from"./extract-error-message-DuqIFU8Z.js";import{R as Zt,C as es,X as ts,Y as ss,T as ns,L as Ua,A as Ht,a as Dn,b as Uo,d as Rn,e as Qo}from"./vendor-recharts-DSxTZhaH.js";import{C as Qa,D as fs,a as zo,E as Ko,T as Ho}from"./trash-2-BVh__r6G.js";import{A as Vo}from"./AuditHistoryPanel-DBUWbfNk.js";import"./vendor-radix-CQ77EO2y.js";import"./vendor-markdown-6dwjPOKK.js";const Wo=[["path",{d:"M5 12h14",key:"1ays0h"}]],Yo=Vs("minus",Wo);const Jo=[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]],Xo=Vs("scan-search",Jo);const Zo=[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]],el=Vs("unplug",Zo);const tl=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],sl=Vs("upload",tl);function _s(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function nl(t,s){return s<=0?null:Math.round((t-s)/s*100)}function nn(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${_s(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${_s(t.prior)} ${s})`:`Flat ${n} (${_s(t.prior)} ${s})`}const za=30;function ta(t){return Math.round(t*10)/10}function al(t){return t.prior>=za&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% vs prior`:`${t.deltaAbs>0?"+":""}${ta(t.deltaAbs)} vs ${ta(t.prior)}`}function il(t,s,n){return t.prior>=za&&t.deltaPct!==null?`${t.deltaPct>0?"+":""}${t.deltaPct}% ${n}`:`${t.deltaAbs>0?"+":""}${_s(Math.round(t.deltaAbs))} ${s} ${n}`}const rl=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Ka(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Ha(t){return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&t.endsWith("s")&&!t.endsWith("ss")?t.slice(0,-1):t}function Va(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Ka).map(Ha).filter(Boolean)):new Set}function Wa(t,s){const n=Ka(t).map(Ha).filter(Boolean).filter(a=>!rl.has(a)).filter(a=>!s.has(a));return[...new Set(n)].sort().join(" ")}function ol(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function ll(t,s){const n=Va(t);if(s.length<=1||n.size===0)return[...s];const a=new Set,i=[];for(const r of s){if(r.category!=="content"){i.push(r);continue}const l=Wa(ol(r),n);!l||a.has(l)||(a.add(l),i.push(r))}return i}function cl(t){const s=Va(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const a=new Set;return n.filter(i=>{const r=Wa(i.query,s);return!r||a.has(r)?!1:(a.add(r),!0)})}function vn({state:t,label:s}){return e.jsx(ae,{tone:Ai(t),children:s??Ci(t)})}function sa({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-faint",children:"No data"});const a={cited:"bg-positive-400","not-cited":"bg-mono-600",lost:"bg-negative-400",emerging:"bg-caution-400 ring-1 ring-caution-300/60"},i={cited:"rounded-full","not-cited":"rounded-sm",lost:"rotate-45 rounded-[1px]",emerging:"rounded-full"},r=new Date(n[0].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),l=new Date(n[n.length-1].createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"}),h=n.map(u=>`${new Date(u.createdAt).toLocaleDateString()}: ${u.citationState}${u.model?`, model ${u.model}`:""}`).join("; ");return e.jsxs("div",{className:"flex items-center gap-1",role:"img","aria-label":`Citation history across ${n.length} runs. ${h}`,children:[e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:r}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,"aria-hidden":"true",children:n.map((u,m)=>e.jsx("span",{className:`h-2.5 w-2.5 ${i[u.citationState]??"rounded-sm"} ${a[u.citationState]??"bg-mono-700"} ${u.model&&m>0&&n[m-1]?.model&&n[m-1].model!==u.model?"ring-1 ring-caution-300/80 ring-offset-1 ring-offset-bg":""}`,title:[u.citationState,new Date(u.createdAt).toLocaleDateString(),u.model?`model ${u.model}`:null,u.model&&m>0&&n[m-1]?.model&&n[m-1].model!==u.model?"model changed":null].filter(Boolean).join(" · ")},`${u.runId}:${u.createdAt}`))}),e.jsx("span",{className:"text-[9px] text-faint shrink-0","aria-hidden":"true",children:l})]})}function Nn(t){const s=new Map;for(const a of t)for(const i of a.runHistory){const r=s.get(i.createdAt);r?r.states.push(i.citationState):s.set(i.createdAt,{states:[i.citationState],runId:i.runId})}return[...s.entries()].sort(([a],[i])=>a.localeCompare(i)).map(([a,{states:i,runId:r}])=>({runId:r,createdAt:a,citationState:i.includes("cited")?"cited":i.includes("emerging")?"emerging":"not-cited"}))}const dl=320;function na(t,s){return s==="citations"?t.citationState:t.visibilityState==="pending"||t.answerMentioned==null&&t.visibilityState==null?"pending":t.visibilityState==="visible"||t.answerMentioned===!0?"cited":"not-cited"}function aa(t,s){if(s==="mentions")switch(t){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(t){case"cited":return"Cited";case"not-cited":return"Not Cited";case"lost":return"Lost";case"emerging":return"Emerging";case"pending":return"Pending"}}function ia(t,s){const n=s==="mentions"?"mentioned":"cited",a=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const i=t[t.length-1].citationState,r=t[t.length-2].citationState;if(r!=="cited"&&i==="cited")return`Newly ${n}`;if(r==="cited"&&i!=="cited")return"Lost since last run";let l=0;for(let h=t.length-1;h>=0&&t[h].citationState===i;h--)l++;return i==="cited"?l<=1?`${a} in latest run`:`${a} for ${l} runs`:l<=1?`Not ${n} in latest run`:`Not ${n} across ${l} runs`}function ul(t,s){return t.map(n=>Ya(n,s))}function Ya(t,s){return s==="citations"?t:{...t,citationState:na(t,s),runHistory:t.runHistory.map(n=>({...n,citationState:na(n,s)}))}}function ra(t,s){const n=s==="mentions"?"mention":"citation",a=s==="mentions"?"Mention":"Citation";if(t.length===0)return{key:s,label:`${a} pending`,tone:"pending"};const i=t[t.length-1].citationState,r=t.length>=2?t[t.length-2].citationState:null,l=i==="cited"||i==="emerging",h=r==="cited"||r==="emerging";return i==="lost"||r!==null&&h&&!l?{key:s,label:`Lost ${n}`,tone:"negative"}:i==="emerging"||r!==null&&!h&&l?{key:s,label:`New ${n}`,tone:"positive"}:r===null&&l?{key:s,label:`First ${n}`,tone:"positive"}:l?{key:s,label:s==="mentions"?"Still mentioned":"Still cited",tone:"neutral"}:{key:s,label:`No ${n}`,tone:"neutral"}}function ml(t){const s=Nn(ul(t,"mentions")),n=Nn(t);return[ra(s,"mentions"),ra(n,"citations")]}function xl({signal:t}){const s=t.tone==="positive"?"border-positive-500/25 bg-positive-500/10 text-positive":t.tone==="negative"?"border-negative-500/25 bg-negative-500/10 text-negative":t.tone==="pending"?"border-caution-500/20 bg-caution-500/10 text-caution":"border-mono-700/60 bg-bg-elevated/70 text-secondary";return e.jsx("span",{className:`inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium leading-none ${s}`,children:t.label})}function oa({items:t}){return e.jsx("div",{className:"mt-1 flex flex-wrap gap-1","aria-label":"Latest run mention and citation signals",children:ml(t).map(s=>e.jsx(xl,{signal:s},s.key))})}function hl({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:a}=$a(),[i,r]=o.useState(new Set),[l,h]=o.useState("mentions"),[u,m]=o.useState(n),p=o.useMemo(()=>{const N=new Map;for(const b of t){const I=b.query,G=s?b.location??null:null,M=s?JSON.stringify([I,G]):I,z=N.get(M)??{key:M,phrase:I,location:G,items:[],rawItems:[]};z.items.push(Ya(b,l)),z.rawItems.push(b),N.set(M,z)}return[...N.values()]},[t,l,s]),d=N=>{r(b=>{const I=new Set(b);return I.has(N)?I.delete(N):I.add(N),I})},S=l==="mentions"?"mentioned":"cited",f=l==="mentions"?"Mention History":"Citation History",C=l==="mentions"?"mentioned":"cited";return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":l==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="mentions"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":l==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${l==="citations"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>h("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-muted",children:l==="mentions"?"Brand or domain in answer text":"Brand or domain in source links"}),e.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong",onClick:()=>{r(N=>N.size===p.length?new Set:new Set(p.map(b=>b.key)))},children:i.size===p.length&&p.length>0?"Collapse all":"Expand all"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-bg-elevated/60 border border-subtle",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="compact"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-mono-800 text-heading":"text-secondary hover:text-strong"}`,onClick:()=>m("detailed"),children:"Detailed"})]})]})]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{style:{width:"2rem"}}),e.jsx("th",{scope:"col",children:"Query"}),e.jsx("th",{scope:"col",children:"Status"}),e.jsx("th",{scope:"col",children:f}),e.jsx("th",{scope:"col",children:"Latest run"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:p.map(({key:N,phrase:b,location:I,items:G,rawItems:M})=>{const z=i.has(N),x=G.map(y=>y.citationState),A=x.includes("cited")?"cited":x.includes("emerging")?"emerging":x.includes("lost")?"lost":x.every(y=>y==="pending")?"pending":"not-cited",_=Nn(G),ee=G.filter(y=>y.citationState===$i.cited||y.citationState==="emerging").length,oe=ia(_,l);return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-mono-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>d(N),onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),d(N))},tabIndex:0,role:"button","aria-expanded":z,children:[e.jsx("td",{children:e.jsx(Ws,{size:14,className:`transition-transform duration-150 text-muted ${z?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-heading",children:b}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-muted",children:I??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:G.map(y=>e.jsx(Xt,{provider:y.provider},y.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vn,{state:A,label:aa(A,l)}),e.jsxs("span",{className:"text-[11px] text-muted",title:`${ee} of ${G.length} engines ${C}`,children:[ee,"/",G.length]})]})}),e.jsx("td",{children:e.jsx(sa,{history:_})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:oe}),e.jsx(oa,{items:M})]}),e.jsx("td",{})]}),z&&G.map((y,g)=>e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:"bg-surface",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Xt,{provider:y.provider})}),e.jsx("td",{children:e.jsx(vn,{state:y.citationState,label:aa(y.citationState,l)})}),e.jsx("td",{children:e.jsx(sa,{history:y.runHistory})}),e.jsxs("td",{className:"evidence-change-cell",children:[e.jsx("div",{children:ia(y.runHistory,l)}),e.jsx(oa,{items:[M[g]??y]})]}),e.jsx("td",{children:e.jsx(R,{variant:"ghost",size:"sm",type:"button",onClick:K=>{K.stopPropagation(),a(y.id)},children:"View"})})]}),u==="detailed"&&e.jsxs("tr",{className:"bg-surface-subtle",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(fl,{item:y,onViewFull:()=>a(y.id)})})]})]},y.id))]},N)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",S==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function pl(t){const s=(t.matchedTerms??[]).filter(i=>i.trim().length>2),n=[...t.competitorDomains.flatMap(i=>{const r=Li(i);return r.length>=4?[r]:[]}),...t.recommendedCompetitors??[]].filter(i=>i.trim().length>2),a=[];return s.length>0&&a.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&a.push({terms:n,className:"answer-highlight-competitor"}),a}function gl(t,s){if(t.length<=s)return{body:t,truncated:!1};const n=t.lastIndexOf(" ",s);return{body:`${t.slice(0,n>s-40?n:s).trimEnd()}…`,truncated:!0}}function fl({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-muted italic",children:"No answer text captured for this run."});const{body:a,truncated:i}=gl(t.answerSnippet,dl),r=pl(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-neutral",children:Pi(a,r)}),(t.citedDomains.length>0||t.competitorDomains.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[t.citedDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited:"}),t.citedDomains.slice(0,6).map(l=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-bg-elevated/60 px-2 py-0.5 text-[11px] text-neutral",children:l},`c-${l}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.citedDomains.length-6," more"]})]}),t.competitorDomains.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-negative-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(l=>e.jsx("span",{className:"rounded-full border border-negative-900/40 bg-negative-950/30 px-2 py-0.5 text-[11px] text-negative",children:l},`co-${l}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-muted",children:["+",t.competitorDomains.length-4," more"]})]})]}),i&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-positive-400 hover:text-positive",onClick:l=>{l.stopPropagation(),s()},children:"View full answer →"})]})}function bl({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:a}){if(t.length===0)return e.jsx("p",{className:"text-sm text-muted",children:"No competitors configured. Add competitors to track overlap."});const i=s!=null,r=n!=null;return e.jsx("div",{className:"competitor-table-wrap",children:e.jsxs("table",{className:"competitor-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Domain"}),e.jsx("th",{children:"Pressure"}),e.jsx("th",{children:"Citations"}),e.jsx("th",{children:"Queries"}),r&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(l=>{const h=a!=null&&a.toLowerCase()===l.domain.toLowerCase(),u=[i?"cursor-pointer hover:bg-mono-800/30 transition-colors":"",h?"bg-negative-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:u,onClick:i?()=>s(l.domain):void 0,title:i?`Filter answers to queries where ${l.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-heading",children:l.domain}),e.jsx("td",{children:e.jsx(ae,{tone:Di(l.pressureLabel),children:l.pressureLabel})}),e.jsx("td",{className:"text-neutral tabular-nums",children:l.totalQueries>0?`${l.citationCount} / ${l.totalQueries}`:"—"}),e.jsx("td",{className:"text-muted text-xs",children:l.citedQueries.length>0?l.citedQueries.join(", "):"Not cited"}),r&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"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","aria-label":`Remove competitor ${l.domain}`,title:`Remove ${l.domain}`,onClick:m=>{m.stopPropagation(),n(l.domain)},children:"Remove"})})]},l.id)})})]})})}function la({eyebrow:t,title:s,status:n,tone:a,targetLabel:i,targetValue:r,coverageValue:l,note:h,updatedAt:u,active:m,onClick:p}){return e.jsxs("button",{type:"button",onClick:p,className:`surface-card w-full text-left transition-colors ${m?"border-mono-200 bg-bg-elevated/50":"hover:border-strong hover:bg-bg-elevated/40"}`,children:[e.jsxs("div",{className:"section-head",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:t}),e.jsx("h3",{children:s})]}),e.jsx(ae,{tone:a,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:i}),e.jsx("p",{className:"mt-1 truncate text-sm text-strong",children:r})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:l})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-muted sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:h}),e.jsx("span",{children:u?`Updated ${et(u)}`:"No recent sync yet"})]})]})}function Ts({label:t,value:s,tone:n}){const a=n==="positive"?"text-positive-400":n==="negative"?"text-negative-400":"text-strong";return e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${a}`,children:s})]})}const jl=6,as="__other__",Yt="_socialTotal";function yl(t,s=jl){const n=new Map;for(const p of t)n.set(p.source,(n.get(p.source)??0)+p.sessions);const a=[...n.entries()].sort((p,d)=>d[1]!==p[1]?d[1]-p[1]:p[0].localeCompare(d[0])),i=a.slice(0,s),r=new Set(i.map(([p])=>p)),l=Math.max(0,a.length-s),h=new Map;for(const p of t){let d=h.get(p.date);d||(d={date:p.date,[Yt]:0},h.set(p.date,d));const S=r.has(p.source)?p.source:as;d[S]=(d[S]??0)+p.sessions,d[Yt]=(d[Yt]??0)+p.sessions}const u=[...h.values()].sort((p,d)=>String(p.date).localeCompare(String(d.date))),m=i.map(([p])=>p);return l>0&&m.push(as),{data:u,sources:m,otherCount:l}}function Jt(t){return t.replace(/\+/g," ")}function Ja(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const vl=["7d","30d","90d","all"],St=He,wn=Ve.textDim,Xa=Ve.textFaint,hs=25,Ms=50;function Es(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Za(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Nl({projectName:t}){const{data:s,isLoading:n,isError:a}=qo(t);if(n)return e.jsx(V,{className:"p-5",children:e.jsx("div",{className:"text-sm text-muted",children:"Loading server activity…"})});if(a)return e.jsx(V,{className:"p-5",children:e.jsx("div",{className:"text-sm text-negative-400",children:"Failed to load server activity."})});const i=s?.sources??[];return e.jsxs("section",{children:[e.jsx("div",{className:"flex items-baseline justify-between mb-3",children:e.jsxs("div",{children:[e.jsx("div",{className:"eyebrow",children:"Server activity (last 24h)"}),e.jsx("h2",{className:"text-lg font-semibold text-primary",children:"Crawler hits, AI fetches & AI referral sessions"}),e.jsxs("p",{className:"text-xs text-muted mt-1",children:["Server-side log evidence of bulk crawlers, on-demand AI user fetches (ChatGPT-User, Perplexity-User), and AI referral sessions — orthogonal to GA4 click-through traffic below."," ",!T()&&e.jsx(ft,{to:"/traffic",className:"text-link hover:underline",children:"Manage sources →"})]})]})}),i.length===0?e.jsx(V,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-secondary",children:["No server traffic source connected yet."," ",!T()&&e.jsxs(e.Fragment,{children:[e.jsx(ft,{to:"/traffic",className:"text-link hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})]})}):e.jsx(V,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-bg-elevated/50 text-[10px] uppercase tracking-wide text-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Source"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium",children:"Status"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Crawler hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI hits 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"AI sessions 24h"}),e.jsx("th",{className:"text-right px-4 py-2 font-medium",children:"Last sync"}),e.jsx("th",{className:"text-left px-4 py-2 font-medium","aria-label":"open"})]})}),e.jsx("tbody",{children:i.map(r=>e.jsxs("tr",{className:"border-t border-default",children:[e.jsx("td",{className:"px-4 py-3 text-heading",children:r.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ae,{tone:Go(r.status),children:r.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-heading",children:r.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-secondary text-xs",children:r.lastSyncedAt?Za(r.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:T()?e.jsx("span",{className:"text-muted text-xs",children:"Detail"}):e.jsx(ft,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:r.id},className:"text-link hover:underline text-xs",children:"Detail →"})})]},r.id))})]})})]})}function wl({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(Nl,{projectName:t}),e.jsx(Sl,{projectName:t})]})}function Sl({projectName:t}){const s=At(),[n,a]=o.useState(null),[i,r]=o.useState(null),[l,h]=o.useState(!0),[u,m]=o.useState(!1),[p,d]=o.useState(!1),[S,f]=o.useState(null),[C,N]=o.useState(null),[b,I]=o.useState("sessions"),[G,M]=o.useState("desc"),[z,x]=o.useState("sessions"),[A,_]=o.useState("desc"),[ee,oe]=o.useState("sessions"),[y,g]=o.useState("desc"),[K,$]=o.useState("sessions"),[q,Z]=o.useState("desc"),[le,te]=o.useState(1),[fe,ue]=o.useState([]),[H,xe]=o.useState([]),[k,B]=o.useState([]),[v,J]=o.useState(!1),[F,ce]=o.useState("30d");async function P(D){h(!0),f(null);try{const ie=await s.fetchQuery({...Ri({client:W,path:{name:t}}),staleTime:xs});if(D.current)return;if(a(ie),!ie.connected){r(null),ue([]),xe([]),B([]),h(!1);return}const X=F==="all"?void 0:F,[me,ot,cs,Re]=await Promise.all([s.fetchQuery({...Ii({client:W,path:{name:t},query:X?{window:X}:void 0}),staleTime:xs}).then(Ge=>Ge),s.fetchQuery({...Ti({client:W,path:{name:t},query:X?{window:X}:void 0}),staleTime:xs}).catch(()=>[]),s.fetchQuery({...Mi({client:W,path:{name:t},query:X?{window:X}:void 0}),staleTime:xs}).catch(()=>[]),s.fetchQuery({...Ei({client:W,path:{name:t},query:X?{window:X}:void 0}),staleTime:xs}).catch(()=>[])]);if(D.current)return;r(me),ue(ot),xe(cs),B(Re),h(!1)}catch(ie){if(D.current)return;f(ie instanceof Error?ie.message:"Failed to load GA4 data"),h(!1)}}o.useEffect(()=>{const D={current:!1};return P(D),()=>{D.current=!0}},[t,F,s]);async function U(){m(!0),f(null),N(null);try{const D=await Pa(t);N(`Synced ${D.rowCount.toLocaleString()} page rows, ${D.aiReferralCount.toLocaleString()} AI and ${D.socialReferralCount.toLocaleString()} social referral rows (${D.days} days)`),await s.invalidateQueries({predicate:ie=>{const X=ie.queryKey[0];return typeof X?._id=="string"&&X._id.startsWith("getApiV1ProjectsByNameGa")}}),await P({current:!1})}catch(D){f(D instanceof Error?D.message:"Sync failed")}finally{m(!1)}}async function we(){d(!0),f(null),N(null);try{await Oi(t),await s.invalidateQueries({predicate:D=>{const ie=D.queryKey[0];return typeof ie?._id=="string"&&ie._id.startsWith("getApiV1ProjectsByNameGa")}}),a({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),r(null),N("GA4 disconnected")}catch(D){f(D instanceof Error?D.message:"Disconnect failed")}finally{d(!1)}}function Me(D){b===D?M(ie=>ie==="desc"?"asc":"desc"):(I(D),M("desc"))}function $e(D){z===D?_(ie=>ie==="desc"?"asc":"desc"):(x(D),_("desc"))}function be(D){ee===D?g(ie=>ie==="desc"?"asc":"desc"):(oe(D),g("desc"))}function E(D){te(1),K===D?Z(ie=>ie==="desc"?"asc":"desc"):($(D),Z("desc"))}const re=o.useMemo(()=>i?.topPages?[...i.topPages].sort((D,ie)=>{const X=D[b],me=ie[b];return typeof X=="string"&&typeof me=="string"?G==="asc"?X.localeCompare(me):me.localeCompare(X):G==="asc"?X-me:me-X}):[],[i?.topPages,b,G]),je=o.useMemo(()=>i?.aiReferrals?[...i.aiReferrals].sort((D,ie)=>{const X=D[z],me=ie[z];return typeof X=="string"&&typeof me=="string"?A==="asc"?X.localeCompare(me):me.localeCompare(X):A==="asc"?X-me:me-X}):[],[i?.aiReferrals,z,A]),pe=o.useMemo(()=>i?.aiReferralLandingPages?[...i.aiReferralLandingPages].sort((D,ie)=>{const X=D[K],me=ie[K];return typeof X=="string"&&typeof me=="string"?q==="asc"?X.localeCompare(me):me.localeCompare(X):q==="asc"?X-me:me-X}):[],[i?.aiReferralLandingPages,K,q]),ye=Math.max(1,Math.ceil(pe.length/Ms)),O=Math.min(Math.max(1,le),ye),Se=(O-1)*Ms,Pe=o.useMemo(()=>pe.slice(Se,Se+Ms),[pe,Se]),Qe=o.useMemo(()=>i?.socialReferrals?[...i.socialReferrals].sort((D,ie)=>{const X=D[ee],me=ie[ee];return typeof X=="string"&&typeof me=="string"?y==="asc"?X.localeCompare(me):me.localeCompare(X):y==="asc"?X-me:me-X}):[],[i?.socialReferrals,ee,y]),{socialChartData:L,socialChartSources:Ne,socialOtherCount:Oe}=o.useMemo(()=>{const D=yl(k);return{socialChartData:D.data,socialChartSources:D.sources,socialOtherCount:D.otherCount}},[k]),{chartData:at,chartSources:Le,dateRange:it}=o.useMemo(()=>{const D=[...new Set(fe.map(Re=>Re.source))],ie=new Map;for(const Re of H)ie.set(Re.date,{_totalSessions:Re.sessions,_organicSessions:Re.organicSessions});const X=new Map;for(const Re of fe){const Ge=`${Re.date}::${Re.source}`,dt=X.get(Ge)??0;X.set(Ge,Math.max(dt,Re.sessions))}for(const[Re,Ge]of X){const[dt,ds]=Re.split("::");let ge=ie.get(dt);ge||(ge={_totalSessions:0,_organicSessions:0},ie.set(dt,ge)),ge[ds]=(ge[ds]??0)+Ge}const me=[...ie.entries()].sort(([Re],[Ge])=>Re.localeCompare(Ge)).map(([Re,Ge])=>({date:Re,...Ge})),ot=me.map(Re=>Re.date),cs=ot.length>0?{start:ot[0],end:ot[ot.length-1]}:null;return{chartData:me,chartSources:D,dateRange:cs}},[fe,H]);if(l&&!n)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return T()?e.jsx(V,{className:"p-5",children:e.jsx("div",{className:"text-sm text-secondary",children:"No Google Analytics 4 property connected yet."})}):e.jsx(kl,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:D=>{const ie=D.queryKey[0];return typeof ie?._id=="string"&&ie._id.startsWith("getApiV1ProjectsByNameGa")}}),await P({current:!1})))()}});const rt=i?.organicSharePctDisplay??"0%",_t=i?.channelBreakdown?.organic.sharePctDisplay??rt,$t=i?.channelBreakdown?.organic.sessions??i?.totalOrganicSessions??0,rs=i?.aiSessionsDeduped??0,De=i?.channelBreakdown?.ai.sessions??i?.aiSessionsBySession??0,os=i?.channelBreakdown?.ai.sharePctDisplay??i?.aiSharePctBySessionDisplay??"0%",Be=i?.paidAiSessionsBySession??0,We=i?.paidAiSharePctBySessionDisplay??"0%",Pt=i?new Set(i.aiReferrals.map(D=>D.source.toLowerCase())).size:0,yt=je[0]??null,ls=i?.totalDirectSessions??0,Lt=i?.directSharePctDisplay??"0%",ct=i?.channelBreakdown?.direct.sessions??ls,Fe=i?.channelBreakdown?.direct.sharePctDisplay??Lt,j=i?.channelBreakdown?.other.sessions??i?.otherSessions??0,se=i?.channelBreakdown?.other.sharePctDisplay??i?.otherSharePctDisplay??"0%",ne=i?.socialSessions??0,ze=i?.socialSharePctDisplay??"0%",_e=i?.channelBreakdown?.social.sessions??ne,qt=i?.channelBreakdown?.social.sharePctDisplay??ze,Gt=i?new Set(i.socialReferrals.map(D=>D.source.toLowerCase())).size:0,Ae=Qe[0]??null;return e.jsxs(e.Fragment,{children:[S&&e.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:S}),C&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-positive-900/20 border border-positive-800/60 text-sm text-positive",children:C}),e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Property ",e.jsx("span",{className:"text-neutral",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-muted",children:n.clientEmail})]})]})]}),!T()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(R,{variant:"outline",size:"sm",disabled:u,onClick:de(U),children:[e.jsx(gt,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(R,{variant:"ghost",size:"sm",className:"text-negative-400 hover:text-negative",disabled:p,onClick:de(we),children:[e.jsx(el,{className:"w-3.5 h-3.5 mr-1.5"}),"Disconnect"]})]})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Site Traffic",e.jsx(Te,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${i?.periodStart&&i?.periodEnd?` Data available: ${new Date(i.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(i.periodEnd+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}.`:""} Organic sessions are Google organic search sessions specifically.`})]})]}),e.jsx("div",{className:"flex gap-1",children:vl.map(D=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${F===D?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>ce(D),children:D==="all"?"All":D},D))})]}),i?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(an,{value:Es(i.totalSessions),label:"Total Sessions",subtitle:i.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(an,{value:Es(i.totalOrganicSessions),label:"Organic Sessions",subtitle:`${rt} of total`,tone:"positive"}),e.jsx(an,{value:Es(i.totalUsers),label:"Total Users",subtitle:i.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-default",children:[e.jsx("p",{className:"text-sm text-secondary mb-3",children:"No traffic data yet."}),!T()&&e.jsxs(R,{variant:"outline",size:"sm",disabled:u,onClick:de(U),children:[e.jsx(gt,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),"Sync from GA4"]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Te,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI includes paid and organic AI referrals; paid rows are labeled in the source table below. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed."})]})]}),it&&e.jsxs("p",{className:"text-xs text-muted",children:[new Date(it.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(it.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),at.length>0&&e.jsxs(V,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:Le.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Le.length===0&&e.jsx("p",{className:"text-xs text-muted mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Le.length===0&&e.jsx("p",{className:"text-xs text-muted",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Zt,{width:"100%",height:"100%",children:e.jsxs(es,{data:at,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(ts,{dataKey:"date",tick:st,tickLine:!1,axisLine:{stroke:jt},tickFormatter:yn}),e.jsx(ss,{tick:st,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ns,{...Bt,labelFormatter:Qs,formatter:(D,ie)=>{const X=typeof D=="number"?D.toLocaleString():String(D??0),me=String(ie??"");return me==="_totalSessions"?[X,"Total Sessions"]:me==="_organicSessions"?[X,"Organic Sessions"]:[X,me]}}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:Ve.text},formatter:D=>D==="_totalSessions"?"Total Sessions":D==="_organicSessions"?"Organic Sessions":D}),e.jsx(Ht,{type:"monotone",dataKey:"_totalSessions",stroke:Ve.textFaint,fill:Ve.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Le.map((D,ie)=>e.jsx(Ht,{type:"monotone",dataKey:D,stackId:"ai",stroke:St[ie%St.length],fill:St[ie%St.length],fillOpacity:.4,strokeWidth:1.5},D))]})})})]}),e.jsxs(V,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(nt,{label:"Organic",value:_t,hint:`${$t.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions from Google organic search (sessionDefaultChannelGrouping = 'Organic Search'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(nt,{label:"Social",value:qt,hint:`${_e.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions from social platforms (sessionDefaultChannelGrouping = 'Organic Social' or 'Paid Social'), after known AI referrers are removed for a disjoint channel breakdown."}),e.jsx(nt,{label:"Direct",value:Fe,hint:`${ct.toLocaleString()} sessions`,tone:"neutral",tooltip:"Sessions with no source — bookmarks, typed URLs, untagged email, in-app browsers, and AI-driven traffic whose referrer header was stripped. Known AI referrers are removed if GA4 classified them as Direct."}),e.jsx(nt,{label:"Known AI referrers (lower bound)",value:os,hint:Be>0?`${De.toLocaleString()} sessions · ${Be.toLocaleString()} paid`:`${De.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). Paid AI is inferred from paid/cpc/sponsored UTM values or GA4 paid channel groups. Untagged ad clicks with no referrer still fall under Direct because GA4 has no paid evidence for them."}),e.jsx(nt,{label:"Other channels",value:se,hint:`${j.toLocaleString()} sessions`,tone:"neutral",tooltip:"Remaining GA4 session default channel groups after Known AI, Organic Search, Organic/Paid Social, and Direct are accounted for. This is a residual bucket, not a single source. It can include Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, Mobile Push Notifications, Paid Other, and unclassified traffic."})]}),yt&&e.jsxs("div",{className:"mt-4 rounded-lg border border-positive-800/40 bg-positive-500/6 px-4 py-3 text-sm text-positive-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:yt.source})," via ",yt.medium,", accounting for ",yt.sessions.toLocaleString()," sessions.",Be>0&&e.jsxs("span",{children:[" Paid AI: ",Be.toLocaleString()," sessions (",We,")."]})]})]}),e.jsxs(V,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.aiReferrals.length>0?`${Pt} unique sources, ${i.aiReferrals.length} rows`:"No source rows"})]}),i.aiReferrals.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Ue,{label:"Source",sortKey:"source",current:z,dir:A,onSort:$e,align:"left"}),e.jsx(Ue,{label:"Medium",sortKey:"medium",current:z,dir:A,onSort:$e,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Class"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ue,{label:"Sessions",sortKey:"sessions",current:z,dir:A,onSort:$e,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ue,{label:"Users",sortKey:"users",current:z,dir:A,onSort:$e,align:"right"})]})}),e.jsx("tbody",{children:je.map(D=>e.jsx(Al,{referral:D,totalSessions:rs},`${D.source}:${D.medium}:${D.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"AI engines that preserve a referrer (Perplexity, copy/paste from ChatGPT, etc.) will appear here. Most AI traffic strips the referrer — see the Direct cell above for the upper bound."})]})]}),e.jsxs(V,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Detail"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-muted",children:pe.length>Ms?`${Se+1}–${Se+Pe.length} of ${pe.length} rows`:pe.length>0?`${pe.length} rows`:"No landing-page rows"})]}),pe.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Ue,{label:"Landing Page",sortKey:"landingPage",current:K,dir:q,onSort:E,align:"left"}),e.jsx(Ue,{label:"Source",sortKey:"source",current:K,dir:q,onSort:E,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ue,{label:"Sessions",sortKey:"sessions",current:K,dir:q,onSort:E,align:"right"}),e.jsx(Ue,{label:"Users",sortKey:"users",current:K,dir:q,onSort:E,align:"right"})]})}),e.jsx("tbody",{children:Pe.map(D=>e.jsx($l,{row:D},`${D.landingPage}:${D.source}:${D.medium}:${D.sourceDimension}`))})]})}),ye>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>te(O-1),disabled:O<=1,className:"text-xs text-secondary hover:text-strong disabled:opacity-40 disabled:hover:text-secondary px-3 py-1 rounded-full border border-base hover:border-strong disabled:hover:border-base transition-colors",children:"Previous"}),e.jsxs("span",{className:"text-xs text-muted tabular-nums",children:["Page ",O," of ",ye]}),e.jsx("button",{type:"button",onClick:()=>te(O+1),disabled:O>=ye,className:"text-xs text-secondary hover:text-strong disabled:opacity-40 disabled:hover:text-secondary px-3 py-1 rounded-full border border-base hover:border-strong disabled:hover:border-base transition-colors",children:"Next"})]})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Te,{text:"Tracks sessions classified as social traffic by GA4's default channel grouping (Organic Social and Paid Social). Google maintains the source-to-channel mapping."})]})]}),L.length>0&&e.jsxs(V,{className:"surface-card p-5 mb-4",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social sessions over time"})]}),Oe>0&&e.jsxs("p",{className:"text-xs text-muted",children:["Showing top ",Ne.length-1," sources · ",Oe," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Zt,{width:"100%",height:"100%",children:e.jsxs(es,{data:L,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(ts,{dataKey:"date",tick:st,tickLine:!1,axisLine:{stroke:jt},tickFormatter:yn}),e.jsx(ss,{tick:st,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ns,{...Bt,labelFormatter:Qs,formatter:(D,ie)=>{const X=typeof D=="number"?D.toLocaleString():String(D??0),me=String(ie??"");if(me===Yt)return[X,"Total Social"];if(me===as){const ot=`Other (${Oe} source${Oe===1?"":"s"})`;return[X,ot]}return[X,Jt(me)]}}),e.jsx(Ht,{type:"monotone",dataKey:Yt,stroke:Xa,fill:Ve.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ne.map((D,ie)=>{const me=D===as?wn:St[ie%St.length];return e.jsx(Ht,{type:"monotone",dataKey:D,stackId:"social",stroke:me,fill:me,fillOpacity:.4,strokeWidth:1.5},D)})]})})}),e.jsx(Ll,{sources:Ne,otherCount:Oe})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(V,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Summary"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Social media visits"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(nt,{label:"Social Sessions",value:Es(ne),hint:`${ne.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(nt,{label:"Share of Traffic",value:ze,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(nt,{label:"Platforms",value:String(Gt),hint:`${i.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),Ae&&e.jsxs("div",{className:"mt-4 rounded-lg border border-info-800/40 bg-info-500/6 px-4 py-3 text-sm text-info-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-info-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${Ae.source} via ${Ae.medium}`,children:Ja(Jt(Ae.source),64)}),e.jsxs("p",{className:"text-xs text-info-200/70 mt-0.5 truncate",title:Ae.medium,children:["via ",Jt(Ae.medium)," · ",Ae.sessions.toLocaleString()," sessions"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(nt,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(nt,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(nt,{label:"Platforms",value:"0",hint:"known platforms",tone:"neutral",tooltip:"Number of distinct social media platforms detected."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3 text-sm text-secondary",children:[e.jsx("p",{className:"mb-1.5 text-neutral",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-muted",children:"Sessions classified as Organic Social or Paid Social by GA4 will appear here. Google maintains the source-to-channel mapping, which includes Facebook, Instagram, X/Twitter, LinkedIn, Reddit, Pinterest, Snapchat, and other platforms."})]})]})]}),e.jsxs(V,{className:"surface-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Breakdown"}),e.jsx("h3",{className:"text-sm font-semibold text-heading",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-muted",children:i.socialReferrals.length>0?Qe.length>hs&&!v?`Top ${hs} of ${Qe.length}`:`${Qe.length} rows`:"No source rows"})]}),i.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm table-fixed",children:[e.jsxs("colgroup",{children:[e.jsx("col",{className:"w-[32%]"}),e.jsx("col",{className:"w-[22%]"}),e.jsx("col",{className:"w-[12%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[11%]"}),e.jsx("col",{className:"w-[12%]"})]}),e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Ue,{label:"Source",sortKey:"source",current:ee,dir:y,onSort:be,align:"left"}),e.jsx(Ue,{label:"Medium",sortKey:"medium",current:ee,dir:y,onSort:be,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Ue,{label:"Sessions",sortKey:"sessions",current:ee,dir:y,onSort:be,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ue,{label:"Users",sortKey:"users",current:ee,dir:y,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:(v?Qe:Qe.slice(0,hs)).map(D=>e.jsx(Pl,{referral:D,totalSessions:ne},`${D.source}:${D.medium}:${D.channelGroup}`))})]})}),Qe.length>hs&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>J(D=>!D),className:"text-xs text-secondary hover:text-strong px-3 py-1 rounded-full border border-base hover:border-strong transition-colors",children:v?`Show top ${hs}`:`Show all ${Qe.length} sources`})})]}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-secondary mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-muted max-w-sm",children:"When visitors arrive from Facebook, X/Twitter, LinkedIn, or other social platforms, their sessions will be broken down here by source and medium."})]})]})]})]})]}),i&&i.topPages.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"page-section-divider"}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-primary flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Te,{text:"Landing pages ranked by session volume. Click column headers to sort. Organic % shows the share of sessions coming from Google organic search."})]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-[10px] uppercase tracking-wider text-muted",children:[e.jsx(Ue,{label:"Landing Page",sortKey:"landingPage",current:b,dir:G,onSort:Me,align:"left"}),e.jsx(Ue,{label:"Sessions",sortKey:"sessions",current:b,dir:G,onSort:Me,align:"right"}),e.jsx(Ue,{label:"Organic",sortKey:"organicSessions",current:b,dir:G,onSort:Me,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Ue,{label:"Users",sortKey:"users",current:b,dir:G,onSort:Me,align:"right"})]})}),e.jsx("tbody",{children:re.map(D=>e.jsx(Cl,{page:D},D.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-muted",children:[e.jsx("span",{children:i?.lastSyncedAt?`Last synced ${Za(i.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:i?`${i.topPages.length} pages · ${i.aiReferrals.length} AI rows · ${i.socialReferrals.length} social rows`:""})]})]})}function kl({projectName:t,onConnected:s}){const[n,a]=o.useState(""),[i,r]=o.useState(null),[l,h]=o.useState(null),[u,m]=o.useState(!1),[p,d]=o.useState(null),S=o.useRef(null),f=o.useCallback(N=>{const b=N.target.files?.[0];if(!b)return;d(null),r(b.name);const I=new FileReader;I.onload=()=>{const G=I.result;try{const M=JSON.parse(G);if(!M.client_email||!M.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)."),h(null);return}h(G)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),h(null)}},I.onerror=()=>{d("Failed to read file."),h(null)},I.readAsText(b)},[]);async function C(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!l){d("Please upload a service account key file.");return}m(!0);try{await Bi(t,{propertyId:n.trim(),keyJson:l});try{await Pa(t)}catch{}s()}catch(N){d(N instanceof Error?N.message:"Failed to connect GA4")}finally{m(!1)}}return e.jsxs(V,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-primary mb-1",children:"Connect Google Analytics 4"}),e.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."}),p&&e.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:p}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-secondary mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:N=>a(N.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"}),e.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)."})]}),e.jsxs("div",{className:"mb-5",children:[e.jsx("label",{className:"block text-xs font-medium text-secondary mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:S,type:"file",accept:".json,application/json",onChange:f,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>S.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:[e.jsx(sl,{className:"w-4 h-4 shrink-0"}),i?e.jsx("span",{className:"text-strong truncate",children:i}):e.jsx("span",{children:"Upload .json key file"})]}),e.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 ",e.jsx("span",{className:"text-secondary",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(R,{variant:"default",size:"sm",disabled:u||!n.trim()||!l,onClick:de(C),children:u?"Connecting & syncing…":"Connect GA4"})]})}function Ue({label:t,sortKey:s,current:n,dir:a,onSort:i,align:r}){const l=n===s;return e.jsx("th",{className:`py-1 ${r==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-neutral transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-mono-400 rounded",onClick:()=>i(s),"aria-label":`Sort by ${t}${l?` (currently ${a==="asc"?"ascending":"descending"})`:""}`,children:[t,l&&e.jsx("span",{className:"ml-0.5",children:a==="asc"?"↑":"↓"})]})})}const ei={positive:"text-positive-400",caution:"text-caution-400",negative:"text-negative-400",neutral:"text-primary"};function an({value:t,label:s,subtitle:n,tone:a}){return e.jsxs("div",{className:"rounded-lg bg-surface border border-default px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${ei[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function nt({value:t,label:s,hint:n,tone:a,tooltip:i}){return e.jsxs("div",{className:"rounded-lg border border-default bg-bg/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted mb-1 flex items-center gap-1",children:[s,i&&e.jsx(Te,{text:i})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${ei[a]}`,children:t}),e.jsx("p",{className:"text-xs text-muted mt-1",children:n})]})}function Cl({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[s,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}const ti={session:"Session",first_user:"First Visit",manual_utm:"UTM"},si={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)"};function Al({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=ti[t.sourceDimension]??t.sourceDimension,i=si[t.sourceDimension]??"",r=t.trafficClass==="paid"?"Paid":"Organic",l=t.trafficClass==="paid"?"Paid AI traffic inferred from paid/cpc/sponsored UTM values or a GA4 paid channel group":"AI traffic without a paid attribution signal";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-muted max-w-[180px] truncate",title:t.medium,children:t.medium}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:`inline-block text-[10px] px-1.5 py-0.5 rounded-full border ${t.trafficClass==="paid"?"border-caution-700 text-caution-300":"border-strong text-secondary"}`,title:l,children:r})}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:i,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function $l({row:t}){const s=ti[t.sourceDimension]??t.sourceDimension,n=si[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 text-neutral max-w-[360px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-strong max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-positive-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Pl({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",a=t.channelGroup==="Paid Social"?"Paid":"Organic",i=Jt(t.source),r=Jt(t.medium);return e.jsxs("tr",{className:"border-t border-subtle",children:[e.jsx("td",{className:"py-1.5 pr-3 text-strong truncate",title:t.source,children:i}),e.jsx("td",{className:"py-1.5 pr-3 text-muted truncate",title:t.medium,children:r}),e.jsx("td",{className:"py-1.5 pr-3",children:e.jsx("span",{className:"inline-block text-[10px] px-1.5 py-0.5 rounded-full border border-strong text-secondary",title:`GA4 channel group: ${t.channelGroup}`,children:a})}),e.jsx("td",{className:"py-1.5 text-right text-info-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-secondary tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-strong tabular-nums",children:t.users.toLocaleString()})]})}function Ll({sources:t,otherCount:s}){const n=[{key:Yt,color:Xa,label:"Total",tooltip:"All social sessions across every source."}];for(let a=0;a<t.length;a++){const i=t[a];if(i===as)n.push({key:as,color:wn,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const r=Jt(i);n.push({key:i,color:St[a%St.length]??wn,label:Ja(r,32),tooltip:r})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-secondary",children:n.map(a=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:a.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:a.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:a.label})]},a.key))})}function Dl(t){const s=t.details;if(t.code!=="FORBIDDEN"||!s||s.reason!=="gsc-api-disabled")return null;const n=typeof s.projectNumber=="string"?s.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 s.enableUrl=="string"?s.enableUrl:void 0,indexingApiUrl:typeof s.indexingApiUrl=="string"?s.indexingApiUrl:void 0,projectNumber:n}}const Rl=["7d","30d","90d","all"],Os=500,Nt=25;function Il({projectName:t,refreshNonce:s}){const n=At(),[a,i]=o.useState(!1),[r,l]=o.useState([]),[h,u]=o.useState([]),[m,p]=o.useState([]),[d,S]=o.useState(null),[f,C]=o.useState([]),[N,b]=o.useState([]),[I,G]=o.useState(null),[M,z]=o.useState(""),[x,A]=o.useState(""),[_,ee]=o.useState("30"),[oe,y]=o.useState(!1),[g,K]=o.useState("30d"),[$,q]=o.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[Z,le]=o.useState(0),[te,fe]=o.useState(!1),[ue,H]=o.useState(0),[xe,k]=o.useState(!1),[B,v]=o.useState(""),[J,F]=o.useState(!0),[ce,P]=o.useState(!1),[U,we]=o.useState(!1),[Me,$e]=o.useState(!1),[be,E]=o.useState(!1),[re,je]=o.useState(!1),[pe,ye]=o.useState(!1),[O,Se]=o.useState(null),[Pe,Qe]=o.useState(!1),[L,Ne]=o.useState(!1),[Oe,at]=o.useState(null),[Le,it]=o.useState(""),[rt,_t]=o.useState(!1),[$t,rs]=o.useState(!1),[De,os]=o.useState("indexed"),[Be,We]=o.useState(null),Pt=!!($.query.trim()||$.page.trim()||Be),yt=Be!==null,ls=o.useMemo(()=>{if(!Be)return m;const{key:c,dir:w}=Be;return[...m].sort((Q,he)=>{const Ce=c===Mt.CTR?Number.isFinite(Q.ctr)?Q.ctr:0:Q[c],Ye=c===Mt.CTR?Number.isFinite(he.ctr)?he.ctr:0:he[c];return w==="asc"?Ce-Ye:Ye-Ce})},[m,Be]),[Lt,ct]=o.useState([]),[Fe,j]=o.useState(null),[se,ne]=o.useState(1);o.useEffect(()=>{ne(1)},[O,De,Fe]);const ze=o.useMemo(()=>Fe?(O?.reasonGroups??[]).find(c=>c.reason===Fe):void 0,[O,Fe]),_e=o.useMemo(()=>O?De==="indexed"?O.indexed:De==="deindexed"?O.deindexed:De==="notIndexed"?Fe?ze?.urls??[]:(O.reasonGroups??[]).length===0?O.notIndexed:[]:[]:[],[O,De,Fe,ze]),qt=Math.max(1,Math.ceil(_e.length/Nt)),Gt=Math.min(Math.max(1,se),qt),Ae=(Gt-1)*Nt,D=_e.length>Nt,ie=_e.length===0?0:Ae+1,X=Math.min(Ae+Nt,_e.length),me=o.useMemo(()=>O?.indexed.slice(Ae,Ae+Nt)??[],[O,Ae]),ot=o.useMemo(()=>O?.notIndexed.slice(Ae,Ae+Nt)??[],[O,Ae]),cs=o.useMemo(()=>O?.deindexed.slice(Ae,Ae+Nt)??[],[O,Ae]),Re=o.useMemo(()=>(ze?.urls??[]).slice(Ae,Ae+Nt),[ze,Ae]),[Ge,dt]=o.useState(!1),[ds,ge]=o.useState(null),[ut,Cs]=o.useState(null),[Bn,mt]=o.useState(null);function ui(c,w){const Q=ea(c),he=Dl(Q);he?(Cs(he),ge(null)):(Cs(null),ge(Q.message||w))}const Ie=r.find(c=>c.connectionType==="gsc"),mi=m.length>0||f.length>0||N.length>0,Js=Fi(),us=_i(),Xs=qi();async function Fn(c,w={}){if(!c){u([]),z("");return}we(!0);try{const{sites:Q}=await n.fetchQuery({...Xi({client:W,path:{name:t}}),staleTime:w.force?0:qe});u(Q),z(c.propertyId??Q[0]?.siteUrl??""),Cs(null),w.notify&&Y({title:"GSC properties refreshed",detail:`${Q.length} propert${Q.length===1?"y":"ies"} available for this connection.`,tone:Q.length>0?"positive":"caution",dedupeKey:`gsc:properties:${t}`,dedupeMode:"replace"})}catch(Q){if(u([]),ui(Q,"Failed to load Search Console properties"),w.notify){const he=ea(Q);Y({title:"GSC property refresh failed",detail:he.message||"Failed to load Search Console properties",tone:"negative",dedupeKey:`gsc:properties:${t}`,dedupeMode:"replace"})}}finally{we(!1)}}async function Ut(c){E(!0);const w=c??Z;try{const Q=parseInt($.limit,10)||20,he=Pt?Os:Q+1,Ce=Pt?0:w,Ye={limit:String(he)};$.startDate&&(Ye.startDate=$.startDate),$.endDate&&(Ye.endDate=$.endDate),$.query&&(Ye.query=$.query),$.page&&(Ye.page=$.page),Ce>0&&(Ye.offset=String(Ce)),g&&g!=="all"&&!$.startDate&&(Ye.window=g);const Je=await n.fetchQuery({...Ui({client:W,path:{name:t},query:Ye}),staleTime:qe});Pt?(fe(!1),p(Je),H(Je.length),k(!0)):(fe(Je.length>Q),p(Je.slice(0,Q)),H(0),k(!1))}catch(Q){p([]),fe(!1),H(0),ge(Q instanceof Error?Q.message:"Failed to load GSC performance data")}finally{E(!1)}}async function Zs(){try{const c={};$.startDate&&(c.startDate=$.startDate),$.endDate&&(c.endDate=$.endDate),g&&g!=="all"&&!$.startDate&&(c.window=g);const w=await n.fetchQuery({...Qi({client:W,path:{name:t},query:c}),staleTime:qe});S(w)}catch{S(null)}}async function As(c={}){je(!0);try{const w=B.trim()||void 0,Q={limit:"20"};w&&(Q.url=w);const[he,Ce]=await Promise.all([n.fetchQuery({...Yi({client:W,path:{name:t},query:Q}),staleTime:c.force?0:qe}),n.fetchQuery({...Ji({client:W,path:{name:t}}),staleTime:c.force?0:qe})]);C(he),b(Ce),c.notify&&Y({title:"Inspection history refreshed",detail:`${he.length} recent inspection${he.length===1?"":"s"} loaded${Ce.length>0?`, ${Ce.length} deindexed URL${Ce.length===1?"":"s"} flagged`:""}.`,tone:"positive",dedupeKey:`gsc:inspection-history:${t}`,dedupeMode:"replace"})}catch(w){const Q=w instanceof Error?w.message:"Failed to load GSC inspection history";C([]),b([]),ge(Q),c.notify&&Y({title:"Inspection history refresh failed",detail:Q,tone:"negative",dedupeKey:`gsc:inspection-history:${t}`,dedupeMode:"replace"})}finally{je(!1)}}async function _n(c={}){Qe(!0);try{const[w,Q]=await Promise.all([n.fetchQuery({...Da({client:W,path:{name:t}}),staleTime:c.force?0:qe}),n.fetchQuery({...Vi({client:W,path:{name:t}}),staleTime:c.force?0:qe}).catch(()=>[])]);Se(w),ct(Q),c.notify&&Y({title:"GSC coverage refreshed",detail:w.summary.total>0?`${w.summary.indexed}/${w.summary.total} URLs indexed. Use Inspect sitemap to re-read new sitemap URLs.`:"No coverage rows yet. Inspect the sitemap to populate this view.",tone:w.summary.total>0?"positive":"caution",dedupeKey:`gsc:coverage:${t}`,dedupeMode:"replace"})}catch(w){const Q=w instanceof Error?w.message:"Failed to load coverage data";Se(null),ct([]),ge(Q),c.notify&&Y({title:"GSC coverage refresh failed",detail:Q,tone:"negative",dedupeKey:`gsc:coverage:${t}`,dedupeMode:"replace"})}finally{Qe(!1)}}async function qn(c){dt(!0),ge(null);try{const w=await Vn(t,{urls:c}),{succeeded:Q,failed:he,total:Ce}=w.summary;Y({title:"Indexing requested",detail:he===0?`${Q} URL${Q!==1?"s":""} submitted for indexing.`:`${Q}/${Ce} submitted successfully, ${he} failed.`,tone:he===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(w){const Q=w instanceof Error?w.message:"Failed to request indexing";ge(Q),Y({title:"Indexing request failed",detail:Q,tone:"negative",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}finally{dt(!1)}}async function xi(){dt(!0),ge(null);try{const c=await Vn(t,{urls:[],allUnindexed:!0}),{succeeded:w,failed:Q,total:he}=c.summary;Y({title:"Indexing requested",detail:Q===0?`${w} unindexed URL${w!==1?"s":""} submitted for indexing.`:`${w}/${he} submitted successfully, ${Q} failed.`,tone:Q===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){const w=c instanceof Error?c.message:"Failed to request indexing";ge(w),Y({title:"Indexing request failed",detail:w,tone:"negative",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}finally{dt(!1)}}async function $s(){if(Le.trim()){_t(!0),ge(null);try{await Hi(t,"gsc",Le.trim()),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(c=>c.map(w=>w.connectionType==="gsc"?{...w,sitemapUrl:Le.trim()}:w)),Y({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),it("")}catch(c){ge(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{_t(!1)}}}async function Gn(){ge(null);try{const c=await us.mutateAsync({projectName:t,projectLabel:t});at(c.sitemaps),l(w=>w.map(Q=>Q.connectionType==="gsc"?{...Q,sitemapUrl:c.primarySitemapUrl}:Q))}catch{}}async function hi(){Ne(!0),ge(null);try{const c=await er(t);n.setQueryData(tr({client:W,path:{name:t}}),c),at(c.sitemaps),c.sitemaps.length===0?(mt("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first."),Y({title:"No GSC sitemaps found",detail:"Submit a sitemap in Google Search Console, then browse again.",tone:"caution",dedupeKey:`gsc:sitemaps:${t}`,dedupeMode:"replace"})):Y({title:"GSC sitemaps loaded",detail:`${c.sitemaps.length} sitemap${c.sitemaps.length===1?"":"s"} returned from Search Console.`,tone:"positive",dedupeKey:`gsc:sitemaps:${t}`,dedupeMode:"replace"})}catch(c){const w=c instanceof Error?c.message:"Failed to list sitemaps";ge(w),Y({title:"Could not load GSC sitemaps",detail:w,tone:"negative",dedupeKey:`gsc:sitemaps:${t}`,dedupeMode:"replace"})}finally{Ne(!1)}}async function Un(){F(!0),ge(null);try{const[c,w]=await Promise.all([La().catch(()=>null),n.fetchQuery({...$n({client:W,path:{name:t}}),staleTime:qe}).catch(()=>[])]);i(!!c?.google?.configured),l(w);const Q=w.find(he=>he.connectionType==="gsc");await Promise.all([Fn(Q),Ut(),Zs(),As(),_n()])}finally{F(!1)}}o.useEffect(()=>{Un()},[t,s]),o.useEffect(()=>{le(0),Ut(0),Zs()},[g]);const Qn=o.useRef(!1);o.useEffect(()=>{if(!Qn.current){Qn.current=!0;return}le(0),Ut(0)},[yt]);async function pi(){if(!a){ge("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}P(!0),ge(null),mt(null);try{const{authUrl:c}=await Ki(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){ge("Unexpected OAuth redirect URL. Please try again.");return}const w=window.open(c,"_blank","width=600,height=700");if(!w){window.location.assign(c);return}mt("Finish the Google consent flow in the popup, then close it to refresh this project.");const Q=window.setInterval(()=>{w.closed&&(window.clearInterval(Q),mt(null),n.invalidateQueries({predicate:he=>{const Ce=he.queryKey[0];return typeof Ce?._id=="string"&&Ce._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),Un())},1e3)}catch(c){ge(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{P(!1)}}async function gi(){ge(null),mt(null);try{await zi(t,"gsc"),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(c=>c.filter(w=>w.connectionType!=="gsc")),u([]),z("")}catch(c){ge(c instanceof Error?c.message:"Failed to disconnect")}}async function fi(){if(M){$e(!0),ge(null);try{await Zi(t,"gsc",M),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),l(c=>c.map(w=>w.connectionType==="gsc"?{...w,propertyId:M}:w)),Y({title:"GSC property updated",detail:`${t} is now linked to ${M}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){ge(c instanceof Error?c.message:"Failed to save GSC property")}finally{$e(!1)}}}async function bi(){ge(null),mt(null);try{await Js.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(_,10)||void 0,full:oe||void 0}}),await n.invalidateQueries({predicate:c=>{const w=c.queryKey[0];return typeof w?._id=="string"&&w._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function zn(){if(x.trim()){ye(!0),ge(null),mt(null);try{const c=await Wi(t,x.trim());await n.invalidateQueries({predicate:w=>{const Q=w.queryKey[0];return typeof Q?._id=="string"&&Q._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),G(c),A(""),await As()}catch(c){ge(c instanceof Error?c.message:"Failed to inspect URL")}finally{ye(!1)}}}return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search Console"}),e.jsx("h2",{children:"Google Search Console"})]})}),ut&&e.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:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-caution-100",children:ut.title}),e.jsx("p",{className:"mt-0.5 text-caution-200/90",children:ut.message}),(It(ut.enableUrl)||It(ut.indexingApiUrl))&&e.jsxs("div",{className:"mt-2 flex flex-wrap gap-3",children:[It(ut.enableUrl)&&e.jsx("a",{href:It(ut.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 ↗"}),It(ut.indexingApiUrl)&&e.jsx("a",{href:It(ut.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 ↗"})]})]}),e.jsx("button",{type:"button",className:"text-caution-400 hover:text-caution-200",onClick:()=>Cs(null),children:"×"})]})}),ds&&e.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:[ds,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>ge(null),children:"×"})]}),Bn&&e.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:[Bn,e.jsx("button",{type:"button",className:"ml-2 text-positive-400 hover:text-positive-200",onClick:()=>mt(null),children:"×"})]}),J?e.jsx("p",{className:"text-sm text-muted",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[Ie?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-neutral",children:"Authorized"})]}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsx("code",{className:"text-secondary",children:Ie.domain}),e.jsx("span",{className:"text-mono-700",children:"·"}),e.jsxs("span",{children:["Last updated ",et(Ie.updatedAt)]}),!T()&&e.jsx("button",{type:"button",className:"ml-auto text-muted transition-colors hover:text-negative-400",onClick:de(gi),children:"Disconnect"})]}):e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ae,{tone:a?"caution":"negative",children:a?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-default bg-surface px-4 py-5",children:[e.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."}),!T()&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[a?e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:ce,onClick:de(pi),children:ce?"Opening…":"Connect Google Search Console"}):e.jsx(R,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(ft,{to:"/settings",children:"Open Settings"})}),!a&&e.jsx("p",{className:"text-xs text-muted",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),Ie&&!Ie.sitemapUrl&&e.jsx("div",{className:"rounded-lg border border-caution-800/40 bg-caution-950/20 px-4 py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 text-caution-400",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",className:"h-5 w-5","aria-hidden":"true",children:e.jsx("path",{fillRule:"evenodd",d:"M8.485 2.495c.673-1.167 2.357-1.167 3.03 0l6.28 10.875c.673 1.167-.17 2.625-1.516 2.625H3.72c-1.347 0-2.189-1.458-1.515-2.625L8.485 2.495zM10 6a.75.75 0 01.75.75v3.5a.75.75 0 01-1.5 0v-3.5A.75.75 0 0110 6zm0 9a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-caution-300",children:"Set your sitemap URL"}),e.jsx("p",{className:"mt-1 text-xs text-caution-400/70",children:"Canonry uses your sitemap to discover URLs for index coverage inspection. Auto-discover from GSC or enter it manually."}),!T()&&e.jsxs("div",{className:"mt-2 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx(R,{type:"button",size:"sm",disabled:us.isPending||!Ie.propertyId,onClick:de(Gn),children:us.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-caution-400/60",children:"or enter manually:"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-caution-800/40 bg-transparent px-2 py-1.5 text-sm text-strong placeholder-mono-500 focus:border-caution-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Le,onChange:c=>it(c.target.value),onKeyDown:c=>c.key==="Enter"&&void $s()}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:rt||!Le.trim(),onClick:de($s),children:rt?"Saving…":"Save sitemap URL"})]})]})]})]})}),(Ie||mi)&&e.jsxs(e.Fragment,{children:[e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Coverage"}),e.jsx("h3",{children:"Index coverage"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[!T()&&O&&O.notIndexed.length>0&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Ge,onClick:()=>{xi()},children:Ge?"Requesting…":`Request indexing (${O.notIndexed.length})`}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:Pe,onClick:()=>{_n({force:!0,notify:!0})},children:[e.jsx(gt,{className:`h-3.5 w-3.5 ${Pe?"animate-spin":""}`,"aria-hidden":"true"}),Pe?"Loading…":"Refresh coverage"]})]})]}),O&&O.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=O.summary.indexed+O.summary.notIndexed,w=c>0?O.summary.indexed/c:0,Q=c>0?O.summary.notIndexed/c:0,he=54,Ce=2*Math.PI*he,Ye=Ce*(1-w),Je=Ce*Q,Qt=Ce*w;return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative h-48 w-48",children:[e.jsxs("svg",{viewBox:"0 0 128 128",className:"h-full w-full","aria-hidden":"true",children:[e.jsx("circle",{cx:"64",cy:"64",r:he,fill:"none",stroke:Ve.trackSubtle,strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:he,fill:"none",stroke:bt.positiveDeep,strokeWidth:"14",strokeDasharray:Ce,strokeDashoffset:Ye,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),O.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:he,fill:"none",stroke:Ve.textFaint,strokeWidth:"14",strokeDasharray:`${Je} ${Ce-Je}`,strokeDashoffset:-Qt,transform:"rotate(-90 64 64)",style:{transition:"stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-bold tabular-nums text-primary",children:[(w*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-muted mt-0.5",children:"Indexed"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center justify-center gap-8",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-positive-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:O.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-mono-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:O.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:["Not indexed",(O.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-faint",children:["· ",(O.reasonGroups??[]).length," ",(O.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),O.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-mono-800"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full bg-negative-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-primary",children:O.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted",children:"Deindexed"})]})]})]})]})]})})()}),Lt.length>=2?e.jsxs("div",{className:"mt-8 border-t border-subtle pt-5",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h4",{children:"Coverage over time"})]}),e.jsxs("span",{className:"text-xs text-muted",children:[Lt.length," snapshots"]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Indexed"}),e.jsx("th",{className:"text-right",children:"Not indexed"}),e.jsx("th",{className:"text-right",children:"Coverage"})]})}),e.jsx("tbody",{children:Lt.slice(-8).reverse().map(c=>{const w=c.indexed+c.notIndexed,Q=w>0?Math.round(c.indexed/w*100):0;return e.jsxs("tr",{children:[e.jsx("td",{className:"tabular-nums text-secondary",children:new Date(`${c.date}T00:00:00`).toLocaleDateString()}),e.jsx("td",{className:"text-right tabular-nums text-positive-400",children:c.indexed.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-muted",children:c.notIndexed.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-strong",children:[Q,"%"]})]},c.date)})})]})})]}):null,e.jsx("div",{className:"mt-3 flex gap-1",children:["indexed","notIndexed","deindexed"].map(c=>{const w=c==="indexed"?O.indexed.length:c==="notIndexed"?O.notIndexed.length:O.deindexed.length,Q=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button","aria-pressed":De===c,className:`min-h-11 rounded-full px-3 py-1 text-xs font-medium transition-colors ${De===c?"bg-mono-700 text-heading":"text-secondary hover:bg-mono-800 hover:text-strong"}`,onClick:()=>{os(c),j(null)},children:[Q," (",w,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[De==="indexed"&&O.indexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),e.jsx("th",{className:"text-left",children:"Mobile"})]})}),e.jsx("tbody",{children:me.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-secondary",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),De==="notIndexed"&&!Fe&&(O.reasonGroups??[]).length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Reason"}),e.jsx("th",{className:"text-right",children:"Pages"})]})}),e.jsx("tbody",{children:(O.reasonGroups??[]).map(c=>e.jsxs("tr",{className:"cursor-pointer hover:bg-surface-inset-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400",onClick:()=>j(c.reason),onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),j(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-strong",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.count})]},c.reason))})]}),De==="notIndexed"&&!Fe&&(O.reasonGroups??[]).length===0&&O.notIndexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing State"}),e.jsx("th",{className:"text-left",children:"Coverage"})]})}),e.jsx("tbody",{children:ot.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.coverageState??"Unknown"})]},c.id))})]}),De==="notIndexed"&&Fe&&(()=>{const c=(O.reasonGroups??[]).find(w=>w.reason===Fe);return c?e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2 mb-3",children:e.jsxs("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>j(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:c.reason}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[c.count," affected page",c.count!==1?"s":""]})]}),!T()&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:Ge,onClick:()=>{qn(c.urls.map(w=>w.url))},children:Ge?"Requesting…":`Request indexing (${c.count})`})]}),e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Last Crawl"}),!T()&&e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:Re.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:w.url}),e.jsx("td",{className:"text-secondary",children:w.crawlTime?w.crawlTime.split("T")[0]:"—"}),!T()&&e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-strong transition-colors",disabled:Ge,onClick:()=>{qn([w.url])},title:"Request indexing",children:"Index"})})]},w.id))})]})]}):null})(),De==="deindexed"&&O.deindexed.length>0&&e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Detected"})]})}),e.jsx("tbody",{children:cs.map((c,w)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.previousState}),e.jsx("td",{className:"text-secondary",children:c.currentState}),e.jsx("td",{className:"text-secondary",children:c.transitionDate.split("T")[0]})]},`${c.url}-${w}`))})]}),(De==="indexed"&&O.indexed.length===0||De==="notIndexed"&&!Fe&&O.notIndexed.length===0||De==="deindexed"&&O.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-muted",children:"No URLs in this category."}),D&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-secondary",children:[e.jsxs("p",{className:"tabular-nums",children:["Showing ",e.jsx("span",{className:"text-neutral",children:ie.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-neutral",children:X.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-neutral",children:_e.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>ne(c=>Math.max(1,c-1)),disabled:Gt<=1,"aria-label":"Previous page",className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-mono-800 disabled:hover:text-strong",children:[e.jsx(Fo,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-strong",children:Gt})," of"," ",e.jsx("span",{className:"text-strong",children:qt})]}),e.jsxs("button",{type:"button",onClick:()=>ne(c=>Math.min(qt,c+1)),disabled:Gt>=qt,"aria-label":"Next page",className:"inline-flex items-center gap-1 rounded-md border border-base bg-bg px-2.5 py-1.5 text-strong transition hover:border-strong hover:text-primary disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-mono-800 disabled:hover:text-strong",children:["Next",e.jsx(Ws,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:Pe?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Performance"}),e.jsx("h3",{children:"Search performance"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex gap-1",role:"tablist","aria-label":"Performance window",children:Rl.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":g===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${g===c?"bg-mono-700 border-mono-600 text-primary":"border-base text-secondary hover:border-strong hover:text-neutral"}`,onClick:()=>K(c),children:c==="all"?"All":c},c))}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:be,onClick:()=>{le(0),Ut(0),Zs()},children:[e.jsx(gt,{className:`h-3.5 w-3.5 ${be?"animate-spin":""}`,"aria-hidden":"true"}),be?"Loading…":"Apply filters"]})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,w=Math.max(...c.map(ke=>ke.impressions),1),{clicks:Q,impressions:he,ctr:Ce}=d.totals,Ye=(Ce*100).toFixed(1),Je=700,Qt=220,Xe={top:12,bottom:36,left:48,right:12},ji=Je-Xe.left-Xe.right,zt=Qt-Xe.top-Xe.bottom,ms=ji/c.length,Ps=Math.max(Math.min(ms*.35,24),4),Kn=Math.max(Ps*.15,1),yi=ke=>{if(ke<=0)return 1;const xt=Math.pow(10,Math.floor(Math.log10(ke))),Ze=ke/xt,vt=Ze<=1.5?1.5:Ze<=3?3:Ze<=5?5:10;return Math.ceil(vt*xt)},Ls=4,Ds=Math.ceil(yi(w)/Ls)*Ls,vi=Array.from({length:Ls+1},(ke,xt)=>Ds/Ls*xt),Ni=ke=>ke>=1e3?`${(ke/1e3).toFixed(ke>=1e4?0:1)}k`:String(ke);return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center gap-5 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-positive-500"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Clicks ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:Q.toLocaleString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm bg-chart-series-2"}),e.jsxs("span",{className:"text-xs text-secondary",children:["Impressions ",e.jsx("span",{className:"text-strong tabular-nums font-medium",children:he.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-muted",children:["CTR ",e.jsxs("span",{className:"text-caution-400 tabular-nums font-medium",children:[Ye,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Je} / ${Qt}`},children:e.jsxs("svg",{viewBox:`0 0 ${Je} ${Qt}`,className:"h-full w-full",children:[vi.map((ke,xt)=>{const Ze=Xe.top+zt-ke/Ds*zt;return e.jsxs("g",{children:[e.jsx("line",{x1:Xe.left,y1:Ze,x2:Je-Xe.right,y2:Ze,stroke:Ve.gridLine,strokeWidth:"1"}),e.jsx("text",{x:Xe.left-6,y:Ze+3.5,textAnchor:"end",fill:Ve.text,fontSize:"10",fontFamily:"inherit",children:Ni(ke)})]},`t-${xt}`)}),c.map((ke,xt)=>{const Ze=Xe.left+ms*xt+ms/2,vt=ke.impressions/Ds*zt,Rs=ke.clicks/Ds*zt;return e.jsxs("g",{children:[e.jsx("title",{children:`${ke.date}
|
|
2
|
-
Clicks: ${ke.clicks}
|
|
3
|
-
Impressions: ${ke.impressions}
|
|
4
|
-
CTR: ${(ke.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Ze-Ps-Kn/2,y:Xe.top+zt-vt,width:Ps,height:Math.max(vt,1),rx:2,fill:He[1],opacity:.85}),e.jsx("rect",{x:Ze+Kn/2,y:Xe.top+zt-Rs,width:Ps,height:Math.max(Rs,1),rx:2,fill:bt.positiveDeep,opacity:.85})]},ke.date)}),(()=>{const ke=Math.min(c.length,7);return Array.from({length:ke},(xt,Ze)=>{const vt=c.length===1?0:Math.round(Ze/(ke-1)*(c.length-1)),Rs=Xe.left+ms*vt+ms/2;return e.jsx("text",{x:Rs,y:Qt-8,textAnchor:"middle",fill:Ve.textDim,fontSize:"10",fontFamily:"inherit",children:c[vt].date.slice(5)},`xl-${vt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-5",children:[e.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:$.startDate,onChange:c=>q(w=>({...w,startDate:c.target.value}))}),e.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:$.endDate,onChange:c=>q(w=>({...w,endDate:c.target.value}))}),e.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:"text",placeholder:"Contains query…","aria-label":"Filter query (substring match)",title:"Case-insensitive substring match on the query column.",value:$.query,onChange:c=>q(w=>({...w,query:c.target.value}))}),e.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:"text",placeholder:"Contains page URL…","aria-label":"Filter page (substring match)",title:"Case-insensitive substring match on the page URL.",value:$.page,onChange:c=>q(w=>({...w,page:c.target.value}))}),e.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:"number",min:"1",placeholder:"Rows per page (20)","aria-label":"Rows per page",title:"Rows per page. Ignored while a filter or column sort is active — then up to 500 matches are loaded.",value:$.limit,onChange:c=>q(w=>({...w,limit:c.target.value}))})]}),e.jsxs("p",{className:"mt-2 text-xs text-muted",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. When a filter or column sort is active, up to ",Os.toLocaleString()," matching rows load so sorting covers the full set."]}),m.length>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Date"}),e.jsx("th",{className:"text-left",children:"Query"}),e.jsx("th",{className:"text-left",children:"Page"}),Object.values(Mt).map(c=>e.jsx("th",{className:"text-right","aria-sort":Be?.key===c?Be.dir==="asc"?"ascending":"descending":"none",children:e.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:()=>We(w=>w?.key===c?w.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"}),children:[Gi[c],Be?.key===c?Be.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:ls.map((c,w)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-secondary",children:c.date}),e.jsx("td",{className:"max-w-xs truncate text-strong",children:c.query}),e.jsx("td",{className:"max-w-xs truncate text-secondary",children:c.page}),e.jsx("td",{className:"text-right tabular-nums text-neutral",children:c.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[(Number.isFinite(c.ctr)?c.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-secondary",children:c.position.toFixed(1)})]},`${c.date}:${c.query}:${c.page}:${w}`))})]})}),xe?e.jsx("div",{className:"mt-3 text-xs text-muted",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",ue.toLocaleString()," matching row",ue===1?"":"s",ue>=Os?` (capped at ${Os.toLocaleString()} — narrow the filter to see more)`:""]})}):(Z>0||te)&&(()=>{const c=parseInt($.limit,10)||20,w=Z+1,Q=Z+m.length;return e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-muted",children:[e.jsxs("span",{className:"tabular-nums",children:["Showing ",w.toLocaleString()," – ",Q.toLocaleString(),te?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:be||Z===0,onClick:()=>{const he=Math.max(0,Z-c);le(he),Ut(he)},children:"Previous"}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:be||!te,onClick:()=>{const he=Z+c;le(he),Ut(he)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No performance rows match the current filters yet."})]}),e.jsxs(V,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Inspection"}),e.jsx("h3",{children:"Inspect a URL"})]})}),!T()&&e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.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:x,onChange:c=>A(c.target.value),onKeyDown:c=>c.key==="Enter"&&void zn()}),e.jsx(R,{type:"button",size:"sm",disabled:pe||!Ie?.propertyId||!x.trim(),onClick:de(zn),children:pe?"Inspecting…":"Inspect URL"})]}),I&&e.jsxs("div",{className:"mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:I.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:I.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:Hn(I.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:et(I.crawlTime)})]})]})]}),e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Inspection log"})]}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:re,onClick:()=>{As({force:!0,notify:!0})},children:[e.jsx(gt,{className:`h-3.5 w-3.5 ${re?"animate-spin":""}`,"aria-hidden":"true"}),re?"Loading…":"Refresh history"]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.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:B,onChange:c=>v(c.target.value)}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:re,onClick:()=>{As({force:!0,notify:!0})},children:"Apply filter"})]}),f.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Indexing"}),e.jsx("th",{className:"text-left",children:"Verdict"}),e.jsx("th",{className:"text-left",children:"Coverage"}),e.jsx("th",{className:"text-left",children:"Mobile"}),e.jsx("th",{className:"text-left",children:"Inspected"})]})}),e.jsx("tbody",{children:f.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-neutral",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-secondary",children:c.coverageState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:Hn(c.isMobileFriendly??null)}),e.jsx("td",{className:"text-secondary",children:et(c.inspectedAt)})]},c.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No inspection history yet."})]}),e.jsxs(V,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Deindexed"}),e.jsx("h3",{children:"Recent indexing losses"})]})}),N.length>0?e.jsx("div",{className:"mt-3 overflow-x-auto",children:e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"URL"}),e.jsx("th",{className:"text-left",children:"Previous"}),e.jsx("th",{className:"text-left",children:"Current"}),e.jsx("th",{className:"text-left",children:"Changed at"})]})}),e.jsx("tbody",{children:N.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-strong",children:c.url}),e.jsx("td",{className:"text-secondary",children:c.previousState??"Unknown"}),e.jsx("td",{className:"text-neutral",children:c.currentState??"Unknown"}),e.jsx("td",{className:"text-secondary",children:et(c.transitionDate)})]},`${c.url}:${c.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-muted",children:"No deindexed transitions recorded."})]})]}),Ie&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-default pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>rs(c=>!c),children:[e.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 ${$t?"rotate-90":""}`,"aria-hidden":"true",children:e.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"})}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted",children:"Setup & Configuration"})]})}),$t&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(V,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Property"}),e.jsx("h3",{children:"Pick the Search Console property"})]})}),e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,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:M,disabled:U||h.length===0,onChange:c=>z(c.target.value),children:h.length===0?e.jsx("option",{value:"",children:U?"Loading properties…":"No properties available"}):h.map(c=>e.jsxs("option",{value:c.siteUrl,children:[c.siteUrl," · ",c.permissionLevel]},c.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(R,{type:"button",size:"sm",variant:"outline",disabled:U,onClick:()=>{Fn(Ie,{force:!0,notify:!0})},children:[e.jsx(gt,{className:`h-3.5 w-3.5 ${U?"animate-spin":""}`,"aria-hidden":"true"}),U?"Refreshing…":"Refresh properties"]}),!T()&&e.jsx(R,{type:"button",size:"sm",disabled:!M||Me,onClick:de(fi),children:Me?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-muted",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(V,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sync"}),e.jsx("h3",{children:"Import GSC performance data"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[160px_1fr]",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:`gsc-sync-days-${t}`,children:"Days"}),e.jsx("input",{id:`gsc-sync-days-${t}`,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:_,onChange:c=>ee(c.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-default bg-surface-subtle px-3 py-2 text-sm text-neutral",children:[e.jsx("input",{type:"checkbox",checked:oe,onChange:c=>y(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),!T()&&e.jsx(R,{type:"button",size:"sm",disabled:Js.isPending||!Ie.propertyId,onClick:de(bi),children:Js.isPending?"Queueing…":"Queue sync"}),!Ie.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(V,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Sitemap"}),e.jsx("h3",{children:"Sitemap configuration"})]})}),e.jsxs("div",{className:"mt-3 space-y-3",children:[Ie.sitemapUrl&&e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Current sitemap URL"}),e.jsx("p",{className:"mt-1 text-sm text-strong break-all",children:Ie.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:L||!Ie.propertyId,onClick:()=>{hi()},children:L?"Loading…":"Browse sitemaps from GSC"}),!T()&&e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:us.isPending||!Ie.propertyId,onClick:de(Gn),children:us.isPending?"Discovering…":"Auto-discover and queue inspection"})]}),e.jsx("p",{className:"text-xs text-muted",children:"Browse lists available sitemaps without queueing a run. Auto-discover saves the primary sitemap and queues an inspection."}),Oe&&Oe.length>0&&e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs uppercase tracking-wide text-muted",children:["Sitemaps (",Oe.length,")"]}),Oe.map(c=>{const w=c.contents?.[0];return e.jsxs("div",{className:"flex items-start justify-between gap-2 text-xs",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-strong break-all",children:c.path}),c.lastSubmitted&&e.jsxs("p",{className:"text-muted",children:["Submitted: ",c.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[w&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-neutral",children:[w.indexed," / ",w.submitted]}),e.jsx("p",{className:"text-muted",children:"indexed"})]}),e.jsx("button",{type:"button",className:"text-xs text-secondary hover:text-strong transition-colors",onClick:()=>it(c.path),children:"Use"})]})]},c.path)})]}),!T()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.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:Ie.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Le,onChange:c=>it(c.target.value),onKeyDown:c=>c.key==="Enter"&&Le.trim()&&void $s()}),e.jsx(R,{type:"button",size:"sm",disabled:rt||!Le.trim(),onClick:de($s),children:rt?"Saving…":Ie.sitemapUrl?"Update":"Save"})]}),!T()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.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:"Sitemap URL for inspection (leave empty for saved default)",id:`gsc-sitemap-inspect-${t}`}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:Xs.isPending||!Ie.propertyId,onClick:de(async()=>{const w=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||Ie.sitemapUrl||void 0;ge(null),mt(null);try{await Xs.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:w}})}catch{}}),children:Xs.isPending?"Queueing…":"Inspect sitemap"})]}),!Ie.propertyId&&e.jsx("p",{className:"text-xs text-caution-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}const Tl=new Set(["gbp-listing-discrepancy","gbp-lodging-gap","gbp-cta-gap","gbp-metric-drop","gbp-keyword-drop"]);function Ml({projectName:t,projectId:s}){const n=At(),[a,i]=o.useState(null),[r,l]=o.useState(null),[h,u]=o.useState(!1),m=ve($n({client:W,path:{name:t}})),p=m.data?.find(P=>P.connectionType==="gbp"),d=!!p,S=a?{locationName:a}:void 0,f=ve({...sr({client:W,path:{name:t}}),enabled:d}),C=ve({...nr({client:W,path:{name:t},query:S}),enabled:d}),N=ve({...ar({client:W,path:{name:t},query:S}),enabled:d}),b=ve({...ir({client:W,path:{name:t},query:S}),enabled:d}),I=ve({...rr({client:W,path:{name:t},query:S}),enabled:d}),G=ve({...or({client:W,path:{name:t},query:S}),enabled:d}),M=ve({queryKey:["gbp-section-insights",t],queryFn:()=>lr(t),enabled:d});function z(){n.invalidateQueries({predicate:P=>{const U=P.queryKey[0];return typeof U?._id=="string"&&U._id.startsWith("getApiV1ProjectsByNameGbp")}})}const x=vs({...dr(),onSuccess:P=>{cr({id:P.runId,projectId:s,kind:Ft["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),Y({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),A=o.useSyncExternalStore(Ra,Gs,Gs),_=Object.values(A.runs).some(P=>P.kind===Ft["gbp-sync"]&&P.projectId===s),ee=x.isPending||_,oe=vs({...ur(),onSuccess:()=>z()});if(o.useEffect(()=>{if(!a||!f.data)return;const P=f.data.locations.filter(U=>U.selected);(P.length<=1||!P.some(U=>U.locationName===a))&&i(null)},[a,f.data]),o.useEffect(()=>{if(!r||!f.data)return;(a?[a]:f.data.locations.filter(U=>U.selected).map(U=>U.locationName)).includes(r)||l(null)},[r,f.data,a]),m.isLoading)return null;if(!p){const P=[{title:"Connect your Google account",command:`canonry gbp connect ${t}`,note:"Opens Google OAuth. Grant Business Profile (business.manage) access."},{title:"Choose the account",command:`canonry gbp accounts ${t}`,note:"Pick which Business Profile account this project tracks."},{title:"Select locations",command:`canonry gbp locations discover ${t}`,note:e.jsxs(e.Fragment,{children:["Then adopt the ones to sync: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry gbp locations select ",t," <location>"]})]})},{title:"Sync, and keep it fresh",command:`canonry gbp sync ${t}`,note:e.jsxs(e.Fragment,{children:["Schedule it: ",e.jsxs("code",{className:"rounded bg-bg-elevated/80 px-1 py-0.5 font-mono text-[11px] text-secondary",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(V,{className:"surface-card",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsx("h2",{children:"Connect Google Business Profile"}),e.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:"}),e.jsx("ol",{className:"mt-5 space-y-4",children:P.map((U,we)=>e.jsxs("li",{className:"grid grid-cols-[1.5rem_1fr] gap-x-3",children:[e.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:we+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:U.title}),e.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:U.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:U.note})]})]},U.title))})]})})}const y=C.data,g=f.data?.locations??[],K=g.filter(P=>P.selected),$=N.data?.keywords??[],q=b.data?.lodging??[],Z=I.data?.placeActions??[],le=G.data?.places??[],te=g.length>0?g[0].accountName:p.domain,fe=a?g.find(P=>P.locationName===a)?.displayName??null:null,ue=a?g.filter(P=>P.locationName===a):K,H=new Set(ue.map(P=>P.locationName)),xe=q.filter(P=>H.has(P.locationName)),k=Z.filter(P=>H.has(P.locationName)),B=le.filter(P=>H.has(P.locationName)),v=new Set(K.map(P=>P.locationName)),J=a?$:$.filter(P=>v.has(P.locationName)),F=!a&&K.length>1,ce=(M.data??[]).filter(P=>!P.dismissed&&Tl.has(P.type)&&(!fe||P.query===fe||P.query===a||P.title.startsWith(fe)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Local presence"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Google Business Profile",e.jsx(Te,{text:"How AI answer engines and Maps surface this business: performance, search terms, and how your public listing compares to the profile you control."})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{tone:"positive",children:"Connected"}),!T()&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:ee,onClick:()=>x.mutate({client:W,path:{name:t},body:{}}),children:ee?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-muted",children:[te?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-secondary",children:te})," · "]}):null,f.data?`${f.data.totalSelected} of ${f.data.totalDiscovered} locations tracked`:"Loading locations…"]}),K.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(ca,{label:"All locations",active:a===null,onClick:()=>i(null)}),K.map(P=>e.jsx(ca,{label:P.displayName,active:a===P.locationName,onClick:()=>i(P.locationName)},P.id))]}),K.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-neutral",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[ce.length>0&&e.jsxs("div",{className:"mb-6 grid gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Needs attention"}),ce.map(P=>e.jsx("div",{className:["insight-card",Vl(P.severity),"rounded-r-lg border border-default bg-surface p-3 pl-4"].filter(Boolean).join(" "),children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-strong",children:[P.title,P.recommendation?.reason&&e.jsx(Te,{text:P.recommendation.reason})]})},P.id))]}),y&&e.jsx(Xl,{performance:y.performance,freshness:y.freshness,timeseries:y.timeseries}),y?.profileCompleteness&&e.jsx(El,{summary:y.profileCompleteness}),ue.length>0&&e.jsx(Ol,{locations:ue,lodging:xe,places:B,placeActions:k,expandedLocation:r,onToggleExpanded:P=>{l(U=>U===P?null:P)}}),e.jsxs("div",{className:"mb-2",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),N.data&&N.data.total>0&&e.jsxs("span",{className:"text-[11px] text-faint",children:[N.data.thresholdedPct,"% privacy-thresholded"]})]}),J.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No keyword impressions stored yet."}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Search term"}),F&&e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:J.slice(0,25).map(P=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-neutral",children:P.keyword}),F&&e.jsx("td",{className:"text-muted",children:g.find(U=>U.locationName===P.locationName)?.displayName??P.locationName}),e.jsx("td",{className:"text-right font-mono text-strong",children:P.valueCount!==null?P.valueCount.toLocaleString():e.jsxs("span",{className:"text-muted",title:"Privacy floor — Google withheld the exact count",children:["<",P.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-faint",children:[P.periodStart,"–",P.periodEnd]})]},`${P.locationName}:${P.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-default pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-secondary hover:text-strong",onClick:()=>u(P=>!P),"aria-expanded":h,children:[e.jsx("span",{"aria-hidden":"true",children:h?"▾":"▸"})," Manage locations (",g.length,")"]}),h&&e.jsx("div",{className:"mt-3",children:g.length===0?e.jsxs("p",{className:"text-sm text-muted",children:["No locations discovered. Run ",e.jsx("span",{className:"font-mono",children:"canonry gbp locations discover"}),"."]}):e.jsxs("table",{className:"data-table w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left",children:"Location"}),e.jsx("th",{className:"text-left",children:"Address"}),e.jsx("th",{className:"text-left",children:"Status"}),!T()&&e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:g.map(P=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:P.displayName}),e.jsx("td",{className:"text-muted",children:P.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ae,{tone:P.selected?"positive":"neutral",children:P.selected?"Tracked":"Not tracked"})}),!T()&&e.jsx("td",{className:"text-right",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:oe.isPending,onClick:()=>oe.mutate({client:W,path:{name:t,locationName:P.locationName},body:{selected:!P.selected}}),children:P.selected?"Untrack":"Track"})})]},P.id))})]})})]})]})})}function ca({label:t,active:s,onClick:n}){return e.jsx("button",{type:"button",role:"tab","aria-selected":s,onClick:n,className:`rounded-full border px-3 py-1 text-xs transition-colors ${s?"border-mono-500 bg-mono-800 text-heading":"border-mono-700/60 text-secondary hover:border-mono-600 hover:text-strong"}`,children:t})}function El({summary:t}){if(t.locationCount===0)return null;const s=t.locationCount,n=[{label:"Description",value:`${t.withDescription}/${s}`,tone:ps(t.withDescription,s,"caution")},{label:"Hours",value:`${t.withHours}/${s}`,tone:ps(t.withHours,s,"caution")},{label:"Phone",value:`${t.withPrimaryPhone}/${s}`,tone:ps(t.withPrimaryPhone,s,"caution")},{label:"Service area",value:`${t.withServiceArea}/${s}`,tone:ps(t.withServiceArea,s,"neutral")},{label:"Secondary categories",value:`${t.withSecondaryCategories}/${s}`,detail:`${t.secondaryCategoryTotal} total`,tone:ps(t.withSecondaryCategories,s,"caution")},{label:"Closed",value:String(t.permanentlyClosed+t.temporarilyClosed),detail:t.permanentlyClosed||t.temporarilyClosed?`${t.permanentlyClosed} permanent, ${t.temporarilyClosed} temporary`:"reported open",tone:t.permanentlyClosed>0?"negative":t.temporarilyClosed>0?"caution":"positive"}];return e.jsxs("div",{className:"mb-6 border-y border-default py-3",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Owner profile · Business Information"}),e.jsx(Te,{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."})]}),e.jsx("div",{className:"grid gap-x-5 gap-y-3 sm:grid-cols-2 lg:grid-cols-3",children:n.map(a=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,1fr)_auto] items-baseline gap-3",children:[e.jsx("span",{className:"text-xs text-muted",children:a.label}),e.jsx("span",{className:`font-mono text-sm tabular-nums ${Hl(a.tone)}`,children:a.value}),a.detail&&e.jsx("span",{className:"col-span-2 text-[11px] text-faint",children:a.detail})]},a.label))})]})}function Ol({locations:t,lodging:s,places:n,placeActions:a,expandedLocation:i,onToggleExpanded:r}){const l=new Map(s.map(m=>[m.locationName,m])),h=new Map(n.map(m=>[m.locationName,m])),u=new Map;for(const m of a){const p=u.get(m.locationName)??[];p.push(m),u.set(m.locationName,p)}return e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Source evidence"}),e.jsx(Te,{text:T()?"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."})]}),e.jsxs("span",{className:"text-[11px] text-faint",children:[t.length," location",t.length===1?"":"s"]})]}),e.jsx("div",{className:"data-table-wrapper",children:e.jsxs("table",{className:"data-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"min-w-[14rem]",children:"Location"}),e.jsx("th",{className:"min-w-[15rem]",children:"Owner profile"}),e.jsx("th",{className:"min-w-[11rem]",children:"Hotel data"}),e.jsx("th",{className:"min-w-[11rem]",children:"Public Maps"}),e.jsx("th",{className:"min-w-[10rem]",children:"CTAs"}),e.jsx("th",{className:"text-right",children:"Detail"})]})}),e.jsx("tbody",{children:t.map(m=>{const p=l.get(m.locationName)??null,d=h.get(m.locationName)??null,S=u.get(m.locationName)??[],f=i===m.locationName;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-strong",children:m.displayName}),e.jsx("p",{className:"mt-1 text-xs text-faint",children:m.primaryCategoryDisplayName??"Primary category not returned"}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1.5",children:[e.jsx(ae,{tone:m.selected?"positive":"neutral",children:m.selected?"Tracked":"Not tracked"}),m.openStatus&&m.openStatus!=="OPEN"&&e.jsx(ae,{tone:m.openStatus==="CLOSED_PERMANENTLY"?"negative":"caution",children:ni(m.openStatus)})]})]})}),e.jsx("td",{children:e.jsx(Fl,{location:m})}),e.jsx("td",{children:e.jsx(_l,{lodging:p})}),e.jsx("td",{children:e.jsx(Gl,{place:d,mapsUri:m.mapsUri})}),e.jsx("td",{children:e.jsx(Ql,{actions:S})}),e.jsx("td",{className:"text-right",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>r(m.locationName),children:f?"Hide":"Details"})})]}),f&&e.jsx("tr",{className:"bg-mono-950/35 hover:bg-mono-950/35",children:e.jsx("td",{colSpan:6,className:"px-4 py-4",children:e.jsx(Kl,{location:m,lodging:p,place:d,placeActions:S})})})]},m.id)})})]})})]})}function Bl(t){return[{label:"Description",tone:Tt(t.description)?"positive":"neutral",value:Tt(t.description)?"set":"not returned"},{label:"Hours",tone:t.regularHours?"positive":"neutral",value:t.regularHours?"set":"not returned"},{label:"Phone",tone:Tt(t.primaryPhone)?"positive":"neutral",value:Tt(t.primaryPhone)?"set":"not returned"},{label:"Website",tone:Tt(t.websiteUri)?"positive":"neutral",value:Tt(t.websiteUri)?"set":"not returned"},{label:"Secondary",tone:t.additionalCategories.length>0?"positive":"neutral",value:t.additionalCategories.length>0?String(t.additionalCategories.length):"not returned"},{label:"Service area",tone:t.serviceArea?"positive":"neutral",value:t.serviceArea?"set":"not returned"}]}function Fl({location:t}){const s=Bl(t);return e.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(n=>e.jsxs(ae,{tone:n.tone,children:[n.label," ",n.value]},n.label))})}function _l({lodging:t}){return e.jsx(In,{...ql(t)})}function ql(t){return t?t.populatedGroupCount===0?{tone:"neutral",label:"0 groups returned",detail:"Lodging API returned no readable groups; verify Hotel details."}:{tone:"positive",label:`${t.populatedGroupCount} group${t.populatedGroupCount===1?"":"s"} returned`,detail:"Owner lodging attributes."}:{tone:"neutral",label:"No Lodging API snapshot",detail:"Not returned for this scoped location."}}function Gl({place:t,mapsUri:s}){return e.jsx(In,{...Ul(t,s)})}function Ul(t,s){if(!t)return{tone:"neutral",label:"Public listing not checked",detail:s?"Maps link available.":"No Places snapshot."};const n=t.amenities.length;return{tone:n>0?"positive":"neutral",label:n>0?`${n} signal${n===1?"":"s"} detected`:"0 supported signals detected",detail:`Places tier: ${t.tier}`}}function Ql({actions:t}){return e.jsx(In,{...zl(t)})}function zl(t){if(t.length===0)return{tone:"neutral",label:"No CTAs stored",detail:"No placeActionLinks returned."};const s=t.filter(n=>n.providerType==="MERCHANT").length;return s===0?{tone:"neutral",label:`${t.length} aggregator CTA${t.length===1?"":"s"}`,detail:"No merchant-owned CTA returned."}:{tone:"positive",label:`${s} merchant CTA${s===1?"":"s"}`,detail:`${t.length} total returned.`}}function In({tone:t,label:s,detail:n}){return e.jsxs("div",{children:[e.jsx(ae,{tone:t,children:s}),e.jsx("p",{className:"mt-1.5 text-xs leading-5 text-faint",children:n})]})}function Kl({location:t,lodging:s,place:n,placeActions:a}){const i=s?Yl(s.attributes):[];return e.jsxs("div",{className:"grid gap-5 text-xs lg:grid-cols-3",children:[e.jsxs(rn,{title:"Owner profile · Business Information",children:[e.jsx(Ke,{label:"Primary category",value:t.primaryCategoryDisplayName??"Not returned"}),e.jsx(Ke,{label:"Secondary categories",value:t.additionalCategories.length>0?t.additionalCategories.join(", "):"Not returned"}),e.jsx(Ke,{label:"Description",value:Tt(t.description)?t.description:"Not returned"}),e.jsx(Ke,{label:"Hours",value:t.regularHours?"Returned by Google":"Not returned"}),e.jsx(Ke,{label:"Service area",value:t.serviceArea?"Returned by Google":"Not returned"}),e.jsx(Ke,{label:"Phone",value:t.primaryPhone??"Not returned"}),e.jsx(Ke,{label:"Website",value:t.websiteUri??"Not returned"}),e.jsx(Ke,{label:"Open status",value:ni(t.openStatus)}),e.jsx(Ke,{label:"Opening date",value:t.openingDate??"Not returned"})]}),e.jsx(rn,{title:"Hotel data · Lodging API",children:s?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{label:"Last checked",value:da(s.syncedAt)}),e.jsx(Ke,{label:"Groups returned",value:String(s.populatedGroupCount)}),e.jsx(Ke,{label:"Populated groups",value:i.length>0?i.join(", "):"None returned"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Lodging API snapshot was stored for this location."})}),e.jsxs(rn,{title:"Public listing + CTAs",children:[n?e.jsxs(e.Fragment,{children:[e.jsx(Ke,{label:"Places tier",value:n.tier}),e.jsx(Ke,{label:"Last checked",value:da(n.syncedAt)}),e.jsx(Ke,{label:"Public signals",value:n.amenities.length>0?n.amenities.join(", "):"No supported signals detected"})]}):e.jsx("p",{className:"leading-5 text-muted",children:"No Places Details snapshot was stored for this location."}),t.mapsUri&&e.jsx("a",{href:t.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"inline-block text-muted hover:text-neutral",children:"View on Google Maps →"}),e.jsx("div",{className:"mt-3 border-t border-default pt-3",children:a.length===0?e.jsx("p",{className:"leading-5 text-muted",children:"No placeActionLinks returned."}):e.jsx("div",{className:"grid gap-2",children:a.map(r=>e.jsxs("div",{className:"grid gap-0.5",children:[e.jsxs("span",{className:"font-medium text-neutral",children:[zs(r.placeActionType),r.isPreferred?" · preferred":""]}),e.jsxs("span",{className:"text-faint",children:[zs(r.providerType),r.uri?` · ${Wl(r.uri)}`:""]})]},r.placeActionLinkName))})})]})]})}function rn({title:t,children:s}){return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-muted",children:t}),e.jsx("div",{className:"grid gap-2",children:s})]})}function Ke({label:t,value:s}){return e.jsxs("div",{className:"grid grid-cols-[7.25rem_minmax(0,1fr)] gap-3",children:[e.jsx("span",{className:"text-faint",children:t}),e.jsx("span",{className:"min-w-0 break-words text-secondary",children:s})]})}function ps(t,s,n){return t===s?"positive":t===0?n:"caution"}function Hl(t){switch(t){case"positive":return"text-positive";case"caution":return"text-caution";case"negative":return"text-negative";case"neutral":return"text-neutral"}}function Vl(t){return t==="critical"||t==="high"?"insight-card-negative":t==="medium"?"insight-card-caution":""}function Tt(t){return typeof t=="string"&&t.trim().length>0}function ni(t){return t?zs(t):"Not returned"}function zs(t){return t?t.toLowerCase().split("_").filter(Boolean).map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" "):"Unknown"}function Wl(t){try{return new URL(t).hostname.replace(/^www\./,"")}catch{return t}}function da(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",year:"numeric"})}function Yl(t){return Object.entries(t).filter(([s,n])=>s!=="name"&&s!=="metadata"&&Jl(n)).map(([s])=>zs(s.replace(/([a-z])([A-Z])/g,"$1_$2")))}function Jl(t){return t==null?!1:Array.isArray(t)?t.length>0:typeof t=="object"?Object.keys(t).length>0:!0}function Xl({performance:t,freshness:s,timeseries:n}){const a=t.totals,i=mr.filter(C=>(a[C]??0)>0),r=xr.filter(C=>(a[C]??0)>0),l=Object.keys(a).filter(C=>(a[C]??0)>0&&hr(C)==="other").sort((C,N)=>(a[N]??0)-(a[C]??0)),h=Object.keys(a).filter(C=>(a[C]??0)===0).sort(),u=n.map(C=>{const N={date:C.date};for(const[b,I]of Object.entries(C.metrics))N[b]=I;return N}),m=n.find(C=>C.pending)?.date,p=n.length>0?n[n.length-1].date:void 0,d=u.length>0,S=s.dataThroughDate?`Data through ${Qs(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,f=[...i,...l];return e.jsxs("div",{className:"mb-6 grid gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Profile actions · daily"}),S&&e.jsx("span",{className:"text-[11px] text-muted",children:S})]}),!d||i.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No profile action activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(ua,{data:u,metrics:i,kind:"line",firstPending:m,lastDate:p}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:f.map(C=>e.jsxs("span",{className:"text-sm text-secondary",children:[Us(C)," ",e.jsx("span",{className:"font-mono text-heading",children:(a[C]??0).toLocaleString()})]},C))})]})]}),d&&r.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(ua,{data:u,metrics:r,kind:"area",firstPending:m,lastDate:p})]}),h.length>0&&e.jsxs("p",{className:"text-xs text-faint",children:["Not active: ",h.map(C=>Us(C)).join(", ")]})]})}function ua({data:t,metrics:s,kind:n,firstPending:a,lastDate:i}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Zt,{width:"100%",height:"100%",children:e.jsxs(es,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Dn,{stroke:Pn,vertical:!1}),e.jsx(ts,{dataKey:"date",tick:st,tickLine:!1,axisLine:{stroke:jt},tickFormatter:yn,minTickGap:24}),e.jsx(ss,{tick:st,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ns,{...Bt,labelFormatter:Qs,formatter:(r,l)=>[typeof r=="number"?r.toLocaleString():String(r??0),Us(String(l??""))]}),e.jsx(Ua,{wrapperStyle:{fontSize:11,color:Ve.text},formatter:r=>Us(r)}),a&&i&&e.jsx(Uo,{x1:a,x2:i,fill:Ve.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Ve.textDim,fontSize:10}}),s.map((r,l)=>n==="line"?e.jsx(Rn,{type:"monotone",dataKey:r,stroke:He[l%He.length],strokeWidth:2,dot:!1,isAnimationActive:!1},r):e.jsx(Ht,{type:"monotone",dataKey:r,stackId:"reach",stroke:He[l%He.length],fill:He[l%He.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},r))]})})})}function Zl(t){return Ln(lt(String(t)))}function ec(t){return Ct(lt(String(t)))}function on({children:t,label:s="More info",placement:n="top",className:a}){const i=o.useId(),[r,l]=o.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${a??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":r?i:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-muted hover:text-strong focus:text-strong focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500",onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),onFocus:()=>l(!0),onBlur:()=>l(!1),children:e.jsx(zo,{className:"h-3.5 w-3.5","aria-hidden":!0})}),r&&e.jsx("span",{id:i,role:"tooltip",className:`absolute z-50 w-64 rounded border border-strong bg-bg-elevated px-3 py-2 text-xs font-normal leading-relaxed text-strong shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const Dt=50,ma={commoncrawl:"Common Crawl","bing-webmaster":"Bing Webmaster"},tc={commoncrawl:"Common Crawl hyperlink graph · refreshes ~monthly when a release sync completes","bing-webmaster":"Bing Webmaster Tools · live inbound links from your connected account"};function Rt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Kt(t){return t.toLocaleString()}function sc(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function nc(t){const s=Date.now()-new Date(t).getTime(),n=Math.floor(s/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const a=Math.floor(n/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function ac(t){const s=t.filter(n=>n.kind===Ft["backlink-extract"]&&!Ia(n.status));return s.length===0?null:s.reduce((n,a)=>n.createdAt>a.createdAt?n:a)}function ic(t,s){const n=new Date(t??s).getTime(),a=Math.max(0,Math.floor((Date.now()-n)/1e3));if(a<60)return`${a}s`;const i=Math.floor(a/60),r=a%60;return r===0?`${i}m`:`${i}m ${r}s`}function rc({projectName:t}){const[s,n]=o.useState(null),[a,i]=o.useState("commoncrawl"),[r,l]=o.useState(null),[h,u]=o.useState(null),[m,p]=o.useState([]),[d,S]=o.useState(null),[f,C]=o.useState(null),[N,b]=o.useState("commoncrawl"),[I,G]=o.useState(null),[M,z]=o.useState(Date.now()),[x,A]=o.useState(0),[_,ee]=o.useState(!0),[oe,y]=o.useState(!1),[g,K]=o.useState(!1),[$,q]=o.useState(null),Z=o.useRef(null),le=o.useRef(!1),te=o.useCallback(async()=>{ee(!0),q(null);try{const[E,re,je,pe,ye,O]=await Promise.all([pr(t,{excludeCrawlers:!0}).catch(()=>null),gr().catch(()=>null),fr(t,{excludeCrawlers:!0,source:a}).catch(()=>null),br(t,{limit:Dt,offset:x,excludeCrawlers:!0,source:a}).catch(Pe=>{if(Pe instanceof bn&&Pe.code==="NOT_FOUND")return null;throw Pe}),jr(t,{source:a}).catch(()=>[]),yr(t).catch(()=>[])]);n(E),S(re),l(je),u(pe),p(ye);const Se=ac(O);C(Se),Z.current=Se?.id??null}catch(E){q(E instanceof Error?E.message:"Failed to load backlinks")}finally{ee(!1)}},[t,x,a]);o.useEffect(()=>{te()},[te]),o.useEffect(()=>{if(!s||le.current)return;const E=s.sources.find(pe=>pe.hasData),re=s.sources.find(pe=>pe.connected),je=E?.source??re?.source;je&&je!==a&&i(je)},[s,a]);function fe(E){le.current=!0,A(0),i(E)}o.useEffect(()=>{if(!f)return;const E=f.id;let re=!1;const je=async()=>{try{const ye=await Ta(E);if(re)return;Ia(ye.status)?(C(null),G(ye),await te()):C(O=>O?.id===ye.id?{...O,...ye}:O)}catch{}},pe=window.setInterval(()=>{je()},3e3);return()=>{re=!0,window.clearInterval(pe)}},[f,te]),o.useEffect(()=>{if(!f)return;const E=window.setInterval(()=>z(Date.now()),1e3);return()=>window.clearInterval(E)},[f]),o.useEffect(()=>{if(!I||I.status==="failed")return;const E=window.setTimeout(()=>G(null),1e4);return()=>window.clearTimeout(E)},[I]);async function ue(){y(!0),q(null);try{const E=await wr(t);b("commoncrawl"),C(E),Z.current=E.id}catch(E){E instanceof bn&&E.code==="MISSING_DEPENDENCY"?q("DuckDB is not installed. Visit the Backlinks admin page to install it."):q(E instanceof Error?E.message:"Failed to trigger extract")}finally{y(!1)}}async function H(){K(!0),q(null);try{const E=await Nr(t);b("bing-webmaster"),C(E),Z.current=E.id}catch(E){q(E instanceof Error?E.message:"Failed to trigger Bing sync")}finally{K(!1)}}const xe=o.useMemo(()=>m.slice().sort((E,re)=>E.queriedAt.localeCompare(re.queriedAt)).map(E=>({date:E.queriedAt,linkingDomains:E.totalLinkingDomains})),[m]),k=h?.rows??[],B=h?.total??0,v=r?.excludedLinkingDomains??0,J=B>Dt,F=Math.floor(x/Dt)+1,ce=Math.max(1,Math.ceil(B/Dt));return o.useEffect(()=>{x>0&&x>=B&&A(0)},[x,B]),e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Backlinks"}),e.jsx("h2",{children:"Referring domains"}),e.jsxs("p",{className:"text-sm text-muted mt-1 max-w-2xl",children:["Domains linking to "," ",e.jsx("span",{className:"text-neutral",children:t}),", from whichever source you have set up — the"," ",e.jsx("span",{className:"text-neutral",children:"Common Crawl"})," hyperlink graph (~monthly) and"," ",e.jsx("span",{className:"text-neutral",children:"Bing Webmaster"})," inbound links (live)."]})]})}),$&&e.jsx(V,{className:"surface-card p-4 mb-4 border-negative-800/60",children:e.jsx("p",{className:"text-sm text-negative",children:$})}),f&&e.jsx(V,{className:"surface-card p-4 mb-4 border-info-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(jn,{className:"h-5 w-5 text-info-400 animate-spin shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("p",{className:"text-sm font-medium text-heading",children:N==="bing-webmaster"?"Bing sync running":"Extract running"}),e.jsx(ae,{tone:"neutral",children:f.status}),e.jsxs("span",{className:"text-xs text-muted tabular-nums",children:[ic(f.startedAt??null,f.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",M]})]}),N==="bing-webmaster"?e.jsxs("p",{className:"text-xs text-muted mt-1",children:["Pulling inbound links live from Bing Webmaster for"," ",e.jsx("span",{className:"text-neutral",children:t}),". Time depends on how many pages link to your site."]}):e.jsxs("p",{className:"text-xs text-muted mt-1",children:["Re-querying the cached Common Crawl release for"," ",e.jsx("span",{className:"text-neutral",children:t}),". No re-download — the ~16 GB dump already lives at"," ",e.jsx("code",{className:"text-secondary",children:"~/.canonry/cache/commoncrawl/"}),". Typically takes ~5 minutes."]})]})]})}),I&&!f&&e.jsx(V,{className:`surface-card p-4 mb-4 ${I.status==="failed"?"border-negative-800/60":"border-positive-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[I.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-negative-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Qa,{className:"h-5 w-5 text-positive-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${I.status==="failed"?"text-negative":"text-positive"}`,children:N==="bing-webmaster"?I.status==="failed"?"Bing sync failed":"Bing sync complete":I.status==="failed"?"Extract failed":"Extract complete"}),I.error?e.jsx("p",{className:"text-xs text-muted mt-1",children:vr(I.error)}):I.status!=="failed"?e.jsx("p",{className:"text-xs text-muted mt-1",children:N==="bing-webmaster"?"Inbound links refreshed live from Bing Webmaster.":"Backlinks refreshed from the cached release."}):null]})]})}),P()]});function P(){return _||!s?e.jsx(V,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-muted",children:"Loading backlinks…"})}):!s.anyConnected&&!s.anyData?we():e.jsxs(e.Fragment,{children:[U(s),a==="bing-webmaster"?Me():$e()]})}function U(E){return e.jsx("div",{className:"flex items-center gap-2 mb-4 flex-wrap",role:"tablist","aria-label":"Backlink source",children:E.sources.map(re=>{const je=re.source===a,pe=re.hasData?"bg-positive-500":re.connected?"bg-caution-500":"bg-mono-600";return e.jsxs("button",{type:"button",role:"tab","aria-selected":je,onClick:()=>fe(re.source),className:`inline-flex items-center gap-2 rounded-full border px-3 py-1 text-xs transition-colors focus:outline-none focus-visible:ring-1 focus-visible:ring-mono-500 ${je?"border-mono-500 bg-mono-800 text-heading":"border-base bg-bg-elevated/40 text-secondary hover:text-strong"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${pe}`,"aria-hidden":!0}),ma[re.source],re.hasData&&e.jsx("span",{className:"text-muted tabular-nums",children:Kt(re.totalLinkingDomains)})]},re.source)})})}function we(){return e.jsx(V,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(en,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlink source set up yet"}),e.jsxs("p",{className:"text-sm text-muted mt-1 max-w-2xl",children:["Connect at least one source to see which domains link to"," ",e.jsx("code",{className:"text-neutral",children:t}),":"]}),e.jsxs("ul",{className:"mt-3 space-y-2 text-sm text-secondary",children:[e.jsxs("li",{children:[e.jsx("span",{className:"text-strong",children:"Common Crawl"})," — free public hyperlink graph, refreshes ~monthly. Enable backlinks and run a workspace release sync."]}),e.jsxs("li",{children:[e.jsx("span",{className:"text-strong",children:"Bing Webmaster"})," — live inbound links from your verified site. Connect a Bing Webmaster account, then sync."]})]}),!T()&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"Set up Common Crawl"})})}),e.jsxs("p",{className:"mt-3 text-xs text-muted",children:["Connect Bing with"," ",e.jsxs("code",{className:"text-secondary",children:["canonry bing connect ",t," --api-key <key>"]}),"."]})]})]})]})})}function Me(){const E=s?.sources.find(ye=>ye.source==="bing-webmaster"),re=E?.connected??!1,je=E?.hasData??!1;return r!==null&&r.totalLinkingDomains>0?be(T()?null:e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:g||f!==null,onClick:de(H),children:[e.jsx(fs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Sync running…":g?"Queuing…":"Re-sync Bing"]})):e.jsx(V,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(en,{className:"h-5 w-5","aria-hidden":!0})}),e.jsx("div",{className:"flex-1",children:re&&je?v>0?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No non-crawler referring domains"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Bing Webmaster synced for ",e.jsx("code",{className:"text-neutral",children:t}),", but"," ",Kt(v)," crawler/proxy referring domain",v===1?"":"s"," in the latest window ",v===1?"is":"are"," hidden by default. Re-sync to check for new links."]}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:g||f!==null,onClick:de(H),children:[e.jsx(fs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Sync running…":g?"Queuing…":"Re-sync Bing inbound links"]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No Bing inbound links returned"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Bing Webmaster synced for ",e.jsx("code",{className:"text-neutral",children:t}),", but the Bing backlink API returned ",e.jsx("span",{className:"text-neutral",children:"0 inbound-link rows"})," in the latest window. There were no referring domains to filter."]}),e.jsx("p",{className:"text-xs text-muted mt-2",children:"Re-sync later or compare against the Bing Webmaster Tools backlink export for this verified site."}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:g||f!==null,onClick:de(H),children:[e.jsx(fs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Sync running…":g?"Queuing…":"Re-sync Bing inbound links"]})})]}):re?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No Bing inbound links yet"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Bing Webmaster is connected for ",e.jsx("code",{className:"text-neutral",children:t})," but no inbound links have been synced yet. Run a sync to pull them live from your account."]}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsxs(R,{type:"button",size:"sm",disabled:g||f!==null,onClick:de(H),children:[e.jsx(Ot,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Sync running…":g?"Queuing…":"Sync Bing inbound links"]})})]}):e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Bing Webmaster not connected"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Connect a Bing Webmaster account for ",e.jsx("code",{className:"text-neutral",children:t})," to pull live inbound links, then sync."]}),e.jsxs("pre",{className:"mt-3 rounded bg-bg-elevated border border-base px-3 py-2 text-xs text-neutral overflow-x-auto",children:["canonry bing connect ",t," --api-key <key>"]})]})})]})})}function $e(){const E=r!==null&&r.totalLinkingDomains>0,re=I?.status==="failed",je=r!==null&&r.totalLinkingDomains===0&&!re,pe=d?.status==="ready",ye=d?.status==="failed",O=d&&(d.status==="downloading"||d.status==="querying"||d.status==="queued");return E?be(e.jsxs(e.Fragment,{children:[!T()&&e.jsxs(e.Fragment,{children:[e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:oe||f!==null,onClick:de(ue),children:[e.jsx(fs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Extract running…":oe?"Queuing…":"Re-run extract"]}),e.jsxs(on,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the ",e.jsx("span",{className:"text-strong",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-neutral",children:"~/.canonry/cache/commoncrawl/"})," for ",e.jsx("span",{className:"text-strong",children:t}),". Replaces existing backlink rows for this project under the current release."]}),e.jsxs("span",{className:"mt-2 block text-secondary",children:[e.jsx("span",{className:"text-strong",children:"No re-download"})," of the ~16 GB dump. Typically ",e.jsx("span",{className:"text-strong",children:"~5 min"}),"."]})]})]}),!T()&&e.jsx(R,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"Open admin"})})]})):e.jsx(V,{className:"surface-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-lg bg-bg-elevated text-secondary",children:e.jsx(en,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!d&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"Set up backlinks"})})})]}),O&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["A workspace release sync is running (",d.status,d.phaseDetail?` — ${d.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"View sync status"})})})]}),ye&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-muted mt-1",children:d.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),!T()&&e.jsx("div",{className:"mt-4",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"Go to Backlinks admin"})})})]}),pe&&!O&&!je&&!re&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["Release ",e.jsx("code",{className:"text-neutral",children:d.release})," is ready but no backlinks have been extracted for"," ",e.jsx("code",{className:"text-neutral",children:t}),". Run an extract to populate data using the cached release."]}),!T()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(R,{type:"button",size:"sm",disabled:oe||f!==null,onClick:de(ue),children:[e.jsx(Ot,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Extract running…":oe?"Queuing…":"Run extract"]}),e.jsxs(on,{label:"What does Run extract do?",children:[e.jsxs("span",{className:"block",children:["Runs a DuckDB query against the ",e.jsx("span",{className:"text-strong",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-neutral",children:"~/.canonry/cache/commoncrawl/"})," to find referring domains for ",e.jsx("span",{className:"text-strong",children:t}),"."]}),e.jsxs("span",{className:"mt-2 block text-secondary",children:["No re-download. Typically takes ",e.jsx("span",{className:"text-strong",children:"~5 min"}),"."]})]})]})]}),re&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"Last extract failed"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["See the error above for details. If the cache files for release"," ",e.jsx("code",{className:"text-neutral",children:d?.release})," are missing, re-sync the release from the Backlinks admin to restore the ~16 GB dump, then re-run the extract."]}),!T()&&e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"Go to Backlinks admin"})})})]}),je&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-heading",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-muted mt-1",children:["The last extract against release ",e.jsx("code",{className:"text-neutral",children:r.release})," found"," ",e.jsx("span",{className:"text-neutral",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-neutral",children:r.targetDomain}),". This can happen when:"]}),e.jsxs("ul",{className:"mt-2 space-y-1 text-xs text-muted list-disc list-inside",children:[e.jsx("li",{children:"the domain is newer than the release’s crawl window"}),e.jsx("li",{children:"the Common Crawl snapshot didn’t capture pages that link to it"}),e.jsx("li",{children:"the extract ran against a cache that was missing or incomplete"})]}),e.jsx("p",{className:"text-sm text-muted mt-3",children:"Try syncing a newer release — each Common Crawl dump is a different snapshot of the web graph."}),!T()&&e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(R,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Rt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:oe||f!==null,onClick:de(ue),children:[e.jsx(Ot,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),f?"Extract running…":oe?"Queuing…":"Re-run extract"]}),e.jsxs(on,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the cached release for ",e.jsx("span",{className:"text-strong",children:r.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.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 be(E){if(!r)return null;const re=a==="bing-webmaster",je=re?"Inbound links":"Linking hosts",pe=re?"inbound links":"linking hosts",ye=re?"window":"release";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"gauge-row",children:[e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Referring domains"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Kt(r.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",r.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Total ",pe]}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:Kt(r.totalHosts)})}),e.jsxs("p",{className:"metric-card-sub",children:["aggregate ",pe," across referring domains"]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Top-10 concentration"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-primary",children:sc(r.top10HostsShare)})}),e.jsxs("p",{className:"metric-card-sub",children:["share of ",pe," from the 10 largest linking domains"]})]})]}),e.jsxs("p",{className:"text-xs text-faint mt-2",children:[e.jsx("span",{className:"text-secondary",children:ma[a]})," · ",ye," ",e.jsx("code",{className:"text-secondary",children:r.release})," · queried ",nc(r.queriedAt),v>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-muted",children:[v," crawler/proxy domain",v===1?"":"s"," hidden"]})]})]}),e.jsx("p",{className:"text-[11px] text-faint mt-0.5",children:tc[a]}),xe.length>=2&&e.jsxs(V,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over time"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Zt,{width:"100%",height:"100%",children:e.jsxs(es,{data:xe,margin:{top:8,right:12,bottom:0,left:12},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"bl-gradient",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:He[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:He[0],stopOpacity:0})]})}),e.jsx(ts,{dataKey:"date",tick:st,stroke:jt,tickFormatter:Zl}),e.jsx(ss,{tick:st,stroke:jt,allowDecimals:!1}),e.jsx(ns,{contentStyle:Bt.contentStyle,labelStyle:Bt.labelStyle,itemStyle:Bt.itemStyle,labelFormatter:ec}),e.jsx(Ht,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:He[0],fill:"url(#bl-gradient)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Top referring domains"}),J&&e.jsxs("p",{className:"text-xs text-faint",children:["Page ",F," of ",ce," · ",Kt(B)," total"]})]}),e.jsx(V,{className:"surface-card overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base text-left text-xs uppercase tracking-wide text-faint",children:[e.jsx("th",{className:"px-4 py-2 font-medium",children:"Domain"}),e.jsx("th",{className:"px-4 py-2 text-right font-medium",children:je})]})}),e.jsxs("tbody",{children:[k.map(O=>e.jsxs("tr",{className:"border-b border-mono-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-strong",children:O.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-secondary tabular-nums",children:Kt(O.numHosts)})]},O.linkingDomain)),k.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-muted",colSpan:2,children:v>0&&B===0?`Every referring domain in this ${ye} was a crawler/proxy host (${v} hidden).`:`No referring domains in this ${ye}.`})})]})]})}),J&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:x===0,onClick:()=>A(O=>Math.max(0,O-Dt)),children:"Previous"}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:x+Dt>=B,onClick:()=>A(O=>O+Dt),children:"Next"})]})]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:E})]})}}function oc({projectName:t}){const s=ve({...Sr({client:W,path:{name:t}}),staleTime:Ma}),n=s.data??null,a=s.error;if(s.isLoading&&!n)return null;if(a)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-negative-400",children:a instanceof Error?a.message:String(a)})]});if(!n)return null;if(n.status==="no-data")return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsx("h2",{children:"Citation + answer-mention coverage"})]})}),e.jsx("p",{className:"text-sm text-muted",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:i,providersMentioning:r,providersConfigured:l}=n.summary;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Citation visibility"}),e.jsxs("h2",{className:"flex items-center gap-2",children:["Cited by ",i," of ",l," engines",e.jsx(Te,{text:"An engine is ‘citing’ when our domain appears in its grounding source list (the structured citation/search-result attribution it returns alongside the answer). Counts each configured engine that cites the project on at least one tracked query in the latest snapshot per (query × provider)."})]}),e.jsxs("p",{className:"text-base text-neutral flex items-center gap-2",children:["Mentioned in ",r," of ",l," engine answers",e.jsx(Te,{text:"An engine is ‘mentioning’ when our brand or domain appears inside the prose of the answer text — independent of whether it’s in the citation list. Models often name-drop from training without citing a fresh page."})]})]}),n.summary.latestRunAt&&e.jsxs("p",{className:"supporting-copy",children:["Latest run ",new Date(n.summary.latestRunAt).toLocaleString()]})]}),e.jsx(lc,{data:n}),e.jsx(cc,{data:n}),n.competitorGaps.length>0&&e.jsx(xc,{data:n})]})}function lc({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:a,queriesMentionedOnly:i,queriesInvisible:r}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(Bs,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Bs,{label:"Cited only",value:`${a} / ${s}`,helper:"In sources, not named in answer",tone:a>0?"positive-dim":"neutral"}),e.jsx(Bs,{label:"Mentioned only",value:`${i} / ${s}`,helper:"Named in answer, no source link",tone:i>0?"caution":"neutral"}),e.jsx(Bs,{label:"Invisible",value:`${r} / ${s}`,helper:"No engine cites or mentions",tone:r>0?"negative":"neutral"})]})}function Bs({label:t,value:s,helper:n,tone:a}){const i=a==="positive"?"text-positive":a==="positive-dim"?"text-positive-400/70":a==="caution"?"text-caution":a==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s}),e.jsx("p",{className:"text-[11px] text-muted",children:n})]})}function cc({data:t}){const s=o.useMemo(()=>{const n=new Set;for(const a of t.byQuery)for(const i of a.providers)n.add(i.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(dc,{}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),s.map(n=>e.jsx("th",{className:"text-center",children:e.jsx(Xt,{provider:n})},n)),e.jsx("th",{className:"text-right",children:"Cite"}),e.jsx("th",{className:"text-right",children:"Ment"})]})}),e.jsx("tbody",{children:t.byQuery.map(n=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:n.query}),s.map(a=>{const i=n.providers.find(r=>r.provider===a);return e.jsx("td",{className:"text-center",children:i==null?e.jsx(Yo,{className:"inline h-3.5 w-3.5 text-mono-700","aria-label":"no data"}):e.jsx(uc,{provider:i})},a)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-positive":n.citedCount>0?"text-positive-400/70":"text-muted",children:[n.citedCount,"/",n.totalProviders]})}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.mentionedCount===n.totalProviders?"text-info-300":n.mentionedCount>0?"text-info-400/70":"text-muted",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function dc(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-muted",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Vt,{active:!1,tone:"cited"}),e.jsx(Vt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function uc({provider:t}){const s=mc(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Vt,{active:t.cited,tone:"cited"}),e.jsx(Vt,{active:t.mentioned,tone:"mentioned"})]})}function mc(t){return t.cited&&t.mentioned?"Cited in sources and mentioned in answer":t.cited?"Cited in sources, not mentioned in answer":t.mentioned?"Mentioned in answer, not in sources":"Not cited and not mentioned"}function Vt({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-strong/80 bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-positive-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-info-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function xc({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-strong mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Te,{text:"Queries where the project is not cited but a configured competitor is. Each row maps to one (query, engine) pair — the same query may surface for multiple engines."}),e.jsxs("span",{className:"text-[10px] font-normal uppercase tracking-wide text-muted",children:[t.competitorGaps.length," ",t.competitorGaps.length===1?"gap":"gaps"]})]}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Engine"}),e.jsx("th",{children:"Competitors cited"})]})}),e.jsx("tbody",{children:t.competitorGaps.map(s=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:s.query}),e.jsx("td",{children:e.jsx(Xt,{provider:s.provider})}),e.jsx("td",{className:"text-neutral",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Ss="__cited__",ks="__mentioned__",tt="__mentionShare__";function ai(t){const s=t,{dataStartDate:n,dataEndDate:a}=s;return typeof n!="string"||typeof a!="string"?null:{start:lt(n),end:lt(a),sweepCount:s.sweepCount??1}}function Ks(t){const s=ai(t);if(!s)return"Sweep date unavailable";const n=Ct(s.start),a=Ct(s.end);return n===a?n:`${n} – ${a} · ${s.sweepCount} sweeps combined`}function hc(t){const s=ai(t);return s?Ln(s.start):""}function is(t){return t.trim().toLowerCase()}function Sn(t){return Math.round(t*1e3)/10}function kn(t){return t.byProvider??{}}function pc(t,s,n){const a=t.buckets.length>0,i=t.buckets.length===1;if(n==="overall"){const u=s==="cited"?Ss:ks,m=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[u]:Sn(d[m])})),series:[u],hasData:a,singleBucket:i}}const r=s==="mentioned"?"mentionRate":"citationRate",l=[...new Set(t.buckets.flatMap(u=>Object.keys(kn(u))))].sort();return{rows:t.buckets.map(u=>{const m={date:u.startDate},p=kn(u);for(const d of l){const S=p[d];m[d]=S?Sn(S[r]):null}return m}),series:l,hasData:a,singleBucket:i}}function ii(t){const s=t;return Object.hasOwn(s,"modelEvidenceByProvider")?s.modelEvidenceByProvider??{}:null}function gc(t){const s=t;return Object.hasOwn(s,"modelAttribution")?s.modelAttribution??{}:null}function fc(t){return t.servedModelAttribution??{}}function bc(t){return t.modelServiceMismatch??{}}function jc(t){return t.modelPointerChanges??{}}function yc(t){return t.length>0?t.join(", "):null}function xa(t,s){const n=is(s);return Object.entries(t).find(([a])=>is(a)===n)?.[1]}function ht(t){switch(t.status){case"known":return t.model;case"unknown":return"Unknown model";case"mixed":return`Mixed: ${t.models.join(", ")}${t.includesUnknown?" + unknown":""}`}}function vc(t,s){for(let n=t.length-1;n>=0;n-=1){const a=t[n];if(!xa(kn(a),s))continue;const i=ii(a);return i?xa(i,s)??null:null}return null}function Nc(t){const s=new Map;for(const[n,a]of Object.entries(t))for(const i of a.events){const r=s.get(i.bucketStartDate)??[];r.push({provider:n,event:i}),s.set(i.bucketStartDate,r)}return[...s.entries()].sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>({bucketStartDate:n,events:[...a].sort((i,r)=>i.provider.localeCompare(r.provider)||i.event.observedAt.localeCompare(r.event.observedAt))}))}function wc(t){const s={},n=[];for(const[a,i]of Object.entries(t)){const r=i.events.filter(l=>!l.fromPreWindowAnchor);for(const l of i.events)l.fromPreWindowAnchor&&n.push({provider:a,event:l});r.length>0&&(s[a]={...i,events:r})}return{buckets:Nc(s),beforeWindow:n.sort((a,i)=>a.event.observedAt.localeCompare(i.event.observedAt)||a.provider.localeCompare(i.provider))}}function Sc(t){let s=0,n=0;for(const a of Object.values(t))s+=a.events.length,n+=a.eventTotal??a.events.length;return{shown:s,total:n}}function kc(t){const s=[];for(const[n,a]of Object.entries(t)){const i=a.eventTotal??a.events.length;i>a.events.length&&s.push({provider:n,shown:a.events.length,total:i})}return s.sort((n,a)=>n.provider.localeCompare(a.provider))}function Cc(t){const s=t.buckets.map(a=>{const i=a.mentionShare;return{date:a.startDate,[tt]:i?.rate==null?null:Sn(i.rate)}}),n=s.map(a=>a[tt]).filter(a=>typeof a=="number"&&Number.isFinite(a));return{rows:s,series:[tt],hasData:n.length>0,singleBucket:n.length===1}}function Ac(t,s,n){return s==="mentionShare"?Cc(t):pc(t,s,n)}function ha(t,s){for(let n=t.length-1;n>=0;n--){const a=t[n][s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function pa(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function ga(t){return t>0?`+${t}`:`${t}`}function $c(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${ga(n.delta)} on ${pa(n.date)}`).join(", ")}`;const s=[...t].sort((n,a)=>a.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${ga(s.delta)} on ${pa(s.date)})`}const Pc=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Lc=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Dc=[{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:"Of all answer-text brand mentions for you and tracked competitors, the share that were you."}],Tn=He[2],Rc="var(--chart-tooltip-bg)",Ic={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function pt(t){const s=is(t);return Ic[s]??t.charAt(0).toUpperCase()+t.slice(1)}function kt(t){return Math.round(t*10)/10}function Tc(t){return t===Ss||t===ks||t===tt}function ri(t){return t===Ss?"Cited":t===ks?"Mentioned":t===tt?"Mention share":pt(t)}function bs(t,s){return t===Ss?bt.positive:t===ks?He[1]:t===tt?Tn:_o(is(t),s)}function Mc(t,s){for(const n of t){const a=n[s];if(typeof a=="number"&&Number.isFinite(a))return a}return null}function Ec(t){return t.map(s=>s.trim().toLowerCase()).filter(Boolean).sort().join(`
|
|
5
|
-
`)}function qs(t){return t==="cited"?"Cited":t==="mentionShare"?"Mention share":"Mentioned"}function Ns(t){return t==="cited"?"citationRate":"mentionRate"}function oi(t,s){return s==="cited"?t.cited:t.mentionedCount}function li(t,s,n){const a=t.byProvider[s];return a?{count:n==="cited"?a.cited:a.mentionedCount,total:a.total,rate:n==="cited"?a.citationRate:a.mentionRate}:null}function ci(t,s){if(s===void 0)return null;const n=String(s);return t.find(a=>a.startDate===n)??null}function Cn(t){const s=ii(t);if(s===null)return"Model attribution unavailable for this bucket.";const n=Object.entries(s).sort(([a],[i])=>is(a).localeCompare(is(i))).map(([a,i])=>`${pt(a)}: ${ht(i)}`);return n.length>0?`Model evidence: ${n.join("; ")}`:"No model evidence in this bucket."}function Oc(t){return t.some(({event:s})=>s.to.status==="mixed")?bt.caution:t.some(({event:s})=>s.to.status==="unknown")?bt.negative:t.every(({event:s})=>s.from.status==="known"&&s.to.status==="known")?He[4]:bt.positive}function Bc(t,s,n){const a=ci(t,s);return a?Ks(a):Ct(lt(n))}function Fc({partition:t,available:s,counts:n,truncated:a,incompleteHistory:i,served:r,mismatch:l,buckets:h}){const u=o.useId(),m=Object.entries(r).sort(([d],[S])=>d.localeCompare(S)),p=t.buckets.length>0||t.beforeWindow.length>0;return e.jsxs("aside",{className:"trend-model-evidence","aria-labelledby":"trend-model-evidence-title","aria-describedby":u,children:[e.jsxs("div",{className:"trend-model-evidence-head",children:[e.jsx("p",{id:"trend-model-evidence-title",className:"trend-model-evidence-title",children:"Model evidence changes"}),e.jsx("span",{className:"trend-model-evidence-key","aria-hidden":"true",children:"Dashed chart markers"})]}),e.jsxs("p",{id:u,className:"sr-only",children:["Model evidence is recorded from the exact snapshots that produced each trend bucket. It is not the project’s configured provider model.",n.total>0?` ${n.shown} of ${n.total} recorded changes are listed.`:""]}),s?p?e.jsxs(e.Fragment,{children:[t.buckets.length>0&&e.jsx("ul",{className:"trend-model-evidence-list",children:t.buckets.flatMap(({bucketStartDate:d,events:S})=>S.map(({provider:f,event:C})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Bc(h,d,C.observedAt)}),e.jsxs("span",{children:[pt(f),": ",ht(C.from)," → ",ht(C.to)]})]},`${f}-${C.observedAt}-${C.bucketStartDate}`)))}),t.beforeWindow.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"Changed before this date range"}),e.jsx("ul",{className:"trend-model-evidence-list",children:t.beforeWindow.map(({provider:d,event:S})=>e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsxs("span",{className:"trend-model-evidence-date",children:["on or before ",Ct(lt(S.observedAt))]}),e.jsxs("span",{children:[pt(d),": ",ht(S.from)," → ",ht(S.to),S.anchorObservedAt?` (last seen ${ht(S.from)} on ${Ct(lt(S.anchorObservedAt))})`:""]})]},`before-${d}-${S.observedAt}`))})]}),a.map(d=>e.jsxs("p",{className:"trend-model-evidence-note",children:[pt(d.provider),": showing the most recent ",d.shown," of ",d.total," changes."]},`truncated-${d.provider}`)),i.map(d=>e.jsxs("p",{className:"trend-model-evidence-note",children:["We did not look far enough back to be sure this is every ",pt(d)," change."]},`incomplete-${d}`))]}):e.jsx("p",{className:"trend-model-evidence-empty",children:"No model evidence changes in this window."}):e.jsx("p",{className:"trend-model-evidence-empty",children:"Attribution unavailable from this API version."}),m.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"trend-model-evidence-note",children:"What the engines answered with"}),e.jsx("ul",{className:"trend-model-evidence-list",children:m.map(([d,S])=>{const f=yc(S.latestServedModelIds),C=l[d];return e.jsxs("li",{className:"trend-model-evidence-item",children:[e.jsx("span",{className:"trend-model-evidence-date",children:Ct(lt(S.latestObservation.observedAt))}),e.jsxs("span",{children:[pt(d),": ",f??ht(S.latestObservation.state),C?` — not the ${ht(C.configured)} you selected`:""]})]},`served-${d}`)})})]})]})}function fa(t){return t===null?"no data":`${t}%`}function ln(t){return t==null?"undefined":`${kt(t*100)}%`}function _c({active:t,label:s,payload:n,metric:a,mode:i,buckets:r}){if(!t)return null;const l=ci(r,s);if(!l)return null;if(a==="mentionShare"){const u=l.mentionShare.projectMentionSnapshots,m=l.mentionShare.competitorMentionSnapshots,p=u+m,d=l.mentionShare.rate==null?null:kt(l.mentionShare.rate*100);return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ks(l)}),e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch trend-tooltip-swatch-ring",style:{borderColor:Tn},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:"Mention share"}),e.jsx("span",{className:"trend-tooltip-value",children:fa(d)})]}),p>0?e.jsxs("p",{className:"trend-tooltip-detail",children:["You ",u," / ",p," brand mentions. Competitors ",m,"."]}):e.jsx("p",{className:"trend-tooltip-detail",children:"No project or competitor brand mentions in this bucket."}),e.jsx("p",{className:"trend-tooltip-detail",children:Cn(l)})]})}const h=i==="byProvider"?(n??[]).filter(u=>u.dataKey!==void 0):[{dataKey:a==="cited"?Ss:ks,value:kt(l[Ns(a)]*100)}];return e.jsxs("div",{className:"trend-tooltip",children:[e.jsx("p",{className:"trend-tooltip-label",children:Ks(l)}),h.map((u,m)=>{const p=String(u.dataKey??u.name??""),d=i==="byProvider"?li(l,p,a):null,S=d?.count??oi(l,a),f=d?.total??l.total,C=typeof u.value=="number"?u.value:kt(d?d.rate*100:l[Ns(a)]*100),N=u.color??bs(p,m);return e.jsxs("div",{className:"trend-tooltip-block",children:[e.jsxs("div",{className:"trend-tooltip-row",children:[e.jsx("span",{className:"trend-tooltip-swatch",style:{backgroundColor:N},"aria-hidden":"true"}),e.jsx("span",{className:"trend-tooltip-name",children:ri(p)}),e.jsx("span",{className:"trend-tooltip-value",children:fa(C)})]}),e.jsxs("p",{className:"trend-tooltip-detail",children:[S," / ",f," snapshots, ",a==="cited"?"source links":"answer text"]})]},`${p}-${m}`)}),e.jsx("p",{className:"trend-tooltip-detail",children:Cn(l)})]})}function qc({buckets:t,metric:s,mode:n,series:a}){return e.jsxs("table",{className:"sr-only",children:[e.jsxs("caption",{children:[qs(s)," trend data"]}),e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Bucket"}),e.jsx("th",{scope:"col",children:"Values"})]})}),e.jsx("tbody",{children:t.map(i=>{let r;if(s==="mentionShare"){const l=i.mentionShare.projectMentionSnapshots,h=i.mentionShare.competitorMentionSnapshots,u=l+h;r=u>0?`${ln(i.mentionShare.rate)} mention share, ${l} of ${u} brand mentions were you`:"mention share undefined, no project or competitor brand mentions"}else n==="byProvider"?r=a.map(l=>{const h=li(i,l,s);return h?`${pt(l)} ${ln(h.rate)} ${qs(s).toLowerCase()}, ${h.count} of ${h.total} snapshots`:`${pt(l)} no data`}).join("; "):r=`${ln(i[Ns(s)])} ${qs(s).toLowerCase()}, ${oi(i,s)} of ${i.total} snapshots`;return r+=`; ${Cn(i)}`,e.jsxs("tr",{children:[e.jsx("th",{scope:"row",children:Ks(i)}),e.jsx("td",{children:r})]},i.startDate)})})]})}function cn({options:t,value:s,onChange:n,ariaLabel:a,className:i}){const r=o.useId();return e.jsx("div",{role:"group","aria-label":a,className:`segmented ${i??""}`,children:t.map(l=>{const h=s===l.value,u=l.description?`${r}-${l.value}-description`:void 0;return e.jsxs(o.Fragment,{children:[e.jsx("button",{type:"button","aria-pressed":h,"aria-describedby":u,className:`segmented-option ${h?"segmented-option-active":""}`,onClick:()=>n(l.value),children:l.label}),l.description&&e.jsx("span",{id:u,className:"sr-only",children:l.description})]},l.value)})})}function Gc({projectName:t,competitorDomains:s=[],analyticsRevision:n="none"}){const[a,i]=o.useState("all"),[r,l]=o.useState("mentioned"),[h,u]=o.useState("byProvider"),m=o.useMemo(()=>Ec(s),[s]),p=ve({queryKey:["analytics-metrics",t,a,m,n],queryFn:()=>kr(t,a),staleTime:Ma}),d=p.data??null,S=p.error,f=r==="mentionShare"?"overall":h,C=o.useMemo(()=>d?Ac(d,r,f):null,[d,r,f]),N=d?gc(d):null,b=o.useMemo(()=>wc(N??{}),[N]),I=o.useMemo(()=>Sc(N??{}),[N]),G=o.useMemo(()=>kc(N??{}),[N]),M=o.useMemo(()=>Object.entries(N??{}).filter(([,H])=>H.anchorUnavailable).map(([H])=>H).sort(),[N]),z=o.useMemo(()=>d?fc(d):{},[d]),x=o.useMemo(()=>d?bc(d):{},[d]),A=o.useMemo(()=>d?Cr(jc(d)):null,[d]),_=r!=="mentionShare"&&f==="byProvider",ee=qs(r),oe=r==="cited"?bt.positive:r==="mentionShare"?Tn:He[1],y=_?Ve.textDim:oe,g=d?.buckets??[],K=o.useMemo(()=>{const H=new Map(g.map(xe=>[xe.startDate,hc(xe)]));return xe=>H.get(String(xe))??""},[g]),$=r==="mentionShare"?C?ha(C.rows,tt):null:g.length>0?kt(g[g.length-1][Ns(r)]*100):null,q=r==="mentionShare"?C?Mc(C.rows,tt):null:g.length>0?kt(g[0][Ns(r)]*100):null,Z=r==="mentionShare"?C?.rows.filter(H=>typeof H[tt]=="number").length??0:g.length,le=$!==null&&q!==null&&Z>1?kt($-q):null,te=s.length,fe=e.jsxs(e.Fragment,{children:[A?.kind==="change"&&e.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:A.text}),e.jsxs("div",{className:"visibility-trend-head",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsxs("h2",{className:"visibility-trend-title",children:["Answer-engine trend",e.jsx(Te,{text:"Three separate signals over sweep buckets: answer text mentions, source citations, and your answer-text mention share against tracked competitors. Mentioned and Cited use query-provider snapshot rates; Mention share uses project plus competitor brand mentions."})]})]}),$!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:y},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:ee}),_&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[$,"%"]}),le!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${le>0?"text-positive-400":le<0?"text-negative-400":"text-muted"}`,children:[le>0?"+":"",le.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(cn,{options:Dc,value:r,onChange:l,ariaLabel:"Metric",className:"visibility-trend-metric-control"}),r!=="mentionShare"&&e.jsx(cn,{options:Lc,value:h,onChange:u,ariaLabel:"Series"}),e.jsx(cn,{options:Pc,value:a,onChange:i,ariaLabel:"Time window",className:"sm:ml-auto"})]}),A?.kind==="no-known-change"&&e.jsxs("p",{className:"mt-3 text-[11px] leading-snug text-muted",children:[A.text,e.jsx(Te,{text:A.detail})]})]});let ue;if(S)ue=e.jsx("p",{className:"text-sm text-negative-400",children:S instanceof Error?S.message:String(S)});else if(p.isLoading&&!d)ue=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-bg-elevated/40","aria-hidden":"true"});else if(r==="mentionShare"&&te===0)ue=e.jsx("p",{className:"text-sm text-secondary",children:"Add tracked competitors to measure mention share over time."});else if(!d||!C)ue=null;else{const{rows:H,series:xe,hasData:k,singleBucket:B}=C,v=$c(d.queryChanges);if(!k)ue=e.jsx("p",{className:"text-sm text-secondary",children:r==="mentionShare"?"No answer-text brand mentions for you or tracked competitors in this window yet.":"Run a sweep to start tracking citations and mentions over time."});else if(_&&xe.length===0)ue=e.jsxs("p",{className:"text-sm text-secondary",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-strong",children:"All engines"})," to see the trend."]});else{const J=`${ee} rate across ${H.length} ${H.length===1?"sweep":"sweeps"}. Latest ${$}%${le!==null?`, ${le>=0?"up":"down"} ${Math.abs(le).toFixed(1)} points over the period`:""}.`;ue=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:J}),e.jsx(qc,{buckets:g,metric:r,mode:f,series:xe}),_&&xe.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:xe.map((F,ce)=>{const P=ha(H,F),U=vc(g,F),we=N===null?"Attribution unavailable":U?ht(U):"No observed model evidence";return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:bs(F,ce)},"aria-hidden":"true"}),e.jsxs("span",{className:"trend-legend-label",children:[e.jsx("span",{className:"trend-legend-name",children:ri(F)}),e.jsxs("span",{className:"trend-legend-model",children:[e.jsx("span",{"aria-hidden":"true",children:"· "}),we]})]}),P!==null&&e.jsxs("span",{className:"trend-legend-value",children:[P,"%"]})]},F)})}),e.jsx("div",{className:"visibility-trend-chart",role:"img","aria-label":`${ee} trend chart over ${H.length} ${H.length===1?"bucket":"buckets"}`,children:e.jsx(Zt,{width:"100%",height:"100%",children:e.jsxs(es,{data:H,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Dn,{stroke:Pn,vertical:!1}),e.jsx(ts,{dataKey:"date",tick:st,tickLine:!1,axisLine:{stroke:jt},tickFormatter:K,minTickGap:24}),e.jsx(ss,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:F=>`${F}%`,tick:st,tickLine:!1,axisLine:!1,width:40}),e.jsx(ns,{cursor:{stroke:jt,strokeWidth:1},content:e.jsx(_c,{metric:r,mode:f,buckets:g})}),b.buckets.map(({bucketStartDate:F,events:ce})=>e.jsx(Qo,{x:F,stroke:Oc(ce),strokeDasharray:"4 4",strokeWidth:1.5,ifOverflow:"extendDomain"},`model-evidence-${F}`)),xe.map((F,ce)=>e.jsx(Rn,{type:"monotone",dataKey:F,name:F,stroke:bs(F,ce),strokeDasharray:F===tt?"5 4":void 0,strokeWidth:Tc(F)?2.5:2,dot:F===tt?{r:2.75,fill:"var(--chart-tooltip-bg)",stroke:bs(F,ce),strokeWidth:1.5}:{r:2.5,fill:bs(F,ce),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Rc},connectNulls:F!==tt,isAnimationActive:!1},F))]})})}),e.jsx(Fc,{partition:b,available:N!==null,counts:I,truncated:G,incompleteHistory:M,served:z,mismatch:x,buckets:g}),B&&e.jsx("p",{className:"visibility-trend-note",children:r==="mentionShare"?"Only one competitive mention-share point so far. The trend line fills in after another sweep with brand mentions.":"Only one sweep so far. The trend line fills in after the next run."}),v&&e.jsx("p",{className:"visibility-trend-note",children:v})]})}}return e.jsxs("section",{className:"visibility-trend",children:[fe,ue]})}const ba=new Set([js.queued,js.running]);function Uc({projectName:t}){const s=At(),[n,a]=o.useState(""),[i,r]=o.useState(""),[l,h]=o.useState(""),[u,m]=o.useState("__default__"),[p,d]=o.useState(null),S=ve({...Ar({client:W,path:{name:t}}),staleTime:6e4}),f=ve({...Ea({client:W}),staleTime:6e4}),C=ve({...$r({client:W,path:{name:t},query:{limit:20}}),refetchInterval:y=>y.state.data?.runs.some(g=>ba.has(g.status))?3e3:!1}),N=C.data?.runs??[];o.useEffect(()=>{!p&&N[0]&&d(N[0].id)},[N,p]);const b=N.find(y=>y.id===p)??null,I=ve({...Pr({client:W,path:{name:t,runId:p??""}}),enabled:!!p,refetchInterval:b&&ba.has(b.status)?3e3:!1}),G=I.data??null,M=o.useMemo(()=>Kc(n),[n]),z=S.data?.locations??[],x=o.useMemo(()=>{const y=new Map((f.data?.providerCatalog??[]).map(g=>[g.name,g]));return(f.data?.providers??[]).filter(g=>g.configured&&y.get(g.name)?.mode==="api").map(g=>({...g,catalog:y.get(g.name)}))},[f.data]),A=!f.isLoading&&x.length===0,_=x.find(y=>y.name===i)??null;o.useEffect(()=>{i&&!_&&(r(""),h(""))},[i,_]);const ee=vs({...Lr(),onSuccess:async y=>{d(y.id),a(""),h(""),await Yc(s),Y({title:"Research batch saved",detail:`${y.totalQueries} quer${y.totalQueries===1?"y is":"ies are"} in research history. Nothing was added to tracked queries.`,tone:"positive",dedupeKey:`research:start:${y.id}`,dedupeMode:"replace"})},onError:y=>{Y({title:"Could not start research",detail:y instanceof Error?y.message:"Check the provider, model, and location, then try again.",tone:"negative"})}});function oe(){if(M.length===0||M.length>50||A||ee.isPending||T())return;const y=u==="__default__"?void 0:u==="__none__"?null:z.find(g=>g.label===u)??void 0;ee.mutate({client:W,path:{name:t},body:{queries:M,...i?{provider:i}:{},...i&&l.trim()?{model:l.trim()}:{},...y!==void 0?{location:y}:{}}})}return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.85fr)_minmax(360px,1.15fr)]",children:[e.jsxs(V,{className:"surface-card",children:[e.jsx("div",{className:"section-head",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"New batch"}),e.jsx("h3",{children:"Research queries"}),e.jsx("p",{className:"mt-1 max-w-xl text-sm leading-6 text-muted",children:"Run specific questions against one API model and keep the answers as a separate research record."})]})}),e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("label",{className:"block",htmlFor:"research-queries",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Queries"}),e.jsx("textarea",{id:"research-queries",className:"mt-1 min-h-36 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:`one query per line
|
|
6
|
-
e.g. What is the best way to choose an AEO platform?`,value:n,onChange:y=>a(y.target.value),"aria-describedby":"research-query-count"}),e.jsxs("span",{id:"research-query-count",className:`mt-1 block text-[11px] ${M.length>50?"text-negative":"text-faint"}`,children:[M.length," ",M.length===1?"query":"queries",", duplicates and blank lines are removed. Maximum 50."]})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"block",htmlFor:"research-provider",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"API provider"}),e.jsxs("select",{id:"research-provider",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:i,onChange:y=>{r(y.target.value),h("")},children:[e.jsx("option",{value:"",children:"Project default"}),x.map(y=>e.jsx("option",{value:y.name,children:y.displayName??y.name},y.name))]})]}),e.jsxs("label",{className:"block",htmlFor:"research-location",children:[e.jsx("span",{className:"text-xs font-medium text-secondary",children:"Location"}),e.jsxs("select",{id:"research-location",className:"mt-1 w-full rounded border border-strong bg-transparent px-3 py-2 text-sm text-strong focus:border-mono-500 focus:outline-none",value:u,onChange:y=>m(y.target.value),children:[e.jsx("option",{value:"__default__",children:"Project default"}),e.jsx("option",{value:"__none__",children:"No location"}),z.map(y=>e.jsx("option",{value:y.label,children:y.label},y.label))]})]})]}),e.jsxs("label",{className:"block",htmlFor:"research-model",children:[e.jsxs("span",{className:"text-xs font-medium text-secondary",children:["Exact model ",e.jsx("span",{className:"font-normal text-muted",children:"(optional)"})]}),e.jsx("input",{id:"research-model",list:"research-known-models",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 disabled:cursor-not-allowed disabled:opacity-50",placeholder:_?`Default: ${_.model??_.defaultModel??_.catalog.defaultModel}`:"Choose a provider to select an exact model",value:l,disabled:!_,onChange:y=>h(y.target.value)}),e.jsx("datalist",{id:"research-known-models",children:(_?.catalog.knownModels??[]).map(y=>e.jsx("option",{value:y.id,children:y.displayName},y.id))})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-t border-default pt-4",children:[!T()&&e.jsxs(R,{type:"button",size:"sm",disabled:M.length===0||M.length>50||A||ee.isPending,onClick:oe,children:[e.jsx(Ot,{size:14}),ee.isPending?"Starting research…":`Run ${M.length||""} research ${M.length===1?"query":"queries"}`]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Saved to research history. Nothing is added to tracked queries."})]}),A&&e.jsx("p",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:"Configure an API provider in Settings before starting research. Browser engines are not available for this workflow."})]})]}),e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Saved research batches"})]}),C.isFetching&&e.jsx(ae,{tone:"neutral",children:"Loading"})]}),N.length===0?e.jsx("p",{className:"mt-4 text-sm text-muted",children:"No research batches yet. Add one or more questions to begin."}):e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Run"}),e.jsx("th",{children:"Model"}),e.jsx("th",{children:"Location"}),e.jsx("th",{children:"Progress"}),e.jsx("th",{children:"Status"})]})}),e.jsx("tbody",{children:N.map(y=>e.jsxs("tr",{className:p===y.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>d(y.id),children:Hc(y.createdAt)})}),e.jsxs("td",{className:"text-secondary",children:[e.jsx("span",{className:"block",children:y.provider}),e.jsx("span",{className:"font-mono text-[11px] text-muted",children:y.requestedModel??y.resolvedModel})]}),e.jsx("td",{className:"text-secondary",children:y.location?.label??"No location"}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[y.completedQueries+y.failedQueries,"/",y.totalQueries]}),e.jsx("td",{children:e.jsx(ae,{tone:di(y.status),children:y.status})})]},y.id))})]})})]})]}),e.jsx(Qc,{detail:G,isLoading:I.isFetching})]})}function Qc({detail:t,isLoading:s}){const[n,a]=o.useState(null);o.useEffect(()=>{a(t?.queries[0]?.id??null)},[t?.id]);const i=t?.queries.find(r=>r.id===n)??t?.queries[0]??null;return e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Results"}),e.jsx("h3",{children:t?`Research run ${Vc(t.id)}`:"Choose a research batch"})]}),t&&e.jsx(ae,{tone:di(t.status),children:t.status})]}),t?e.jsxs("div",{className:"mt-4 grid gap-4 xl:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)]",children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"evidence-table min-w-[680px]",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Mentioned"}),e.jsx("th",{children:"Cited"})]})}),e.jsx("tbody",{children:t.queries.map(r=>e.jsxs("tr",{className:i?.id===r.id?"bg-bg-elevated/40":void 0,children:[e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-left font-medium text-heading hover:text-link focus:outline-none focus:underline",onClick:()=>a(r.id),children:r.query})}),e.jsx("td",{children:e.jsx(ae,{tone:Wc(r.status),children:r.status})}),e.jsx("td",{children:e.jsx(ae,{tone:r.answerMentioned===!0?"positive":r.answerMentioned===!1?"neutral":r.status===Et.failed?"negative":"caution",children:r.answerMentioned===null?r.status===Et.failed?"Unavailable":"Pending":r.answerMentioned?"Mentioned":"Not mentioned"})}),e.jsx("td",{children:e.jsx(ae,{tone:r.citationState==="cited"?"positive":r.citationState==="not-cited"?"neutral":r.status===Et.failed?"negative":"caution",children:r.citationState===null?r.status===Et.failed?"Unavailable":"Pending":r.citationState==="cited"?"Cited":"Not cited"})})]},r.id))})]})}),e.jsx(zc,{query:i,isLoading:s})]}):e.jsx("p",{className:"mt-4 text-sm text-muted",children:"Select a saved batch to inspect each answer and its source links."})]})}function zc({query:t,isLoading:s}){return t?e.jsxs("div",{className:"space-y-4 border-t border-default pt-4 xl:border-t-0 xl:border-l xl:pl-4 xl:pt-0",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Selected query"}),e.jsx("p",{className:"mt-1 text-sm font-medium leading-6 text-heading",children:t.query})]}),t.error?e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:t.error}):t.answerText?e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Answer"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-sm leading-6 text-secondary",children:t.answerText})]}):e.jsx("p",{className:"text-sm text-muted",children:t.status===Et.failed?"This query did not return an answer.":"The answer will appear here when this query finishes."}),t.namedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Named in answer"}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.namedCompetitors.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n},n))})]}),t.citedCompetitorDomains.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Cited competitor domains"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-muted",children:"Cited as a source, not merely named in the answer."}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:t.citedCompetitorDomains.map(n=>e.jsx("span",{className:"mention-chip mention-chip--competitor",children:n.replace(/^www\./,"")},n))})]}),t.groundingSources.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Source links"}),e.jsx("ul",{className:"mt-2 space-y-1",children:t.groundingSources.map((n,a)=>{const i=It(n.uri),r=n.title||n.uri;return e.jsxs("li",{className:"flex min-w-0 items-start gap-1.5 text-sm",children:[i?e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",className:"truncate text-secondary hover:text-link focus:outline-none focus:underline",children:r}):e.jsx("span",{className:"truncate text-secondary",children:r}),i&&e.jsx(Ko,{className:"mt-0.5 size-3 shrink-0 text-muted","aria-hidden":"true"})]},`${n.uri}-${a}`)})})]})]}):e.jsx("p",{className:"text-sm text-muted",children:s?"Loading saved answers…":"Select a query to inspect its answer."})}function Kc(t){const s=new Set;return t.split(/\r?\n/).map(n=>n.trim()).filter(n=>{const a=n.toLocaleLowerCase();return!n||s.has(a)?!1:(s.add(a),!0)})}function Hc(t){const s=new Date(t);return Number.isNaN(s.valueOf())?t:new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(s)}function Vc(t){return t.length>8?t.slice(0,8):t}function di(t){return t===js.completed?"positive":t===js.partial?"caution":t===js.failed?"negative":"neutral"}function Wc(t){return t===Et.completed?"positive":t===Et.failed?"negative":"neutral"}async function Yc(t){await t.invalidateQueries({predicate:s=>{const n=s.queryKey[0];return typeof n?._id=="string"&&n._id.startsWith("getApiV1ProjectsByNameResearchRuns")}})}const An=new Set(["queued","seeding","probing"]);function Jc({projectName:t}){const[s,n]=o.useState("find");return e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query discovery"}),e.jsx("h2",{children:"Explore the questions that matter"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-muted",children:"Find query ideas from an ideal customer profile, or run a focused research batch without changing what this project tracks."})]})}),e.jsxs("div",{className:"inline-flex rounded-md border border-default bg-surface p-1",role:"tablist","aria-label":"Query discovery workflow",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":s==="find",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="find"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("find"),children:"Find queries"}),e.jsx("button",{type:"button",role:"tab","aria-selected":s==="research",className:`rounded px-3 py-1.5 text-sm font-medium transition-colors ${s==="research"?"bg-bg-elevated text-heading shadow-sm":"text-muted hover:text-strong"}`,onClick:()=>n("research"),children:"Research queries"})]}),e.jsx("div",{className:"mt-4",children:s==="find"?e.jsx(Xc,{projectName:t}):e.jsx(Uc,{projectName:t})})]})}function Xc({projectName:t}){const s=At(),[n,a]=o.useState(null),[i,r]=o.useState(""),[l,h]=o.useState("100"),u=ve({...Dr({client:W,path:{name:t},query:{limit:"10"}}),refetchInterval:x=>x.state.data?.some(_=>An.has(_.status))?3e3:!1}),m=u.data??[];o.useEffect(()=>{!n&&m[0]&&a(m[0].id)},[n,m]);const p=m.find(x=>x.id===n)??null,d=ve({...Rr({client:W,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:p&&An.has(p.status)?3e3:!1}),S=d.data??null,f=ve({...Ir({client:W,path:{name:t,id:n??""}}),enabled:!!(n&&p?.status==="completed")}),C=vs({mutationFn:()=>{const x={},A=i.trim();A&&(x.icpDescription=A);const _=Number.parseInt(l,10);return Number.isFinite(_)&&_>0&&(x.maxProbes=_),Tr(t,x)},onSuccess:async x=>{a(x.sessionId),r(""),await ya(s,t,x.sessionId),Y({title:"Discovery started",detail:`Run ${dn(x.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${x.sessionId}`,dedupeMode:"replace"})},onError:x=>{Y({title:"Discovery failed to start",detail:x instanceof Error?x.message:"Could not start discovery.",tone:"negative"})}}),N=vs({mutationFn:x=>{if(!n)throw new Error("Select a completed discovery session first.");return Mr(t,n,x)},onSuccess:async x=>{await ya(s,t,x.sessionId),s.invalidateQueries({queryKey:Oa({client:W})}),s.invalidateQueries({predicate:A=>Array.isArray(A.queryKey)&&A.queryKey[0]==="projects"&&A.queryKey.length>1}),Y({title:"Queries added",detail:sd(x),tone:"positive",dedupeKey:`discovery:promote:${x.sessionId}`,dedupeMode:"replace"})},onError:x=>{Y({title:"Could not add queries",detail:x instanceof Error?x.message:"Could not add queries from this run.",tone:"negative"})}}),b=S??p,I=f.data??null,G=(I?.queriesByBucket.cited.length??0)+(I?.queriesByBucket.aspirational.length??0),M=o.useMemo(()=>(S?.probes??[]).slice(0,30),[S?.probes]);async function z(){try{const x=await u.refetch();if(x.error)throw x.error;const A=x.data?.length??0;Y({title:"Discovery sessions refreshed",detail:`${A} recent session${A===1?"":"s"} loaded.`,tone:"positive",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}catch(x){Y({title:"Discovery refresh failed",detail:x instanceof Error?x.message:"Could not reload discovery sessions.",tone:"negative",dedupeKey:`discovery:refresh:${t}`,dedupeMode:"replace"})}}return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Find queries"}),e.jsx("h2",{children:"Find new queries to track"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-muted",children:T()?"Generated questions your ideal customers would ask an AI engine, with a check of which ones already cite your site.":"Describe your ideal customer and Canonry generates the questions they would ask an AI engine, checks which ones already cite your site, then lets you add the promising ones to your tracked queries."})]}),e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:u.isFetching,onClick:()=>{z()},children:[e.jsx(gt,{className:`size-3.5 ${u.isFetching?"animate-spin":""}`,"aria-hidden":"true"}),"Refresh"]})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[360px_minmax(0,1fr)]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 1"}),e.jsx("h3",{children:"Describe your customer"})]}),e.jsx(ae,{tone:"neutral",children:"Runs on Gemini"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-muted",children:"Who is your ideal customer?"}),e.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:i,onChange:x=>r(x.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-muted",children:"How many questions to test"}),e.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:l,onChange:x=>h(x.target.value)}),e.jsx("span",{className:"mt-1 block text-[11px] text-faint",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),!T()&&e.jsxs(R,{type:"button",size:"sm",disabled:C.isPending,onClick:()=>C.mutate(),children:[e.jsx(Ot,{size:14}),C.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"History"}),e.jsx("h3",{children:"Recent runs"})]}),u.isFetching&&e.jsx(ae,{tone:"neutral",children:"Loading"})]}),m.length===0?e.jsx("p",{className:"text-sm text-muted",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:m.map(x=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===x.id?"border-mono-600 bg-bg-elevated/70":"border-default bg-bg/40 hover:border-strong hover:bg-bg-elevated/40"}`,onClick:()=>a(x.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:dn(x.id)}),e.jsx(ae,{tone:ja(x.status),children:x.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-[11px] text-muted",children:[e.jsxs("span",{children:["Cited ",x.citedCount??0]}),e.jsxs("span",{children:["Opportunity ",x.aspirationalCount??0]}),e.jsxs("span",{children:["Low value ",x.wastedCount??0]})]})]},x.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Run detail"}),e.jsx("h3",{children:b?dn(b.id):"No run selected"})]}),b&&e.jsx(ae,{tone:ja(b.status),children:b.status})]}),b?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(wt,{label:"Questions tested",value:b.probeCount??0}),e.jsx(wt,{label:"Already cited",value:b.citedCount??0,tone:"positive"}),e.jsx(wt,{label:"Opportunities",value:b.aspirationalCount??0,tone:"caution"}),e.jsx(wt,{label:"Low value",value:b.wastedCount??0,tone:"negative"})]}),b.error&&e.jsx("div",{className:"rounded-md border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:b.error}),b.warning&&e.jsx("div",{className:"rounded-md border border-caution-800/40 bg-caution-950/20 px-3 py-2 text-sm text-caution",children:b.warning}),b.icpDescription&&e.jsxs("div",{className:"rounded-md border border-default bg-surface px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-neutral",children:b.icpDescription})]}),b.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:b.competitorMap.slice(0,8).map(x=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[x.domain," ",e.jsx("span",{className:"text-muted",children:x.hits})]},x.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),b?.status==="completed"&&e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Step 2"}),e.jsx("h3",{children:"Add queries to your project"})]}),!T()&&e.jsxs(R,{type:"button",size:"sm",disabled:N.isPending||G===0,onClick:()=>N.mutate(void 0),children:[e.jsx(Qa,{size:14}),N.isPending?"Adding…":"Add recommended queries"]})]}),f.isLoading?e.jsx("p",{className:"text-sm text-muted",children:"Loading recommendations…"}):I?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(wt,{label:"Queries to add",value:G,tone:"positive"}),e.jsx(wt,{label:"Already cited",value:I.queriesByBucket.cited.length,tone:"positive"}),e.jsx(wt,{label:"Opportunities",value:I.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(wt,{label:"Low value (skipped)",value:I.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-xs leading-5 text-muted",children:"Adding queries starts tracking the “already cited” and “opportunity” questions, plus any competitor sites that kept showing up. “Low value” questions are listed below for reference only and are not added."}),I.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-secondary",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:I.suggestedCompetitors.map(x=>e.jsxs("span",{className:"rounded-md border border-default bg-bg px-2 py-1 text-xs text-neutral",children:[x.domain," ",e.jsx("span",{className:"text-muted",children:x.hits})]},x.domain))})]})]}):e.jsx("p",{className:"text-sm text-muted",children:"No recommendations available for this run."})]}),e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"All results"}),e.jsx("h3",{children:"Every question we tested"})]}),d.isFetching&&e.jsx(ae,{tone:"neutral",children:"Loading"})]}),M.length===0?e.jsx("p",{className:"text-sm text-muted",children:"Results show up here once the run starts testing questions."}):e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Question"}),e.jsx("th",{children:"Result"}),e.jsx("th",{children:"Sites cited"})]})}),e.jsx("tbody",{children:M.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-heading",children:x.query}),e.jsx("td",{children:e.jsx(ae,{tone:Zc(x.bucket),children:td(x.bucket)})}),e.jsx("td",{className:"text-secondary",children:x.citedDomains.length>0?x.citedDomains.slice(0,3).join(", "):"-"})]},x.id))})]})})]})]})]})]})}function wt({label:t,value:s,tone:n="neutral"}){const a=n==="positive"?"text-positive":n==="caution"?"text-caution":n==="negative"?"text-negative":"text-heading";return e.jsxs("div",{className:"rounded-md border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-muted",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s})]})}function ja(t){return t==="completed"?"positive":t==="failed"?"negative":An.has(t)?"caution":"neutral"}function Zc(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const ed={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function td(t){return t?ed[t]:"Not classified"}function dn(t){return t.length>8?t.slice(0,8):t}function sd(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,a=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${a>0?`; ${a} already tracked`:""}.`}async function ya(t,s,n){await Promise.all([t.invalidateQueries({predicate:a=>{const i=a.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith("getApiV1ProjectsByNameDiscover")}}),t.invalidateQueries({queryKey:Er({client:W})})])}const nd=100,un=12;function mn(t){return t>=70?"positive":t>=40?"caution":"negative"}function xn(t){return t>=70?"text-positive-400":t>=40?"text-caution-400":"text-negative-400"}function ad(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function Fs(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function id(t){return Ln(lt(String(t)))}function rd(t){return Ct(lt(String(t)))}function od({projectName:t,projectId:s}){const[n,a]=o.useState(!1),[i,r]=o.useState(null),[l,h]=o.useState(null),[u,m]=o.useState(!1),p=o.useRef(null),d=ve(Or({client:W,path:{name:t},...l?{query:{runId:l}}:{}})),S=ve(Br({client:W,path:{name:t},query:{limit:30}})),f=ve(Fr({client:W,path:{name:t},query:{limit:nd,sort:"score-asc",...l?{runId:l}:{}}})),C=ve({...Ba({client:W,path:{name:t},query:{kind:Ft["site-audit"],limit:10}}),refetchOnWindowFocus:"always",refetchInterval:v=>v.state.data?.some(F=>F.status==="queued"||F.status==="running")?3e3:1e4}),N=_r(),b=o.useSyncExternalStore(Ra,Gs,Gs),I=Object.values(b.runs).find(v=>v.kind===Ft["site-audit"]&&v.projectId===s),G=C.data??[],M=G.find(v=>v.status==="queued"||v.status==="running"),z=G.at(-1),x=N.isPending||!!I||!!M,A=N.isPending?"starting":M?.status??I?.lastAnnouncedStatus,_=o.useCallback(async()=>{const v=await Promise.all([d.refetch(),S.refetch(),f.refetch()]),J=v.find(F=>F.error);if(J?.error)throw J.error;return v[0]},[f.refetch,d.refetch,S.refetch]);o.useEffect(()=>{l||!z||z.status!=="completed"&&z.status!=="partial"||d.data?.runId===z.id||p.current===z.id||(p.current=z.id,_().catch(v=>{Y({title:"Technical AEO auto-refresh failed",detail:v instanceof Error?v.message:"Could not load the completed audit.",tone:"negative",dedupeKey:`technical-aeo:auto-refresh:${t}`,dedupeMode:"replace"})}))},[z?.id,z?.status,t,_,d.data?.runId,l]);const ee=async()=>{m(!0);try{const v=await _();Y({title:"Technical AEO refreshed",detail:x?"The audit is still running. This view will refresh again when it finishes.":v.data?.hasData?`Latest score is ${v.data.aggregateScore}/100 from ${v.data.pagesAudited} audited page${v.data.pagesAudited===1?"":"s"}.`:"No audit data yet. Run an audit to crawl the sitemap.",tone:v.data?.hasData?"positive":"caution",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}catch(v){Y({title:"Technical AEO refresh failed",detail:v instanceof Error?v.message:"Could not reload technical audit data.",tone:"negative",dedupeKey:`technical-aeo:refresh:${t}`,dedupeMode:"replace"})}finally{m(!1)}},oe=()=>N.mutate({projectName:t,projectId:s}),y=A==="running"?"Audit running":A==="queued"?"Audit queued":"Starting audit",g=d.data;if(o.useEffect(()=>{a(!1),r(null)},[l]),d.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!g||!g.hasData)return e.jsxs(V,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Xo,{className:"mx-auto mb-3 h-8 w-8 text-muted","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-heading",children:"No technical audit yet"}),e.jsx("p",{className:"supporting-copy mx-auto mt-2 max-w-md",children:"A technical AEO audit crawls your sitemap and scores every page for structured data, AI-readable content, crawler access, freshness, and more, then rolls it up into one site score."}),!T()&&e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(R,{type:"button",onClick:oe,disabled:x,children:[x?e.jsx(jn,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ot,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),x?y:"Run first audit"]})}),x?e.jsx("p",{className:"mt-3 text-xs text-muted",role:"status","aria-live":"polite",children:"The dashboard will refresh automatically when the audit finishes."}):null,e.jsxs("p",{className:"mt-3 text-xs text-faint",children:["Or from the CLI: ",e.jsxs("code",{className:"text-secondary",children:["canonry technical-aeo run ",t," --wait"]})]})]});const K=g.deltaScore==null?null:`${g.deltaScore>=0?"+":""}${g.deltaScore} vs previous`,$=g.trend==="up"?"positive":g.trend==="down"?"negative":"neutral",q=S.data?.points??[],Z=q.map(v=>({runId:v.runId,date:v.auditedAt,score:v.aggregateScore})),le=l!==null,te=f.data?.pages??[],fe=te.filter(v=>v.status==="success"),ue=g.pagesErrored>0,H=n&&ue,xe=H?te.filter(v=>v.status==="error"):te,k=g.pagesAudited>te.length;function B(v){const J=[];for(const F of fe){const ce=F.factors.find(P=>P.id===v);ce&&ce.score<70&&J.push({url:F.url,score:ce.score})}return J.sort((F,ce)=>F.score-ce.score)}return e.jsxs("div",{className:"mt-6",children:[e.jsxs("section",{className:"surface-card flex flex-wrap items-start justify-between gap-6 rounded-lg border border-default bg-surface p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:le?"Technical AEO history":"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${xn(g.aggregateScore)}`,children:g.aggregateScore}),e.jsx("span",{className:"text-lg text-muted",children:"/ 100"}),e.jsx(ae,{tone:mn(g.aggregateScore),children:Fs(g.aggregateScore)}),K?e.jsx(ae,{tone:$,children:K}):null,x?e.jsx(ae,{tone:"neutral",children:y}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[g.pagesDiscovered," URL",g.pagesDiscovered===1?"":"s"," in sitemap · ",g.pagesAudited," audited · ",g.pagesSkipped," skipped · ",g.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-muted",children:[e.jsx("span",{className:"text-faint",children:"Sitemap:"}),e.jsx("a",{href:g.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-secondary underline decoration-mono-700 underline-offset-2 hover:text-strong",children:g.sitemapUrl}),e.jsx(Te,{text:"Every audit re-reads this sitemap, so pages you add or remove are picked up on the next run. Discovered/audited counts and the score reflect the sitemap at the time of the latest run. Override it with `canonry technical-aeo run <project> --sitemap-url <url>`."})]}),g.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-faint",children:["Audited ",new Date(g.auditedAt).toLocaleString()]}):null,x?e.jsx("p",{className:"mt-1 text-xs text-muted",role:"status","aria-live":"polite",children:"Results refresh automatically when this audit finishes."}):null]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-end gap-2",children:[q.length>1?e.jsxs("select",{"aria-label":"View a Technical AEO audit",value:l??"",onChange:v=>h(v.target.value||null),className:"min-h-11 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:[e.jsx("option",{value:"",children:"Latest audit"}),[...q].reverse().slice(1).map(v=>e.jsxs("option",{value:v.runId,children:[new Date(v.auditedAt).toLocaleDateString()," · ",v.aggregateScore,"/100"]},v.runId))]}):null,e.jsxs(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{ee()},disabled:u,children:[e.jsx(gt,{className:`mr-1.5 h-4 w-4 ${u?"motion-safe:animate-spin":""}`,"aria-hidden":"true"}),u?"Refreshing…":"Refresh"]}),!T()&&e.jsxs(R,{type:"button",size:"sm",onClick:oe,disabled:x,children:[x?e.jsx(jn,{className:"mr-1.5 h-4 w-4 motion-safe:animate-spin","aria-hidden":"true"}):e.jsx(Ot,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),x?y:"Re-run audit"]})]})]}),Z.length>=2?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Trend"}),e.jsx("h2",{children:"Site score over time"})]}),e.jsxs("div",{className:"mt-3 h-56",children:[e.jsxs("p",{className:"sr-only",children:["Technical AEO scores range from ",Math.min(...Z.map(v=>v.score))," to ",Math.max(...Z.map(v=>v.score))," across ",Z.length," audits. Use the audit selector to inspect a previous scorecard."]}),e.jsx("div",{className:"h-full","aria-hidden":"true",children:e.jsx(Zt,{width:"100%",height:"100%",children:e.jsxs(es,{data:Z,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Dn,{stroke:Pn,vertical:!1}),e.jsx(ts,{dataKey:"date",tick:st,tickLine:!1,axisLine:{stroke:jt},tickFormatter:id,minTickGap:24}),e.jsx(ss,{domain:[0,100],ticks:[0,25,50,75,100],tick:st,tickLine:!1,axisLine:!1,width:32}),e.jsx(ns,{...Bt,cursor:{stroke:jt,strokeWidth:1},labelFormatter:rd,formatter:v=>[`${v}/100`,"Site score"]}),e.jsx(Rn,{type:"monotone",dataKey:"score",name:"score",stroke:bt.positive,strokeWidth:2.5,dot:{r:2.5,fill:bt.positive,strokeWidth:0},isAnimationActive:!1})]})})})]})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Scorecard"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Ranking factors",e.jsx(Te,{text:"Each factor is scored 0–100 per page (via the aeo-audit engine), then averaged across all successfully-audited pages. Pass ≥70, partial 40–69, fail <40. Expand a row to see which pages fall short and how to fix it."})]})]}),e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Factor"}),e.jsx("th",{className:"text-right",children:"Weight"}),e.jsx("th",{className:"text-right",children:"Avg"}),e.jsx("th",{children:"Status"}),e.jsx("th",{children:"Pass / Partial / Fail"})]})}),e.jsx("tbody",{children:g.factors.map(v=>{const J=i===v.id,F=g.crossCuttingIssues.find(U=>U.factorId===v.id),ce=J?B(v.id):[],P=v.pagesPartial+v.pagesFailing;return e.jsxs(o.Fragment,{children:[e.jsxs("tr",{className:J?"bg-surface":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left font-medium text-strong hover:text-primary","aria-expanded":J,onClick:()=>r(J?null:v.id),children:[J?e.jsx(Ys,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}):e.jsx(Ws,{className:"h-3.5 w-3.5 shrink-0 text-muted","aria-hidden":"true"}),v.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-muted",children:[v.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:v.avgScore}),e.jsx("td",{children:e.jsx(ae,{tone:ad(v.status),children:Fs(v.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-secondary",children:[e.jsx("span",{className:"text-positive-400",children:v.pagesPassing})," / ",e.jsx("span",{className:"text-caution-400",children:v.pagesPartial})," / ",e.jsx("span",{className:"text-negative-400",children:v.pagesFailing})]})]}),J?e.jsx("tr",{className:"bg-surface",children:e.jsx("td",{colSpan:5,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"space-y-4 border-l border-base pl-4",children:[F&&F.topRecommendations.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:"How to fix"}),e.jsx("ul",{className:"space-y-1",children:F.topRecommendations.map((U,we)=>e.jsxs("li",{className:"flex gap-2 text-sm text-neutral",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:U})]},we))})]}):P===0?e.jsx("p",{className:"text-sm text-muted",children:"Every audited page passes this factor."}):null,P>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-muted",children:["Pages below pass (",P,")"]}),e.jsx("ul",{className:"space-y-1",children:ce.slice(0,un).map(U=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${xn(U.score)}`,children:U.score}),e.jsx("a",{href:U.url,target:"_blank",rel:"noreferrer",className:"truncate text-neutral hover:text-heading",title:U.url,children:U.url})]},U.url))}),ce.length>un?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["+ ",ce.length-un," more below pass"]}):null,k?e.jsxs("p",{className:"mt-1 text-xs text-faint",children:["Showing the worst ",te.length," audited pages."]}):null]}):null]})})}):null]},v.id)})})]})})]}),g.crossCuttingIssues.length>0?e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Opportunities"}),e.jsxs("h2",{className:"inline-flex items-center gap-1.5",children:["Prioritized fixes",e.jsx(Te,{text:"Factors scoring below pass across the most pages, ranked by site-wide impact. Fixing one of these typically lifts many pages at once."})]})]}),e.jsx("div",{className:"mt-3 divide-y divide-mono-800/60 overflow-hidden rounded-lg border border-default",children:g.crossCuttingIssues.map(v=>e.jsxs("div",{className:"p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-medium text-heading",children:v.factorName}),e.jsx(ae,{tone:mn(v.avgScore),children:Fs(v.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-muted",children:["avg ",v.avgScore," · affects ",v.affectedPages," of ",v.totalPages," pages (",v.affectedPct,"%)"]})]}),v.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:v.topRecommendations.map((J,F)=>e.jsxs("li",{className:"flex gap-2 text-sm text-secondary",children:[e.jsx("span",{className:"select-none text-faint",children:"→"}),e.jsx("span",{children:J})]},F))}):null]},v.factorId))})]}):null,e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Pages"}),e.jsx("h2",{children:"Per-page breakdown"})]}),ue?e.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full border border-default p-0.5",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>a(!1),"aria-pressed":!H,className:`min-h-11 rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${H?"text-muted hover:text-neutral":"bg-mono-800 text-heading"}`,children:["All ",g.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>a(!0),"aria-pressed":H,className:`min-h-11 rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${H?"bg-negative-500/15 text-negative":"text-muted hover:text-neutral"}`,children:["Errors ",g.pagesErrored]})]}):null]}),xe.length===0?e.jsx("p",{className:"supporting-copy mt-3",children:"No pages recorded."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"evidence-table-wrap mt-3",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-right",children:"Score"}),e.jsx("th",{children:"Status"}),e.jsx("th",{className:"w-full",children:"URL"})]})}),e.jsx("tbody",{children:xe.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:v.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-negative-400",children:[e.jsx(qr,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:xn(v.overallScore),children:v.overallScore})}),e.jsx("td",{children:v.status==="error"?e.jsx(ae,{tone:"negative",children:"Error"}):e.jsx(ae,{tone:mn(v.overallScore),children:Fs(v.overallScore)})}),e.jsx("td",{className:"w-full max-w-0",children:e.jsx("a",{href:v.url,target:"_blank",rel:"noreferrer",className:"block truncate text-neutral hover:text-heading",title:v.status==="error"?v.error??v.url:v.url,children:v.url})})]},v.url))})]})}),k?e.jsxs("p",{className:"mt-2 text-xs text-faint",children:["Showing the worst ",te.length," of ",g.pagesAudited," audited pages."]}):null]})]})]})}function va(t){return`${(t*100).toFixed(1)}%`}function ld({projectName:t}){const[s,n]=o.useState("changes"),[a,i]=o.useState(null),[r,l]=o.useState(null),h=ve({...Gr({client:W,path:{name:t},query:{limit:30}}),enabled:s==="health"}),u=ve({...Ba({client:W,path:{name:t},query:{kind:"answer-visibility",limit:100}}),enabled:s==="compare"}),m=(u.data??[]).filter(b=>(b.status==="completed"||b.status==="partial")&&b.trigger!=="probe").reverse(),p=r??m[0]?.id??"",d=a??m.find(b=>b.id!==p)?.id??"",S=!!(d&&p&&d!==p),f=ve({...Ur({client:W,path:{name:t},query:{run1:d,run2:p}}),enabled:s==="compare"&&S}),C=h.data??[],N=f.data?.diff.filter(b=>b.changed||b.visibilityChanged)??[];return e.jsxs("div",{className:"mt-6",children:[e.jsx("div",{className:"filter-row",role:"tablist","aria-label":"Project history views",children:[["changes","Changes"],["health","Coverage history"],["compare","Compare runs"]].map(([b,I])=>e.jsx("button",{type:"button",role:"tab","aria-selected":s===b,className:`filter-chip ${s===b?"filter-chip-active":""}`,onClick:()=>n(b),children:I},b))}),s==="changes"?e.jsx(Vo,{projectName:t}):null,s==="health"?e.jsxs("section",{className:"mt-6","aria-labelledby":"coverage-history-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Query evidence"}),e.jsx("h2",{id:"coverage-history-heading",children:"Mention and citation coverage"}),e.jsx("p",{className:"supporting-copy mt-1",children:"Independent answer-text mentions and source citations across completed sweeps."})]}),h.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Loading coverage history…"}):null,!h.isLoading&&C.length===0?e.jsxs(V,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No coverage history yet"}),e.jsx("p",{children:"Complete an answer visibility sweep to create the first snapshot."})]}):null,C.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Date"}),e.jsx("th",{className:"text-right",children:"Mentioned"}),e.jsx("th",{className:"text-right",children:"Mention coverage"}),e.jsx("th",{className:"text-right",children:"Cited"}),e.jsx("th",{className:"text-right",children:"Citation coverage"})]})}),e.jsx("tbody",{children:C.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"whitespace-nowrap tabular-nums text-secondary",children:new Date(b.createdAt).toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.mentionedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:va(b.overallMentionRate)}),e.jsxs("td",{className:"text-right tabular-nums text-secondary",children:[b.citedPairs,"/",b.totalPairs]}),e.jsx("td",{className:"text-right tabular-nums text-strong",children:va(b.overallCitedRate)})]},b.id))})]})}):null]}):null,s==="compare"?e.jsxs("section",{className:"mt-6","aria-labelledby":"compare-runs-heading",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Evidence diff"}),e.jsx("h2",{id:"compare-runs-heading",children:"Compare answer visibility runs"}),e.jsx("p",{className:"supporting-copy mt-1",children:"See which tracked queries changed mention or citation state between two sweeps."})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("label",{className:"text-xs text-muted",children:["Earlier run",e.jsx("select",{value:d,onChange:b=>i(b.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:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]}),e.jsxs("label",{className:"text-xs text-muted",children:["Later run",e.jsx("select",{value:p,onChange:b=>l(b.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:m.map(b=>e.jsx("option",{value:b.id,children:new Date(b.createdAt).toLocaleString()},b.id))})]})]}),u.isLoading||f.isLoading?e.jsx("p",{className:"supporting-copy mt-4",role:"status",children:"Comparing runs…"}):null,!u.isLoading&&m.length<2?e.jsxs(V,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"Two completed sweeps are required"}),e.jsx("p",{children:"Run another answer visibility sweep before comparing historical evidence."})]}):null,f.data&&N.length===0?e.jsxs(V,{className:"surface-card empty-card mt-4",children:[e.jsx("h3",{children:"No mention or citation changes"}),e.jsx("p",{children:"The selected sweeps have the same states for every comparable tracked query."})]}):null,N.length>0?e.jsx("div",{className:"evidence-table-wrap mt-4",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Query"}),e.jsx("th",{children:"Citation"}),e.jsx("th",{children:"Mention"})]})}),e.jsx("tbody",{children:N.map(b=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-strong",children:b.query??"Archived query"}),e.jsx("td",{children:e.jsxs(ae,{tone:b.changed?"caution":"neutral",children:[b.run1State??"none"," → ",b.run2State??"none"]})}),e.jsx("td",{children:e.jsxs(ae,{tone:b.visibilityChanged?"caution":"neutral",children:[b.run1MentionState??"none"," → ",b.run2MentionState??"none"]})})]},b.queryId??b.query??"unknown"))})]})}):null]}):null]})}const cd={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function Ee(t){return Number.isFinite(t)?Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}M`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString("en-US"):"—"}function dd(t){if(!t)return"—";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}function ud(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function md({projectName:t}){const[s,n]=o.useState(!1),[a,i]=o.useState(null),[r,l]=o.useState(Qr),h=ve({...zr({client:W,path:{name:t},query:{period:r}}),placeholderData:wi});async function u(){n(!0),i(null);try{await Hr(t,"client",r)}catch(p){const d=p instanceof bn||p instanceof Error?p.message:"Download failed";i(d)}finally{n(!1)}}if(h.isLoading)return e.jsx("p",{className:"text-sm text-muted py-8 text-center",children:"Loading report…"});if(h.error){const p=h.error instanceof Error?h.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-negative-400",children:p})})}const m=h.data;return m?e.jsxs("div",{children:[e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("p",{className:"eyebrow",children:"AI Visibility Report"}),e.jsx("h1",{className:"page-title",children:m.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[m.meta.project.canonicalDomain," · ",m.meta.project.country," / ",m.meta.project.language.toUpperCase(),m.meta.location?` · Location: ${ud(m.meta.location)}`:" · No location set"," · ","Last ",m.meta.periodDays," days"," · ","Generated ",dd(m.meta.generatedAt)]}),a&&e.jsx("p",{className:"mt-2 text-xs text-negative-400",children:a})]}),e.jsxs("div",{className:"page-header-right flex flex-col items-end gap-2",children:[e.jsx(xd,{period:r,onChange:l}),e.jsxs(R,{variant:"secondary",size:"sm",onClick:de(u),disabled:s,children:[e.jsx(fs,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})]})]}),e.jsx(yd,{report:m}),e.jsx(Cd,{report:m,audience:"client"}),e.jsx(gd,{report:m}),e.jsx(wd,{report:m,audience:"client",projectName:t}),e.jsx(Sd,{report:m})]}):null}function xd({period:t,onChange:s}){return e.jsx("div",{className:"inline-flex items-center gap-0.5 rounded-full border border-default bg-bg-elevated/40 p-0.5",role:"group","aria-label":"Report time period",children:Kr.map(n=>{const a=n===t;return e.jsxs("button",{type:"button",onClick:()=>s(n),"aria-pressed":a,className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${a?"bg-mono-200 text-mono-900":"text-secondary hover:text-heading"}`,children:[n,"d"]},n)})})}const Na="AI Visibility — Server-Side",wa="AI engine attention",hd=t=>`What AI engines actually do in your server logs over the last ${t} days — the other half of citations.`,pd="Live telemetry from your server logs.";function gd({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ws,{eyebrow:wa,title:Na,subtitle:pd}),e.jsx("p",{className:"text-sm text-muted",children:"Your server-side traffic source is connected. Numbers will appear after the next sync."})]});const n={current:s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,prior:s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior,deltaPct:nl(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},a=t.meta.periodDays,i=`vs prior ${a} days`,r=nn(n,"requests",i),l=`${Ee(s.verifiedCrawlerHits.current)} verified · ${Ee(s.unverifiedCrawlerHits.current)} unverified${r?` · ${r}`:""}`,h=nn(s.aiUserFetchHits,"requests",i),m=[nn(s.referralArrivals,"sessions",i),s.referralArrivalsClassSummary].filter(Boolean).join(" · "),p=s.byOperator.filter(d=>d.verifiedHits>0||d.unverifiedHits>0||d.userFetchHits>0||d.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ws,{eyebrow:wa,title:Na,subtitle:hd(a)}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(gn,{label:"AI bot requests observed",value:Ee(n.current),subtitle:l}),e.jsx(gn,{label:"AI user-fetch requests",value:Ee(s.aiUserFetchHits.current),subtitle:h||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(gn,{label:"AI referral sessions",value:Ee(s.referralArrivals.current),subtitle:m})]}),p.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:"By AI tool"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"AI tool"}),e.jsxs("th",{children:["Bot requests (",a,"d)"]}),e.jsxs("th",{children:["User fetches (",a,"d)"]}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:p.map(d=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:d.operator}),e.jsx("td",{children:Ee(d.verifiedHits+d.unverifiedHits)}),e.jsx("td",{children:Ee(d.userFetchHits)}),e.jsx("td",{children:Ee(d.referralArrivals)})]},d.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-muted",children:"Bot requests are bulk crawl (GPTBot, PerplexityBot, …). User fetches are on-demand reads triggered by real users inside an AI surface (ChatGPT-User, Perplexity-User, …). Verified means the request came from an IP the operator publishes as its own; unverified means the user-agent matched but the IP is not in a published range. User-fetch totals count both, since many genuine user fetches come from outside any published range."})]})]})}function fd(t,s){return t.audience==="both"||t.audience===s}const bd={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Hs(t){return bd[t]??t.charAt(0).toUpperCase()+t.slice(1)}function jd(t){if(!t)return null;const s=t.window??1,n=s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`;return t.direction==="up"?{text:`Up ${t.deltaAbs.toFixed(1)} points ${n}`,tone:"positive",arrow:"↑"}:t.direction==="down"?{text:`Down ${Math.abs(t.deltaAbs).toFixed(1)} points ${n}`,tone:"negative",arrow:"↓"}:{text:`Holding steady ${s>=2?`vs prior ${s} checks (avg ${t.prior}%)`:`since last check (was ${t.prior}%)`}`,tone:"neutral",arrow:"→"}}function yd({report:t}){const s=t.executiveSummary,n=t.citationScorecard,a=s.totalQueryCount,i=a>0?`${s.mentionRate}%`:"—",r=a>0?`When customers asked AI ${a} ${a===1?"question":"questions"} about your industry, AI mentioned you in ${s.mentionedQueryCount} of ${a===1?"them":"those answers"}.`:"No AI check has been run yet. Run a check to see how AI tools answer customer questions about your business.",l=jd(t.whatsChanged.mentionRate),h=n.providers.length>0?n.providers.map(Hs).join(", "):`${Ee(s.queryCount)} ${s.queryCount===1?"question":"questions"} tested`;return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"rounded-2xl border border-default bg-bg-elevated/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-primary sm:text-7xl",children:i}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-neutral sm:text-lg",children:r}),l&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${l.tone==="positive"?"text-positive-400":l.tone==="negative"?"text-negative-400":"text-secondary"}`,children:[e.jsx("span",{className:"mr-1",children:l.arrow}),l.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(hn,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:a>0?`Says your name in ${s.mentionedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(hn,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:a>0?`Cites your site as a source in ${s.citedQueryCount} of ${a} ${a===1?"answer":"answers"}`:"No data yet"}),e.jsx(hn,{label:"AI tools tested",value:Ee(s.providerCount),subtitle:h})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-bg/40 px-4 py-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-semibold text-strong",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-strong",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-strong",children:"link"})," is when AI lists your website as a source it used. AI can do either, both, or neither — that's why we track both."]}),n.queries.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Customer questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["These are the ",n.queries.length," ",n.queries.length===1?"question we asked":"questions we asked"," every AI tool. The numbers above measure how often you came up."]}),e.jsx("ol",{className:"mt-4 grid gap-2 sm:grid-cols-2",children:n.queries.map((u,m)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-default bg-bg/40 px-3 py-2 text-sm text-strong",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-muted",children:String(m+1).padStart(2,"0")}),e.jsxs("span",{children:['"',u,'"']})]},m))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"How often each AI tool mentions you"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Higher is better. Each bar shows the share of customer questions where the AI named you in the answer."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(u=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-neutral",children:Hs(u.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-positive-500/70",style:{width:`${Math.max(u.mentionRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-heading",children:[u.mentionRate,"% ",e.jsxs("span",{className:"font-normal text-muted",children:["(",u.mentionedCount,"/",u.totalCount,")"]})]})]},u.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((u,m)=>e.jsx("div",{className:"rounded-lg border border-default bg-surface px-3 py-2 text-xs text-secondary",children:u},m))})]})}function hn({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-primary sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:n})]})}function vd(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function Nd(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function wd({report:t,audience:s,projectName:n}){const a=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(d=>fd(d,s)),i=ll(t,a),r=s==="client",l=Vr(),[h,u]=o.useState(new Set),m=h.size>0?i.filter(d=>!d.targetRef||!h.has(d.targetRef)):i,p=d=>{if(!d.targetRef)return;const S=d.targetRef;u(f=>new Set(f).add(S)),l.mutate({projectName:n,body:{targetRef:S}},{onSuccess:()=>{Y({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:f=>{Y({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(f)}),u(C=>{const N=new Set(C);return N.delete(S),N})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ws,{eyebrow:r?"Action plan":"Agency actions",title:r?"What to do next":"Agency Action Plan",subtitle:r?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),m.length===0?e.jsx(On,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:m.map((d,S)=>{const f=d.evidence.length>0?d.evidence:d.why,C=d.why.length>0||d.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-default bg-surface p-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-full bg-mono-800/80 text-sm font-semibold text-heading",title:"Priority — 1 will move the needle fastest",children:S+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"mb-2 flex flex-wrap gap-2",children:[e.jsx(ae,{tone:Yr(d),children:r?vd(d.horizon):Wr(d.horizon)}),!r&&e.jsx(ae,{tone:"neutral",children:Jr(d.category)}),e.jsx(ae,{tone:"neutral",children:r?Nd(d.confidence):`${Xr(d.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-heading",children:d.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-secondary",children:d.action}),e.jsx(Ad,{items:f,limit:3,className:"mt-3"}),C&&e.jsxs("details",{className:"mt-3 text-xs text-secondary",children:[e.jsx("summary",{className:"cursor-pointer text-muted hover:text-neutral",children:r?"See the data behind this":"Evidence details"}),d.why.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.why.map((N,b)=>e.jsx("li",{children:N},b))})]}),d.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:r?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.evidence.map((N,b)=>e.jsx("li",{children:N},b))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-default pt-3 text-xs text-neutral",children:[e.jsx("span",{className:"font-medium",children:r?"What success looks like:":"Win condition:"})," ",d.successMetric]}),d.targetRef&&!T()&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>p(d),className:"rounded-md border border-strong/60 bg-bg-elevated/50 px-2.5 py-1 text-[11px] font-medium text-neutral hover:border-mono-600 hover:bg-mono-800/70 hover:text-heading",title:"Stop showing this recommendation. The page-detection logic relies on GSC/GA syncs that lag by days — if you've already addressed it, dismissing keeps the report current.",children:"Mark addressed"})})]},`${d.priority}-${d.title}`)})})]})}function Sa({label:t,value:s,displayValue:n,max:a,barClass:i}){const r=a>0?Math.max(s/a*100,1.5):0;return e.jsxs("div",{className:"grid grid-cols-[1fr_auto] items-center gap-3 text-sm",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-neutral",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${i}`,style:{width:`${r}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-heading",children:n})]})}function Sd({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,a=t.indexingHealth,i=cl(t).slice(0,5),r=s.length>0?Math.max(...s.map(u=>u.count)):0,l=n?Math.max(...n.topQueries.slice(0,5).map(u=>u.impressions),1):0,h=s.length>0||n!==null||a!==null||i.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(ws,{eyebrow:"What we based this on",title:"The signals behind this plan",subtitle:"The data behind the recommendations above. Switch to Agency for the full breakdowns."}),h?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"The websites AI tools cited most often when answering customer questions about your industry."}),e.jsx("div",{className:"mt-4 space-y-3",children:s.map(u=>e.jsx(Sa,{label:u.domain+(u.isCompetitor?" (competitor)":""),value:u.count,displayValue:`${Ee(u.count)}×`,max:r,barClass:"bg-mono-400/70"},u.domain))})]}),a&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Google indexing your site increases the chances of it appearing in AI search (especially Gemini)."}),e.jsxs("p",{className:`mt-4 text-5xl font-bold tracking-tight ${a.indexedPct>=90?"text-positive-400":a.indexedPct>=70?"text-caution-400":"text-negative-400"}`,children:[a.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:[Ee(a.indexed)," of ",Ee(a.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-mono-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a.indexedPct>=90?"bg-positive-500/70":a.indexedPct>=70?"bg-caution-500/70":"bg-negative-500/70"}`,style:{width:`${Math.max(a.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-secondary",children:[e.jsx("span",{className:"font-medium text-strong",children:Ee(a.notIndexed)})," ",a.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-muted",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-strong",children:Ee(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-strong",children:Ee(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(u=>e.jsx(Sa,{label:u.query,value:u.impressions,displayValue:`${Ee(u.impressions)} ${u.impressions===1?"search":"searches"}`,max:l,barClass:"bg-info-500/70"},u.query))})]}),i.length>0&&e.jsxs("div",{className:"rounded-xl border border-default bg-surface p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-heading",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-muted",children:"Customer questions where better content on your site would help AI cite you."}),e.jsx("ul",{className:"mt-4 space-y-2 text-sm text-neutral",children:i.map((u,m)=>e.jsxs("li",{className:"rounded-lg border border-default bg-bg/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-heading",children:u.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-secondary",children:[Zr(u.action),u.winnabilityClass==="ceded"&&e.jsx(ae,{tone:"caution",children:"Ceded surface"})]})]},m))})]})]}):e.jsx(On,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}function Mn(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function En(t){return t==="up"?"↑":t==="down"?"↓":"→"}function pn({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"No prior data"})]});const a=n==="%"?"%":"",i=Mn(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",l=n==="%"?`${s.deltaAbs>0?"+":""}${s.deltaAbs.toFixed(1)}% vs ${s.prior}%`:al(s);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:[s.current,a," ",e.jsx("span",{className:"text-sm font-medium",children:En(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:l})]})}function ka({label:t,delta:s,countLabel:n,comparisonWindowDays:a}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-muted",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:"Not enough trend data"})]});const i=Mn(s.direction),r=i==="positive"?"text-positive-400":i==="negative"?"text-negative-400":"text-heading",l=il(s,n,`vs prior ${a} days`);return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${r}`,children:[Ee(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:En(s.direction)})]}),e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:l})]})}function kd({movements:t,audience:s}){const n=t.filter(i=>i.direction!=="flat");if(n.length===0)return null;const a=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:a?"How each AI tool changed":"AI engine movements"}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:a?"AI tool":"Engine"}),e.jsx("th",{children:a?"Was":"Prior"}),e.jsx("th",{children:a?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(i=>{const r=i.deltaAbs>0?"+":"",l=Mn(i.direction),h=l==="positive"?"text-positive-400":l==="negative"?"text-negative-400":"text-neutral";return e.jsxs("tr",{children:[e.jsx("td",{children:a?Hs(i.provider):i.provider}),e.jsxs("td",{children:[i.prior,"%"]}),e.jsxs("td",{children:[i.current,"%"]}),e.jsxs("td",{className:h,children:[r,i.deltaAbs.toFixed(1),"% ",En(i.direction)]})]},i.provider)})})]})})]})}function Ca({insights:t,heading:s,emptyMessage:n,audience:a}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-default bg-surface p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-muted",children:n})]});const i=a==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:s}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[!i&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:i?"What changed":"Title"}),e.jsx("th",{children:i?"Customer question":"Query"}),e.jsx("th",{children:i?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(r=>e.jsxs("tr",{children:[!i&&e.jsxs("td",{children:[e.jsx(ae,{tone:cd[r.severity],children:eo(r.severity)}),r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[r.title,i&&r.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-muted",children:["×",r.instanceCount]})]}),e.jsx("td",{className:"text-xs text-secondary",children:r.query}),e.jsx("td",{className:"text-xs text-secondary",children:i?Hs(r.provider):r.provider})]},r.id))})]})})]})}function Cd({report:t,audience:s}){const n=t.whatsChanged,a=s==="client",i=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,r=e.jsx(ws,{eyebrow:a?"Since last check":"Section 2",title:a?"What's different since last check":"What's Changed",subtitle:a?void 0:n.headline});return i?e.jsxs("section",{className:"page-section-divider",children:[r,e.jsx(On,{message:a?"No comparison yet — trends will appear after a few more checks.":"Trends will appear after a few more checks."})]}):e.jsxs("section",{className:"page-section-divider",children:[r,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(pn,{label:a?"AI mentions your name":"Citation rate",delta:a?n.mentionRate:n.citationRate,unit:"%"}),e.jsx(pn,{label:a?"AI links to your website":"Mention rate",delta:a?n.citationRate:n.mentionRate,unit:"%"}),e.jsx(pn,{label:a?"Questions AI mentioned you in":"Cited queries",delta:a?n.mentionedQueryCount:n.citedQueryCount,unit:"count"}),e.jsx(ka,{label:a?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:a?"visits":"clicks",comparisonWindowDays:n.comparisonWindowDays}),e.jsx(ka,{label:a?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:a?"visits":"sessions",comparisonWindowDays:n.comparisonWindowDays})]}),e.jsx(kd,{movements:n.providerMovements,audience:s}),e.jsx(Ca,{insights:n.wins,heading:a?"What got better":"Wins",emptyMessage:a?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(Ca,{insights:n.regressions,heading:a?"What got worse":"Regressions",emptyMessage:a?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function gn({label:t,value:s,tone:n,subtitle:a}){const i=n==="positive"?"text-positive-400":n==="caution"?"text-caution-400":n==="negative"?"text-negative-400":"text-heading";return e.jsxs("div",{className:"rounded-xl border border-default bg-surface px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${i}`,children:s}),a&&e.jsx("p",{className:"mt-1 text-[11px] text-muted",children:a})]})}function ws({eyebrow:t,title:s,subtitle:n}){return e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("h2",{className:"page-title",children:s}),n&&e.jsx("p",{className:"page-subtitle mt-1",children:n})]})}function Ad({items:t,limit:s=3,className:n}){if(t.length===0)return null;const a=t.slice(0,s),i=t.length-a.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[a.map((r,l)=>e.jsx("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-neutral",children:r},l)),i>0&&e.jsxs("span",{className:"rounded-md border border-default bg-bg-elevated/40 px-2 py-0.5 text-[11px] text-secondary",children:["+",i," more"]})]})}function On({message:t}){return e.jsx("p",{className:"text-sm text-muted py-4 text-center",children:t})}function $d({project:t,onUpdateProject:s,onRefresh:n}){const[a,i]=o.useState(!1),[r,l]=o.useState(!1),[h,u]=o.useState(null),[m,p]=o.useState(t.displayName),[d,S]=o.useState(t.canonicalDomain),[f,C]=o.useState(t.country),[N,b]=o.useState(t.language),[I,G]=o.useState(t.ownedDomains??[]),[M,z]=o.useState(""),[x,A]=o.useState(t.aliases??[]),[_,ee]=o.useState(""),[oe,y]=o.useState(null),[g,K]=o.useState(!1),[$,q]=o.useState(!1),[Z,le]=o.useState(""),[te,fe]=o.useState(""),[ue,H]=o.useState(""),[xe,k]=o.useState(""),[B,v]=o.useState(""),[J,F]=o.useState(null),[ce,P]=o.useState(null);o.useEffect(()=>{a||(p(t.displayName),S(t.canonicalDomain),C(t.country),b(t.language),G(t.ownedDomains??[]),A(t.aliases??[]))},[t,a]);function U(){i(!1),u(null),p(t.displayName),S(t.canonicalDomain),C(t.country),b(t.language),G(t.ownedDomains??[]),A(t.aliases??[]),z(""),ee("")}function we(){const L=M.trim();L&&(I.includes(L)||G([...I,L]),z(""))}function Me(L){G(I.filter(Ne=>Ne!==L))}function $e(){const L=_.trim();if(!L)return;const Ne=L.toLowerCase();x.some(Oe=>Oe.toLowerCase()===Ne)||A([...x,L]),ee("")}function be(L){A(x.filter(Ne=>Ne!==L))}async function E(){if(!(!m.trim()||!d.trim()||!f.trim()||!N.trim())){l(!0),u(null);try{await s(t.name,{displayName:m.trim(),canonicalDomain:d.trim(),ownedDomains:I,aliases:x,country:f.trim(),language:N.trim()}),i(!1),Y({title:"Project settings saved",detail:`${m.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(L){u(L instanceof Error?L.message:"Failed to save")}finally{l(!1)}}}async function re(){const L=Z.trim(),Ne=te.trim(),Oe=ue.trim(),at=xe.trim();if(!(!L||!Ne||!Oe||!at)){K(!0),y(null);try{const Le={label:L,city:Ne,region:Oe,country:at};B.trim()&&(Le.timezone=B.trim()),await no(t.name,Le),n(),le(""),fe(""),H(""),k(""),v(""),q(!1),Y({title:"Location added",detail:`${L} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${L}`,dedupeMode:"drop"})}catch(Le){y(Le instanceof Error?Le.message:"Failed to add location")}finally{K(!1)}}}async function je(L){K(!0),y(null);try{await so(t.name,L),n(),Y({title:"Location removed",detail:`${L} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${L}`,dedupeMode:"drop"})}catch(Ne){y(Ne instanceof Error?Ne.message:"Failed to remove location")}finally{K(!1)}}async function pe(L){K(!0),y(null);try{await to(t.name,L),n(),Y({title:"Default location updated",detail:`${L} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(Ne){y(Ne instanceof Error?Ne.message:"Failed to set default location")}finally{K(!1)}}async function ye(L){F(L),P(null);try{await ao(t.name,L),Y({title:`${L.toUpperCase()} download started`,detail:`Historical citation and mention results for ${t.displayName}.`,tone:"positive",dedupeKey:`project:results-export:${t.name}`,dedupeMode:"replace"})}catch(Ne){P(Ne instanceof Error?Ne.message:"Could not download tracking results.")}finally{F(null)}}const O=m!==t.displayName||d!==t.canonicalDomain||f!==t.country||N!==t.language||JSON.stringify(I)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(x)!==JSON.stringify(t.aliases??[]),Se="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",Pe="block text-xs font-medium text-secondary mb-1",Qe=Z.trim()&&te.trim()&&ue.trim()&&xe.trim();return e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!T()&&!a&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>i(!0),children:"Edit settings"})]}),h&&e.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:[h,e.jsx("button",{type:"button",className:"ml-2 text-negative-400 hover:text-negative-200",onClick:()=>u(null),children:"×"})]}),!T()&&a?e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"Display name"}),e.jsx("input",{className:Se,type:"text",value:m,onChange:L=>p(L.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"Canonical domain"}),e.jsx("input",{className:Se,type:"text",value:d,onChange:L=>S(L.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"Country"}),e.jsx("input",{className:Se,type:"text",value:f,onChange:L=>C(L.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"Language"}),e.jsx("input",{className:Se,type:"text",value:N,onChange:L=>b(L.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:I.map(L=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:[L,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>Me(L),"aria-label":`Remove ${L}`,children:"×"})]},L))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Se} flex-1`,type:"text",placeholder:"docs.example.com",value:M,onChange:L=>z(L.target.value),onKeyDown:L=>L.key==="Enter"&&(L.preventDefault(),we())}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:!M.trim(),onClick:we,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Pe,children:"Aliases"}),e.jsx("p",{className:"text-[11px] text-muted mb-1.5",children:'Additional brand names checked against LLM answer text. Use for product names, prior names, or DBAs (e.g. add "Meta" as an alias to facebook.com).'}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:x.map(L=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:[L,e.jsx("button",{type:"button",className:"ml-0.5 text-muted hover:text-strong transition-colors",onClick:()=>be(L),"aria-label":`Remove ${L}`,children:"×"})]},L))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${Se} flex-1`,type:"text",placeholder:"Facebook",value:_,onChange:L=>ee(L.target.value),onKeyDown:L=>L.key==="Enter"&&(L.preventDefault(),$e())}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:!_.trim(),onClick:$e,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-default",children:[e.jsx(R,{type:"button",disabled:r||!O||!m.trim()||!d.trim(),onClick:de(E),children:r?"Saving...":"Save changes"}),e.jsx(R,{type:"button",variant:"outline",disabled:r,onClick:U,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-default bg-surface overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Owned domains"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.ownedDomains??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.ownedDomains.map(L=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:L},L))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Aliases"}),e.jsx("td",{className:"px-4 py-2.5",children:(t.aliases??[]).length>0?e.jsx("div",{className:"flex flex-wrap gap-1.5",children:t.aliases.map(L=>e.jsx("span",{className:"rounded-full border border-mono-700/60 bg-mono-800/40 px-2 py-0.5 text-xs text-neutral",children:L},L))}):e.jsx("span",{className:"text-muted",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.country})]}),e.jsxs("tr",{className:"border-b border-subtle",children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-strong",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-muted font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[oe&&e.jsxs("div",{className:"mb-2 rounded border border-negative-800/40 bg-negative-950/20 px-2 py-1 text-xs text-negative",children:[oe,e.jsx("button",{type:"button",className:"ml-1 text-negative-400 hover:text-negative-200",onClick:()=>y(null),children:"×"})]}),(t.locations??[]).length>0?e.jsxs("table",{className:"w-full text-xs mb-2",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-faint",children:[e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Label"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"City"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Region"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Country"}),e.jsx("th",{className:"text-left pb-1 font-medium pr-3",children:"Timezone"}),e.jsx("th",{className:"pb-1"})]})}),e.jsx("tbody",{children:t.locations.map(L=>e.jsxs("tr",{className:"border-t border-mono-800/30",children:[e.jsx("td",{className:"py-1.5 pr-3",children:e.jsxs("span",{className:`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium ${L.label===t.defaultLocation?"border-positive-700/60 bg-positive-950/30 text-positive":"border-mono-700/60 bg-mono-800/40 text-neutral"}`,children:[L.label,L.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:L.city}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:L.region}),e.jsx("td",{className:"py-1.5 pr-3 text-neutral",children:L.country}),e.jsx("td",{className:"py-1.5 pr-3 text-muted",children:L.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[!T()&&L.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:g,onClick:()=>{pe(L.label)},className:"text-[10px] text-muted hover:text-positive-400 transition-colors disabled:opacity-40","aria-label":`Set ${L.label} as default location`,children:"Set default"}),!T()&&e.jsx("button",{type:"button",disabled:g,onClick:()=>{je(L.label)},className:"text-[10px] text-muted hover:text-negative-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${L.label}`,children:"Remove"})]})})]},L.label))})]}):e.jsx("p",{className:"text-muted text-xs mb-2",children:"No locations configured"}),T()?null:$?e.jsxs("div",{className:"mt-2 rounded border border-base bg-bg-elevated/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-muted",children:"Add location"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Label *"}),e.jsx("input",{className:Se,type:"text",value:Z,onChange:L=>le(L.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"City *"}),e.jsx("input",{className:Se,type:"text",value:te,onChange:L=>fe(L.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Region *"}),e.jsx("input",{className:Se,type:"text",value:ue,onChange:L=>H(L.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Country *"}),e.jsx("input",{className:Se,type:"text",value:xe,onChange:L=>k(L.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-[10px] text-muted mb-0.5",children:"Timezone (optional)"}),e.jsx("input",{className:Se,type:"text",value:B,onChange:L=>v(L.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(R,{type:"button",size:"sm",disabled:g||!Qe,onClick:de(re),children:g?"Adding...":"Add location"}),e.jsx(R,{type:"button",size:"sm",variant:"outline",disabled:g,onClick:()=>{q(!1),y(null)},children:"Cancel"})]})]}):e.jsx(R,{type:"button",size:"sm",variant:"outline",onClick:()=>q(!0),children:"+ Add location"})]})]})]})})})]}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Data export"}),e.jsx("h2",{children:"Tracking results"}),e.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."})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.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."}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:J!==null,onClick:de(()=>ye("csv")),children:J==="csv"?"Preparing CSV...":"Download CSV"}),e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:J!==null,onClick:de(()=>ye("json")),children:J==="json"?"Preparing JSON...":"Download JSON"})]})]}),ce&&e.jsx("p",{className:"mt-3 rounded border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:ce})]})]})]})}function gs(t){return{...t??{}}}function Pd(t,s){const n=Object.entries(t).sort(([i],[r])=>i.localeCompare(r)),a=Object.entries(s).sort(([i],[r])=>i.localeCompare(r));return n.length===a.length&&n.every(([i,r],l)=>{const h=a[l];return h?.[0]===i&&h[1]===r})}function Ld({project:t,onSave:s}){const n=ve({queryKey:["settings"],queryFn:La,staleTime:6e4}),[a,i]=o.useState(t.providers.length===0),[r,l]=o.useState(t.providers),[h,u]=o.useState(()=>gs(t.providerModels)),[m,p]=o.useState({providers:t.providers,providerModels:gs(t.providerModels)}),[d,S]=o.useState(!1),[f,C]=o.useState(!1),[N,b]=o.useState(null),[I,G]=o.useState(null),M=o.useRef(null),z=n.data?.providerCatalog??[],x=o.useMemo(()=>new Set((n.data?.providers??[]).filter($=>$.configured).map($=>$.name)),[n.data]),A=o.useMemo(()=>{const $=new Map(z.map(q=>[q.name,q]));for(const q of Object.keys(h))$.has(q)||$.set(q,{name:q,displayName:q,mode:"api",modelConfigurable:!0,defaultModel:"",knownModels:[],modelValidationPattern:{source:".",flags:""},modelValidationHint:"Validate this custom model ID with the server."});return[...$.values()].sort((q,Z)=>q.displayName.localeCompare(Z.displayName))},[z,h]),_=!Pd(h,m.providerModels);o.useEffect(()=>{if(d||f)return;const $={providers:t.providers,providerModels:gs(t.providerModels)};p($),i($.providers.length===0),l($.providers),u($.providerModels)},[t]);function ee(){C(!0),i(!1),r.length===0&&l([...x])}function oe($,q,Z=!1){C(!0),u(le=>{const te={...le};return q==="__inherit__"?delete te[$]:q==="__custom__"?te[$]=Z?"":te[$]??"":te[$]=q,te}),q==="__custom__"&&queueMicrotask(()=>M.current?.focus())}function y($,q){C(!0),l(Z=>q?[...new Set([...Z,$])]:Z.filter(le=>le!==$))}function g(){C(!1),i(m.providers.length===0),l(m.providers),u(gs(m.providerModels)),b(null),G(null)}async function K(){if(!(n.isError||n.isLoading||!a&&r.length===0)){S(!0),b(null),G(null);try{const $=Object.fromEntries(Object.entries(h).filter(([Z,le])=>le.trim()!==""&&(a||r.includes(Z)))),q={providers:a?[]:r,providerModels:$};await s(q),p({providers:[...q.providers],providerModels:gs(q.providerModels)}),C(!1),G("Engine settings saved. They apply on the next sweep.")}catch($){b($ instanceof Error?$.message:String($))}finally{S(!1)}}}return T()?null:n.isLoading?e.jsx("section",{className:"project-engine-settings","aria-busy":"true",children:e.jsx("p",{role:"status",className:"text-sm text-secondary",children:"Loading engine settings…"})}):n.isError?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Could not load the engine catalogue. Saving is disabled until it is available."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):z.length===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"The engine catalogue is incomplete. Saving is disabled so existing project overrides cannot be cleared."}),e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{n.refetch()},children:"Retry"})]}):x.size===0?e.jsxs("section",{className:"project-engine-settings",children:[e.jsx("h2",{children:"Answer engines"}),e.jsxs("p",{className:"text-sm text-secondary",children:["Configure an answer engine in ",e.jsx(ft,{to:"/settings",className:"text-link",children:"global Settings"})," before choosing project engines."]})]}):e.jsxs("section",{className:"project-engine-settings","aria-busy":d,children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Execution"}),e.jsx("h2",{children:"Answer engines"})]}),e.jsx("p",{className:"supporting-copy",children:"Changes apply on the next sweep."})]}),e.jsxs("fieldset",{disabled:d,className:"project-engine-fieldset",children:[e.jsx("legend",{children:"Provider mode"}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:a,onChange:()=>{C(!0),i(!0)}})," All configured engines"]}),e.jsx("p",{className:"project-engine-help",children:"Includes engines configured later in global Settings."}),e.jsxs("label",{children:[e.jsx("input",{type:"radio",checked:!a,onChange:ee})," Choose engines"]}),!a&&e.jsx("div",{className:"project-engine-list",children:A.map($=>{const q=r.includes($.name),Z=x.has($.name),le=q&&!Z,te=h[$.name],fe=$.knownModels.some(H=>H.id===te),ue=te===void 0?"__inherit__":fe?te:"__custom__";return e.jsxs("div",{className:"project-engine-row",children:[e.jsxs("label",{className:"project-engine-provider",children:[e.jsx("input",{type:"checkbox",checked:q,disabled:!Z&&!q,onChange:H=>y($.name,H.target.checked)})," ",e.jsx("span",{children:$.displayName}),le&&e.jsx("span",{className:"text-xs text-caution-400",children:"Not configured, skipped"})]}),q&&($.modelConfigurable?e.jsxs("div",{className:"project-engine-model",children:[e.jsx("label",{htmlFor:`project-model-${$.name}`,children:"Model"}),e.jsxs("select",{id:`project-model-${$.name}`,value:ue,onChange:H=>oe($.name,H.target.value,fe),children:[e.jsxs("option",{value:"__inherit__",children:["Use instance setting: ",$.defaultModel||"default"]}),$.knownModels.map(H=>e.jsx("option",{value:H.id,children:H.displayName},H.id)),e.jsx("option",{value:"__custom__",children:"Custom model ID…"})]}),ue==="__custom__"&&e.jsx("input",{ref:M,"aria-label":`${$.displayName} custom model ID`,value:te??"",onChange:H=>{C(!0),u(xe=>({...xe,[$.name]:H.target.value}))},"aria-describedby":`project-model-hint-${$.name}`}),e.jsxs("p",{id:`project-model-hint-${$.name}`,className:"project-engine-help",children:[te?"Project override":"Inherited from instance settings",". ",$.modelValidationHint]})]}):e.jsx("p",{className:"project-engine-help",children:"Model is detected/fixed for this browser engine."}))]},$.name)})})]}),!a&&r.length===0&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:"Choose at least one configured engine."}),N&&e.jsx("p",{role:"alert",className:"text-sm text-negative-400",children:N}),I&&e.jsx("p",{role:"status",className:"text-sm text-positive-400",children:I}),_&&e.jsx("p",{className:"project-engine-warning",children:"Applies on the next sweep. Existing history remains visible. If the recorded model changes, month-to-month comparison may exclude that engine."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(R,{type:"button",onClick:()=>{K()},disabled:d||!a&&r.length===0,children:d?"Saving engines…":"Save engines"}),e.jsx(R,{type:"button",variant:"outline",onClick:g,disabled:d,children:"Cancel"})]})]})}const Dd=[{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:"custom",label:"Custom cron expression"}],Aa=["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 Rd({projectName:t}){const[s,n]=o.useState("loading"),[a,i]=o.useState(!1),[r,l]=o.useState("daily"),[h,u]=o.useState(6),[m,p]=o.useState(""),[d,S]=o.useState("UTC"),[f,C]=o.useState(!1),[N,b]=o.useState(""),[I,G]=o.useState(!1),[M,z]=o.useState(!1),[x,A]=o.useState(null);o.useEffect(()=>{io(t).then(n).catch(()=>n(null))},[t]);const _=()=>{if(s&&s!=="loading"){const g=oo(s.preset??null,s.cronExpr);l(g.freq),u(g.hour),p(g.customCron);const K=Aa.includes(s.timezone);S(K?s.timezone:"Other"),C(!K),b(K?"":s.timezone)}else l("daily"),u(6),p(""),S("UTC"),C(!1),b("");A(null),i(!0)},ee=async()=>{G(!0),A(null);try{const K={timezone:f?N.trim()||"UTC":d};r==="custom"?K.cron=m.trim():K.preset=co(r,h);const $=await Wn(t,K);n($),i(!1),Y({title:"Schedule saved",detail:tn($.preset??null,$.cronExpr,$.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(g){A(g instanceof Error?g.message:"Failed to save schedule")}finally{G(!1)}},oe=async()=>{if(!(!s||s==="loading")){G(!0),A(null);try{const g={timezone:s.timezone,enabled:!s.enabled};s.preset?g.preset=s.preset:g.cron=s.cronExpr;const K=await Wn(t,g);n(K),Y({title:K.enabled?"Schedule resumed":"Schedule paused",detail:tn(K.preset??null,K.cronExpr,K.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(g){A(g instanceof Error?g.message:"Failed to update schedule")}finally{G(!1)}}},y=async()=>{z(!0),A(null);try{await lo(t),n(null),i(!1),Y({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(g){A(g instanceof Error?g.message:"Failed to remove schedule")}finally{z(!1)}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Scheduled runs"})]}),!T()&&s!=="loading"&&!a&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:_,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!a&&s===null&&e.jsx(V,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No schedule configured. Set one to automatically trigger visibility sweeps."})}),s!=="loading"&&!a&&s!==null&&e.jsxs(V,{className:"surface-card compact-card",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm font-medium text-strong",children:tn(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-muted",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-muted",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ae,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),!T()&&e.jsx(R,{type:"button",variant:"outline",size:"sm",disabled:I,onClick:de(oe),children:s.enabled?"Pause":"Resume"}),!T()&&e.jsx(R,{type:"button",variant:"ghost",size:"sm",disabled:M,onClick:de(y),children:M?"Removing...":"Remove"})]})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:x})]}),!T()&&a&&e.jsxs("div",{className:"rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Frequency"}),e.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",value:r,onChange:g=>l(g.target.value),children:Dd.map(g=>e.jsx("option",{value:g.value,children:g.label},g.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Time"}),e.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:h,disabled:r==="twice-daily"||r==="custom",onChange:g=>u(parseInt(g.target.value)),children:Array.from({length:24},(g,K)=>e.jsx("option",{value:K,children:ro(K)},K))})]})]}),r==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Cron expression"}),e.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:m,onChange:g=>p(g.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Timezone"}),e.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",value:f?"Other":d,onChange:g=>{g.target.value==="Other"?(C(!0),S("Other")):(C(!1),S(g.target.value))},children:[Aa.map(g=>e.jsx("option",{value:g,children:g},g)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),f&&e.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:N,onChange:g=>b(g.target.value)})]}),x&&e.jsx("p",{className:"text-negative-400 text-sm",children:x}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),A(null)},children:"Cancel"}),e.jsx(R,{type:"button",size:"sm",disabled:I||r==="custom"&&!m.trim(),onClick:de(ee),children:I?"Saving...":"Save schedule"})]})]})]})}const Id=[{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 Td({projectName:t}){const[s,n]=o.useState("loading"),[a,i]=o.useState(!1),[r,l]=o.useState(""),[h,u]=o.useState(["citation.lost","citation.gained"]),[m,p]=o.useState(!1),[d,S]=o.useState(null),[f,C]=o.useState({}),[N,b]=o.useState(new Set);o.useEffect(()=>{uo(t).then(n).catch(()=>n([]))},[t]);const I=x=>{u(A=>A.includes(x)?A.filter(_=>_!==x):[...A,x])},G=async()=>{if(!(!r.trim()||h.length===0)){p(!0),S(null);try{const x=await mo(t,{channel:"webhook",url:r.trim(),events:h});n(A=>A==="loading"?[x]:[...A,x]),l(""),u(["citation.lost","citation.gained"]),i(!1),Y({title:"Webhook added",detail:`Notifications will be sent to ${x.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(x){S(x instanceof Error?x.message:"Failed to add webhook")}finally{p(!1)}}},M=async x=>{if(!N.has(x)){b(A=>new Set(A).add(x));try{await ho(t,x),n(A=>A==="loading"?A:A.filter(_=>_.id!==x)),Y({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${x}`,dedupeMode:"drop"})}catch(A){S(A instanceof Error?A.message:"Failed to remove webhook")}finally{b(A=>{const _=new Set(A);return _.delete(x),_})}}},z=async x=>{C(A=>({...A,[x]:{state:"testing"}}));try{const A=await xo(t,x);C(_=>({..._,[x]:{state:A.ok?"ok":"fail",status:A.status}})),A.ok&&Y({title:"Test notification sent",detail:`Webhook returned status ${A.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${x}`,dedupeMode:"replace"})}catch{C(A=>({...A,[x]:{state:"fail"}}))}};return e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Automation"}),e.jsx("h2",{children:"Notifications"})]}),!T()&&s!=="loading"&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!a),S(null)},children:a?"Cancel":"+ Add webhook"})]}),!T()&&a&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-4 space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Webhook URL"}),e.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:r,onChange:x=>l(x.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-secondary",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:Id.map(x=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-mono-600 bg-mono-800",checked:h.includes(x.value),onChange:()=>I(x.value)}),e.jsx("span",{className:"text-sm text-neutral",children:x.label})]},x.value))})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>{i(!1),S(null)},children:"Cancel"}),e.jsx(R,{type:"button",size:"sm",disabled:m||!r.trim()||h.length===0,onClick:de(G),children:m?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!a&&e.jsx(V,{className:"surface-card compact-card",children:e.jsx("p",{className:"supporting-copy",children:"No webhooks configured. Add one to get alerted when citations change or runs complete."})}),s!=="loading"&&s.length>0&&e.jsxs("div",{className:"evidence-table-wrap",children:[e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:"Endpoint"}),e.jsx("th",{children:"Events"}),e.jsx("th",{children:"Status"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:s.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-neutral break-all",title:x.urlHost,children:x.urlDisplay??x.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.events.map(A=>e.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:A.replace("."," ")},A))})}),e.jsx("td",{children:e.jsx(ae,{tone:x.enabled?"positive":"neutral",children:x.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[f[x.id]&&(()=>{const A=f[x.id],_=A.state==="testing"?"Sending…":A.state==="ok"?`Delivered${A.status?` (${A.status})`:""}`:`Failed${A.status?` (${A.status})`:""}`;return e.jsx(ae,{tone:A.state==="ok"?"positive":A.state==="fail"?"negative":"neutral",children:_})})(),!T()&&e.jsx(R,{variant:"ghost",size:"sm",type:"button",disabled:f[x.id]?.state==="testing",onClick:()=>{z(x.id)},children:"Test"}),!T()&&e.jsx(R,{variant:"ghost",size:"sm",type:"button",disabled:N.has(x.id),onClick:()=>{M(x.id)},children:N.has(x.id)?"Removing…":"Remove"})]})})]},x.id))})]}),d&&e.jsx("p",{className:"text-negative-400 text-sm mt-2",children:d})]})]})}function Wt(t,s){return t.invalidateQueries({predicate:n=>{const a=n.queryKey[0];return typeof a?._id=="string"&&a._id.startsWith(s)}})}function Md(t,s){t.setQueriesData({predicate:n=>n.queryKey[0]==="project-dashboard-full"&&n.queryKey[1]===s.id},n=>!n||typeof n!="object"||!("project"in n)?n:{...n,project:s})}function Ed({projectName:t,refreshNonce:s}){const n=At(),[a,i]=o.useState(null),[r,l]=o.useState([]),[h,u]=o.useState(null),[m,p]=o.useState([]),[d,S]=o.useState([]),[f,C]=o.useState(null),[N,b]=o.useState(""),[I,G]=o.useState(""),[M,z]=o.useState(""),[x,A]=o.useState(!0),[_,ee]=o.useState(!1),[oe,y]=o.useState(null),[g,K]=o.useState("performance");o.useEffect(()=>{$()},[t,s]);async function $(){A(!0),y(null);try{const k=await n.fetchQuery({...Fa({client:W,path:{name:t}}),staleTime:qe});if(i(k),k.connected){const[B,v,J,F]=await Promise.all([n.fetchQuery({..._a({client:W,path:{name:t}}),staleTime:qe}).catch(()=>null),n.fetchQuery({...qa({client:W,path:{name:t}}),staleTime:qe}).catch(()=>[]),n.fetchQuery({...Io({client:W,path:{name:t}}),staleTime:qe}).catch(()=>[]),k.siteUrl?Promise.resolve([]):n.fetchQuery({...To({client:W,path:{name:t}}),staleTime:qe}).then(ce=>ce.sites).catch(()=>[])]);u(B),p(v),S(J),l(F)}else u(null),p([]),S([]),l([])}catch(k){y(k instanceof Error?k.message:"Failed to load Bing data")}finally{A(!1)}}async function q(){if(I.trim()){y(null);try{const k=await Mo(t,I.trim());await Wt(n,"getApiV1ProjectsByNameBing"),G(""),k.availableSites.length>0&&l(k.availableSites),await $()}catch(k){y(k instanceof Error?k.message:"Failed to connect")}}}async function Z(){try{await Eo(t),await Wt(n,"getApiV1ProjectsByNameBing"),i(null),l([]),u(null),p([]),S([]),C(null),z(""),y(null)}catch(k){y(k instanceof Error?k.message:"Failed to disconnect")}}async function le(){if(M)try{await Oo(t,M),await Wt(n,"getApiV1ProjectsByNameBing"),await $()}catch(k){y(k instanceof Error?k.message:"Failed to set site")}}async function te(){if(N.trim())try{const k=await Ga(t,N.trim());await Wt(n,"getApiV1ProjectsByNameBing"),C(k),p(B=>[k,...B])}catch(k){y(k instanceof Error?k.message:"Inspection failed")}}async function fe(k){ee(!0),y(null);try{const B=await Zn(t,{urls:[k]}),{succeeded:v,failed:J,total:F}=B.summary;Y({title:"Bing submission requested",detail:J===0?`${v} URL submitted to Bing.`:`${v}/${F} submitted successfully, ${J} failed.`,tone:J===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${k}`,dedupeMode:"replace"})}catch(B){const v=B instanceof Error?B.message:"Submission failed";y(v),Y({title:"Bing submission failed",detail:v,tone:"negative",dedupeKey:`bing:indexing:${t}:${k}`,dedupeMode:"replace"})}finally{ee(!1)}}async function ue(){ee(!0),y(null),Y({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const k=await Zn(t,{allUnindexed:!0}),{succeeded:B,failed:v,total:J}=k.summary;Y({title:"Bing submissions requested",detail:v===0?`${B}/${J} URL${J!==1?"s":""} submitted to Bing.`:`${B}/${J} submitted successfully, ${v} failed.`,tone:v===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(k){const B=k instanceof Error?k.message:"Batch submission failed";y(B),Y({title:"Bing submissions failed",detail:B,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{ee(!1)}}if(x)return e.jsx(V,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-secondary",children:"Loading Bing data..."})});if(!a?.connected)return T()?e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ae,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Bing Webmaster Tools is not connected for this project."})]}):e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsx(ae,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-neutral",children:"Connect Bing Webmaster Tools to inspect URLs, monitor index coverage, and submit pages for indexing."}),e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"text-xs text-muted",htmlFor:"bing-api-key",children:"API Key"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.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:I,onChange:k=>G(k.target.value),onKeyDown:k=>{k.key==="Enter"&&q()}}),e.jsx(R,{size:"sm",disabled:!I.trim(),onClick:de(q),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-muted",children:["Get your API key from"," ",e.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"})]})]}),oe&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:oe})]});if(!a.siteUrl)return e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{tone:"positive",children:"Connected"}),!T()&&e.jsx(R,{size:"sm",variant:"ghost",onClick:de(Z),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.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."})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.domain})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?et(a.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Select site"}),r.length>0?e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.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:M,onChange:k=>z(k.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),r.map(k=>e.jsxs("option",{value:k.url,children:[k.url,k.verified?" (verified)":""]},k.url))]}),!T()&&e.jsx(R,{size:"sm",disabled:!M,onClick:de(le),children:"Set Site"})]}):e.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."})]})]}),oe&&e.jsx("p",{className:"mt-3 text-xs text-negative-400",children:oe})]});const H=[{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"}],xe=H.find(k=>k.key===g)??H[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Connection"}),e.jsx("h3",{children:"Domain authorization"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ae,{tone:"positive",children:"Connected"}),!T()&&e.jsx(R,{size:"sm",variant:"ghost",onClick:de(Z),children:"Disconnect"})]})]}),oe&&e.jsx("p",{className:"mb-3 text-xs text-negative-400",children:oe}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-positive-500"}),e.jsx("span",{className:"text-sm text-strong",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-muted",children:a.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-muted",children:T()?e.jsxs(e.Fragment,{children:["This project is currently mapped to ",e.jsx("code",{children:a.siteUrl}),"."]}):e.jsxs(e.Fragment,{children:["Canonry stores Bing connections per canonical domain. This project is currently mapped to ",e.jsx("code",{children:a.siteUrl}),"."]})})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-default bg-surface-subtle p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-strong",children:a.updatedAt?et(a.updatedAt):"—"})]})]})]})]}),e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:xe.eyebrow}),e.jsx("h3",{children:xe.title})]}),e.jsx("p",{className:"text-xs text-muted",children:h?.lastInspectedAt?`Last inspected ${et(h.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-base",children:H.map(k=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${g===k.key?"border-mono-200 text-strong":"border-transparent text-muted hover:text-neutral"}`,onClick:()=>K(k.key),children:k.label},k.key))}),g==="coverage"&&h&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Ts,{label:"Indexed",value:h.summary.indexed,tone:"positive"}),e.jsx(Ts,{label:"Not in index",value:h.summary.notIndexed+(h.summary.unknown??0),tone:"negative"}),e.jsx(Ts,{label:"Status unknown",value:h.summary.unknown??0,tone:"neutral"}),e.jsx(Ts,{label:"Coverage",value:`${h.summary.percentage}%`,tone:"neutral"})]}),h.notIndexed.length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Not Indexed (",h.notIndexed.length,")"]}),!T()&&e.jsx(R,{size:"sm",variant:"ghost",disabled:_,onClick:de(ue),children:_?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"HTTP"}),!T()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:h.notIndexed.map(k=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:k.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:k.httpCode??"—"}),!T()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-secondary hover:text-strong underline underline-offset-2",disabled:_,onClick:()=>{fe(k.url)},children:"Submit"})})]},k.id))})]})})]}),(h.unknown??[]).length>0&&e.jsxs("div",{children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-3",children:[e.jsxs("h4",{className:"text-xs font-medium text-secondary",children:["Unknown — not yet confirmed (",(h.unknown??[]).length,")"]}),!T()&&e.jsx(R,{size:"sm",variant:"ghost",disabled:_,onClick:de(ue),children:_?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"}),!T()&&e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(h.unknown??[]).map(k=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:k.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:k.lastCrawledDate?et(k.lastCrawledDate):"—"}),!T()&&e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-secondary hover:text-strong underline underline-offset-2",disabled:_,onClick:()=>{fe(k.url)},children:"Submit"})})]},k.id))})]})})]}),h.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-secondary",children:["Indexed (",h.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:h.indexed.map(k=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:k.url}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:k.lastCrawledDate?et(k.lastCrawledDate):"—"})]},k.id))})]})})]})]}),g==="coverage"&&!h&&e.jsx("p",{className:"mt-4 text-xs text-muted",children:"No coverage data yet. Inspect URLs to build coverage data."}),g==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[!T()&&e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.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:N,onChange:k=>b(k.target.value),onKeyDown:k=>{k.key==="Enter"&&te()}}),e.jsx(R,{size:"sm",disabled:!N.trim(),onClick:de(te),children:"Inspect"})]}),f&&e.jsxs("div",{className:"rounded border border-base bg-bg-elevated/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-strong",children:f.url}),e.jsxs("div",{className:"text-secondary",children:["In Index: ",e.jsx("span",{className:f.inIndex?"text-positive-400":"text-negative-400",children:f.inIndex?"Yes":"No"})," · ","HTTP: ",f.httpCode??"—"," · ","Crawled: ",f.lastCrawledDate??"—"]})]}),m.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:m.map(k=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:k.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ae,{tone:k.inIndex?"positive":"negative",children:k.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:k.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-secondary",children:et(k.inspectedAt)})]},k.id))})]})})]}),g==="performance"&&e.jsx("div",{className:"mt-4",children:d.length===0?e.jsx("p",{className:"text-xs text-muted",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-default",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-base",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-muted font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Is[Mt.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-16",children:Is[Mt.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Is[Mt.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-muted font-medium w-14",children:Is[Mt.Position]})]})}),e.jsx("tbody",{children:d.map((k,B)=>e.jsxs("tr",{className:"border-b border-base/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-neutral truncate max-w-[480px]",children:k.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-strong",children:k.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:k.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-secondary",children:[(Number.isFinite(k.ctr)?k.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-secondary",children:k.averagePosition.toFixed(1)})]},B))})]})})})]})]})}function Od({projectName:t}){const s=At(),[n,a]=o.useState("google"),[i,r]=o.useState(!0),[l,h]=o.useState("idle"),[u,m]=o.useState(null),p=o.useRef(null),[d,S]=o.useState(!1),[f,C]=o.useState(null),[N,b]=o.useState(null),[I,G]=o.useState(!1),[M,z]=o.useState(null),[x,A]=o.useState(null),[_,ee]=o.useState(0);async function oe(k=!1){k||r(!0),m(null);try{const[B,v,J]=await Promise.all([s.fetchQuery(Ea({client:W})).catch(()=>null),s.fetchQuery({...$n({client:W,path:{name:t}}),staleTime:qe}).catch(()=>[]),s.fetchQuery({...Fa({client:W,path:{name:t}}),staleTime:qe}).catch(()=>null)]),F=v.find(U=>U.connectionType==="gsc")??null;S(!!B?.google?.configured),G(!!B?.bing?.configured),C(F),z(J);const[ce,P]=await Promise.all([F?s.fetchQuery({...Da({client:W,path:{name:t}}),staleTime:qe}).catch(()=>null):Promise.resolve(null),J?.connected?s.fetchQuery({..._a({client:W,path:{name:t}}),staleTime:qe}).catch(()=>null):Promise.resolve(null)]);b(ce),A(P)}catch(B){m(B instanceof Error?B.message:"Failed to load search console overview")}finally{r(!1)}}async function y(){if(l!=="idle")return;p.current?.abort();const k=new AbortController;p.current=k;const B=k.signal;h("syncing"),m(null),Y({title:"Refreshing search coverage",detail:"Queueing Google and Bing checks, then reloading the workspaces.",tone:"neutral",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"});const v=[];try{async function J(){if(!f)return;const U=await Do(t);if(!U?.id)return;const we=2e3,$e=Date.now()+12e4;for(;Date.now()<$e;){if(B.aborted||(await new Promise(E=>setTimeout(E,we)),B.aborted))return;const be=await Ta(U.id).catch(()=>null);if(!be)break;if(["completed","failed","cancelled"].includes(be.status)){be.status!=="completed"&&v.push(`Google sync ${be.status}`);break}}}const F=10;async function ce(){if(!M?.connected)return;const U=await s.fetchQuery({...qa({client:W,path:{name:t}}),staleTime:0}).catch(()=>[]),we=[...new Set(U.map(Me=>Me.url))];if(we.length===0){await Ro(t).catch(()=>null);return}for(let Me=0;Me<we.length;Me+=F){if(B.aborted)return;const $e=we.slice(Me,Me+F),E=(await Promise.allSettled($e.map(re=>Ga(t,re)))).filter(re=>re.status==="rejected").length;E>0&&v.push(`${E} Bing inspection(s) failed`)}}const P=await Promise.allSettled([J(),ce()]);for(const U of P)U.status==="rejected"&&v.push(U.reason instanceof Error?U.reason.message:"Sync failed");if(B.aborted)return;if(h("reloading"),await Promise.all([Wt(s,"getApiV1ProjectsByNameGoogleGsc"),Wt(s,"getApiV1ProjectsByNameBing")]),await oe(!0),ee(U=>U+1),v.length>0){const U=`Partial refresh: ${v.join("; ")}`;m(U),Y({title:"Search coverage partially refreshed",detail:U,tone:"caution",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}else Y({title:"Search coverage refreshed",detail:"Google and Bing workspaces are reloaded with the latest stored coverage.",tone:"positive",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}catch(J){if(!B.aborted){const F=J instanceof Error?J.message:"Refresh failed";m(F),Y({title:"Search coverage refresh failed",detail:F,tone:"negative",dedupeKey:`search-console-refresh:${t}`,dedupeMode:"replace"})}}finally{B.aborted||h("idle")}}o.useEffect(()=>(oe(),()=>{p.current?.abort()}),[t]);const g=f?"positive":d?"caution":"negative",K=f?"Connected":d?"Ready to connect":"Needs setup",$=N?`${N.summary.percentage}% indexed`:f?"Awaiting coverage":"No coverage data",q=N?`${N.summary.notIndexed} not indexed${N.summary.deindexed>0?` · ${N.summary.deindexed} deindexed`:""}`:f?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",Z=N?.lastSyncedAt??N?.lastInspectedAt??f?.updatedAt??null,le=M?.connected?"positive":I?"caution":"negative",te=M?.connected?"Connected":I?"Ready to connect":"Needs setup",fe=x?`${x.summary.percentage}% indexed`:M?.connected?"Awaiting coverage":"No coverage data",ue=x?x.summary.notIndexed+(x.summary.unknown??0):0,H=x?`${ue} not in index`:M?.connected?"Inspect URLs to populate coverage":I?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",xe=x?.lastInspectedAt??M?.updatedAt??null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(V,{className:"surface-card",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engines"}),e.jsx("h2",{children:"Coverage & performance"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-muted",children:"Scan both engines at a glance, then open the Google or Bing workspace when you need to inspect coverage or take action."})]}),!T()&&e.jsxs(R,{type:"button",variant:"outline",size:"sm",disabled:i||l!=="idle",onClick:()=>{y()},children:[e.jsx(gt,{className:`h-3.5 w-3.5 ${l!=="idle"?"animate-spin":""}`,"aria-hidden":"true"}),i?"Loading…":l==="syncing"?"Refreshing Google & Bing…":l==="reloading"?"Reloading workspaces…":"Refresh all"]})]}),u&&e.jsx("div",{className:"mb-3 rounded-lg border border-negative-800/40 bg-negative-950/20 px-3 py-2 text-sm text-negative",children:u}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(la,{eyebrow:"Google",title:"Google Search Console",status:i?"Loading…":K,tone:i?"neutral":g,targetLabel:"Selected property",targetValue:f?.propertyId??"No property selected",coverageValue:i?"Loading…":$,note:i?"Loading overview…":q,updatedAt:Z,active:n==="google",onClick:()=>a("google")}),e.jsx(la,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:i?"Loading…":te,tone:i?"neutral":le,targetLabel:"Selected site",targetValue:M?.siteUrl??"No site selected",coverageValue:i?"Loading…":fe,note:i?"Loading overview…":H,updatedAt:xe,active:n==="bing",onClick:()=>a("bing")})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([k,B])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===k,className:`project-subnav-link ${n===k?"project-subnav-link-active":""}`,onClick:()=>a(k),children:B},k))}),n==="google"&&e.jsx(Il,{projectName:t,refreshNonce:_}),n==="bing"&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search engine"}),e.jsx("h2",{children:"Bing Webmaster Tools"})]})}),e.jsx(Ed,{projectName:t,refreshNonce:_})]})]})}function Bd(t,s=4){return t.length<=s?t.map(a=>`"${a}"`).join(", "):`${t.slice(0,s).map(a=>`"${a}"`).join(", ")}, and ${t.length-s} more`}function ys({label:t,summary:s,displayValue:n,tooltip:a}){const i=s.value.trim()!==""&&Number.isFinite(Number(s.value)),r=s.progress!==void 0?Math.min(Math.max(s.progress,0),100):0;return e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("p",{className:"aeo-hero-row-label",children:[t,(a||s.tooltip)&&e.jsx(Te,{text:a||s.tooltip||""})]}),e.jsx("p",{className:`aeo-hero-row-value ${wo[s.tone]}`,children:n??e.jsxs(e.Fragment,{children:[s.value,i?e.jsx("span",{className:"text-faint",children:"%"}):null]})}),e.jsx("div",{className:"aeo-hero-row-bar","aria-hidden":"true",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.tone}`,style:{width:`${r}%`}})}),e.jsx("p",{className:"aeo-hero-row-detail",children:s.delta})]})}function Fd({model:t,sweepRunning:s,onJumpToEvidence:n,onJumpToActions:a}){const i=t.citationMovement,r=t.mentionMovement,l=t.movementComparison,h=t.recentRuns.find(M=>M.kind===Ft["answer-visibility"]),u=t.insights.find(M=>M.actionGroup==="investigate")??t.insights.find(M=>M.actionGroup==="write")??t.insights.at(0),m=t.suggestedQueries.rows.at(0),p=new Set(t.providerScores.map(M=>M.provider)).size,d=t.project.locations.length,S=M=>M.tone==="positive"?"improved":M.tone==="negative"?"declined":M.gained>0||M.lost>0?"mixed":"steady",f=S(r),C=S(i),N=(()=>{if(s)return"A fresh sweep is running now";if(!l.hasPreviousRun)return"Baseline captured. The next sweep will show change.";if(l.querySetChanged)return"Tracking scope changed since the previous sweep";if(f===C)return f==="steady"?"Answer mentions and citation coverage held steady":f==="mixed"?"Answer mention and citation movement was mixed":`Answer mentions and citation coverage ${f}`;const M=f==="mixed"?"Answer mention movement was mixed":f==="steady"?"Answer mentions held steady":`Answer mentions ${f}`,z=C==="mixed"?"citation movement was mixed":C==="steady"?"citation coverage held steady":`citation coverage ${C}`;return`${M}; ${z}`})(),b=[...new Set([...r.lostQueries??[],...i.lostQueries??[],...r.gainedQueries??[],...i.gainedQueries??[]])],I=`${t.queryCounts.total} ${t.queryCounts.total===1?"query":"queries"} across ${p} ${p===1?"engine":"engines"}`,G=d>0?`${d} ${d===1?"location":"locations"}`:"project-wide";return e.jsxs("section",{className:"overview-brief","aria-labelledby":"overview-brief-title",children:[e.jsxs("div",{className:"overview-brief-head",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft",children:["Operator brief",e.jsx(Te,{text:"Each sweep records two independent signals: answer mentions (your brand named in the answer text) and source citations (your domain in the engine's source list). They move separately."})]}),e.jsx("h2",{id:"overview-brief-title",className:"overview-brief-title",children:N}),e.jsxs("p",{className:"overview-brief-scope",children:["Tracking ",I,", ",G,"."]})]}),e.jsx("p",{className:"overview-brief-updated",children:h?`Latest sweep ${h.startedAt}`:"No sweep completed yet"})]}),e.jsxs("div",{className:"overview-brief-grid",children:[e.jsxs("div",{className:"overview-brief-panel overview-brief-coverage",children:[e.jsx("p",{className:"overview-brief-label",children:"Coverage now"}),e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(ys,{label:"Mentioned",summary:t.mentionSummary}),e.jsx(ys,{label:"Cited",summary:t.visibilitySummary})]}),t.mentionSummary.providerCoverage&&e.jsxs("p",{className:"overview-brief-note",children:["Partial sweep: ",t.mentionSummary.providerCoverage]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Since previous sweep"}),l.hasPreviousRun?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"overview-signal-change-list",children:[e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Mentioned"}),e.jsxs("span",{className:"text-positive-400",children:["+",r.gained]}),e.jsxs("span",{className:"text-negative-400",children:["-",r.lost]})]}),e.jsxs("div",{className:"overview-signal-change-row",children:[e.jsx("span",{className:"overview-signal-change-label",children:"Cited"}),e.jsxs("span",{className:"text-positive-400",children:["+",i.gained]}),e.jsxs("span",{className:"text-negative-400",children:["-",i.lost]})]})]}),e.jsx("p",{className:`overview-brief-panel-copy ${l.querySetChanged?"text-caution-400/80":""}`,children:l.querySetChanged?`Query basket changed: +${l.addedQueryCount} added, -${l.removedQueryCount} removed. Movement compares ${l.comparableQueryCount} shared queries.`:`Same ${l.comparableQueryCount}-query basket${l.previousRunAt?` since ${et(l.previousRunAt)}`:""}.`}),b.length>0&&e.jsxs("p",{className:"overview-brief-panel-copy",children:["Affected: ",Bd(b,2)]}),e.jsx("button",{type:"button",className:"overview-brief-link",onClick:n,children:"Review query evidence"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No comparison yet"}),e.jsx("p",{className:"overview-brief-panel-copy",children:"Run another sweep to measure mention and citation movement."})]})]}),e.jsxs("div",{className:"overview-brief-panel",children:[e.jsx("p",{className:"overview-brief-label",children:"Next action"}),u?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:u.title}),u.detail&&e.jsx("p",{className:"overview-brief-panel-copy",children:u.detail}),e.jsx("button",{type:"button",className:"overview-brief-link",onClick:a,children:"Open action queue"})]}):m?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"overview-brief-panel-title",children:["Consider tracking “",m.query,"”"]}),e.jsx("p",{className:"overview-brief-panel-copy",children:m.reason}),e.jsx("button",{type:"button",className:"overview-brief-link",onClick:a,children:"Review query suggestions"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"overview-brief-panel-title",children:"No outstanding action"}),e.jsx("p",{className:"overview-brief-panel-copy",children:T()?"Keep monitoring. Regressions and new query opportunities will surface here.":"Keep monitoring. Canonry will surface regressions and new query opportunities here."})]})]})]})]})}function fn({id:t,eyebrow:s,title:n,meta:a,defaultOpen:i=!1,children:r}){return e.jsxs("details",{id:t,className:"overview-disclosure page-section-divider scroll-mt-24",open:i||void 0,children:[e.jsxs("summary",{className:"overview-disclosure-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"eyebrow eyebrow-soft",children:s}),e.jsx("span",{className:"overview-disclosure-title",children:n})]}),e.jsxs("span",{className:"overview-disclosure-meta",children:[a&&e.jsx("span",{children:a}),e.jsx(Ys,{className:"overview-disclosure-icon",size:16,"aria-hidden":"true"})]})]}),e.jsx("div",{className:"overview-disclosure-body",children:r})]})}function _d({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const a=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(a===0)return null;const i=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(l=>({label:l.domain,mentions:l.mentionSnapshots,isYou:!1}))].sort((l,h)=>h.mentions-l.mentions),r=i[0]?.mentions??1;return e.jsxs("div",{className:"mention-share-breakdown",children:[e.jsx("p",{className:"mention-share-breakdown-title",children:"Mention share breakdown · latest run"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:i.map(l=>{const h=l.mentions/a*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${l.isYou?"text-heading font-medium":"text-secondary"}`,children:l.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${l.isYou?"bg-positive-500/70":"bg-mono-500/60"}`,style:{width:`${Math.max(l.mentions/r*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:l.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[h.toFixed(1),"%"]})]},l.label)})})]})}const qd={write:{title:"Write or update content",subtitle:"Queries with no answer, persistent gaps, or competitors winning the spot"},investigate:{title:"Investigate what changed",subtitle:"Citations or mentions you lost since the previous run"},monitor:{title:"Keep monitoring",subtitle:"Gains, new providers picking you up, holding ground"}};function Gd({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:a}=$a(),[i,r]=o.useState(null),l=s.rows.length>0;if(t.length===0&&!l)return e.jsx("p",{className:"text-sm text-muted",children:"No outstanding opportunities. Trigger a sweep to surface fresh signals."});const h=["investigate","write","monitor"],u=new Map;for(const m of t){const p=u.get(m.actionGroup)??[];p.push(m),u.set(m.actionGroup,p)}return e.jsxs("div",{className:"opportunities-grid",children:[h.map(m=>{const p=u.get(m);if(!p||p.length===0)return null;const d=qd[m],S=e.jsx("div",{className:"opportunity-card-list",children:p.map(f=>{const C=i===f.id,N=f.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${f.tone} ${N?"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-400":""}`,onClick:N?()=>r(C?null:f.id):void 0,onKeyDown:N?b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),r(C?null:f.id))}:void 0,tabIndex:N?0:void 0,role:N?"button":void 0,"aria-expanded":N?C:void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[N&&e.jsx(Ws,{size:12,className:`mt-1 shrink-0 text-muted transition-transform duration-150 ${C?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-heading leading-snug",children:f.title}),f.detail&&e.jsx("p",{className:"text-[11px] text-muted mt-0.5 leading-snug",children:f.detail})]})]})}),C&&e.jsx("div",{className:"opportunity-item-detail",children:f.affectedPhrases.map((b,I)=>e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx(vn,{state:b.citationState}),e.jsx("span",{className:"text-xs text-neutral truncate",children:b.query}),b.provider&&e.jsx(Xt,{provider:b.provider})]}),b.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-secondary hover:text-strong whitespace-nowrap",onClick:G=>{G.stopPropagation(),a(b.evidenceId)},children:"View →"})]},b.evidenceId||`${f.id}-${I}`))})]},f.id)})});return m==="monitor"?e.jsxs("details",{className:"opportunity-card opportunity-card-monitor opportunity-monitor",children:[e.jsxs("summary",{className:"opportunity-monitor-summary",children:[e.jsxs("span",{children:[e.jsx("span",{className:"opportunity-card-title",children:d.title}),e.jsx("span",{className:"opportunity-card-subtitle mt-1 block",children:d.subtitle})]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opportunity-card-count",children:p.length}),e.jsx(Ys,{className:"opportunity-monitor-icon text-muted",size:14,"aria-hidden":"true"})]})]}),S]},m):e.jsxs("div",{className:`opportunity-card opportunity-card-${m}`,children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:d.title}),e.jsx("span",{className:"opportunity-card-count",children:p.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:d.subtitle}),S]},m)}),l&&e.jsx(Ud,{suggestedQueries:s,projectName:n})]})}function Ud({suggestedQueries:t,projectName:s}){const n=Lo(),[a,i]=o.useState(new Set),r=p=>{i(d=>new Set(d).add(p)),n.mutate({projectName:s,queries:[p]},{onSuccess:()=>{Y({tone:"positive",title:`Tracking "${p}"`}),i(d=>{const S=new Set(d);return S.delete(p),S})},onError:d=>{Y({tone:"negative",title:`Couldn't add "${p}"`,detail:String(d)}),i(S=>{const f=new Set(S);return f.delete(p),f})}})},{rows:l,totalCandidates:h,skippedAlreadyTracked:u}=t,m=u>0?`GSC queries you're getting impressions for · ${u} already tracked`:"GSC queries you're getting impressions for but aren't tracking yet";return e.jsxs("div",{className:"opportunity-card opportunity-card-track",children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:"Track new queries"}),e.jsx("span",{className:"opportunity-card-count",children:h>l.length?`${l.length} of ${h}`:l.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:m}),e.jsx("div",{className:"opportunity-card-list",children:l.map(p=>{const d=a.has(p.query);return e.jsxs("div",{className:"opportunity-item opportunity-item-neutral flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-heading leading-snug truncate",title:p.query,children:p.query}),e.jsx("p",{className:"text-[11px] text-muted mt-0.5 leading-snug",children:p.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:d,onClick:()=>r(p.query),children:d?"Adding…":"+ Track"})]},p.query)})})]})}function su(t){const{projectName:s}=Si({from:"/projects/$projectName"}),a=po()?.dashboard.projects.find(S=>S.project.name===s||S.project.id===s)?.project.name??null,i=ve({...go({client:W}),enabled:!a}),r=a??i.data?.find(S=>S.name===s||S.id===s)?.name??null,{commandCenter:l,isLoading:h,latestVisibilityRevision:u,refetch:m}=fo(r),p=!a&&i.isLoading||h;return!r&&!a&&i.isSuccess&&!h?e.jsx("div",{className:"page-container",children:e.jsxs(V,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project named "',s,'".']}),e.jsx(R,{asChild:!0,children:e.jsx(ft,{to:"/",children:"Return to overview"})})]})}):!l||p?e.jsxs("div",{className:"page-skeleton",children:[e.jsxs("div",{className:"page-skeleton-header",children:[e.jsx("div",{className:"skeleton-text h-6 w-48"}),e.jsx("div",{className:"skeleton-text-sm w-32"})]}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(S=>e.jsxs("div",{className:"page-skeleton-card flex flex-col items-center",children:[e.jsx("div",{className:"skeleton-circle size-20"}),e.jsx("div",{className:"skeleton-text w-16 mt-3"})]},S))}),e.jsxs("div",{className:"page-skeleton-card",children:[e.jsx("div",{className:"skeleton-text w-28"}),e.jsx("div",{className:"space-y-2 mt-2",children:[1,2,3,4].map(S=>e.jsx("div",{className:"skeleton-text-sm w-full"},S))})]})]}):e.jsx(zd,{model:l,refetch:m,latestVisibilityRevision:u,...t})}function Qd({items:t,activeTab:s}){const[n,a]=o.useState(!1),i=o.useRef(null);if(o.useEffect(()=>{if(!n)return;const l=u=>{i.current&&!i.current.contains(u.target)&&a(!1)},h=u=>{u.key==="Escape"&&a(!1)};return document.addEventListener("pointerdown",l),document.addEventListener("keydown",h),()=>{document.removeEventListener("pointerdown",l),document.removeEventListener("keydown",h)}},[n]),t.length===0)return null;const r=t.some(l=>l.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:i,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${r?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>a(l=>!l),children:["More",e.jsx(Ys,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(l=>e.jsx(ft,{to:l.href,role:"menuitem",className:`project-subnav-menu-item ${l.key===s?"project-subnav-menu-item-active":""}`,"aria-current":l.key===s?"page":void 0,onClick:()=>a(!1),children:l.label},l.key))}):null]})}function zd({tab:t,model:s,refetch:n,latestVisibilityRevision:a}){const i=ki(),r=At(),l=o.useMemo(()=>bo()?.projectTabs,[]),h=jo(t,l),u=o.useMemo(()=>s.competitors.map(j=>j.domain),[s.competitors]),[m,p]=o.useState(!1),[d,S]=o.useState(!1),[f,C]=o.useState(!1),[N,b]=o.useState(""),[I,G]=o.useState(!1),[M,z]=o.useState(null),[x,A]=o.useState(!1),[_,ee]=o.useState(""),[oe,y]=o.useState(!1),[g,K]=o.useState(!1),[$,q]=o.useState(""),[Z,le]=o.useState(!1),[te,fe]=o.useState(!1),[ue,H]=o.useState(""),[xe,k]=o.useState(!1),[B,v]=o.useState(void 0),[J,F]=o.useState(!1),[ce,P]=o.useState(null),[U,we]=o.useState(null),[Me,$e]=o.useState(!1),be=s?.visibilityEvidence??[],E=s?.project.name??"",re=s?.project.displayName||s?.project.name||E,je=yo(),pe=(s?.recentRuns??[]).some(j=>j.kind===Ft["answer-visibility"]&&(j.status===Yn.running||j.status===Yn.queued)),ye=o.useMemo(()=>(s?.project.locations??[]).map(j=>j.label),[s?.project.locations]),O=o.useMemo(()=>new Set(be.map(j=>j.location??"")),[be]),Se=O.has(""),Pe=o.useMemo(()=>[...new Set(be.map(j=>j.query))].sort((j,se)=>j.localeCompare(se)),[be]),Qe=o.useMemo(()=>{const j=[...O].filter(Boolean);return j.length>1?j:ye},[O,ye]);o.useEffect(()=>{if(B===void 0||B===""||!E){we(null),$e(!1);return}$e(!0),vo(E,B,20).then(j=>{we(j),$e(!1)}).catch(()=>{we(null),$e(!1)})},[B,E]);const L=o.useMemo(()=>{if(!U)return null;const j=new Map;for(const se of U){for(const[ne,ze]of Object.entries(se.providerRuns??{}))j.set(`${se.query}::${ne}`,ze.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})));(!se.providerRuns||Object.keys(se.providerRuns).length===0)&&j.set(`${se.query}::`,se.runs.map(ne=>({runId:ne.runId,citationState:ne.citationState,createdAt:ne.createdAt,answerMentioned:ne.answerMentioned,visibilityState:ne.visibilityState,visibilityTransition:ne.visibilityTransition,mentionState:ne.mentionState,mentionTransition:ne.mentionTransition})))}return j},[U]),Ne=o.useMemo(()=>{let j=B!==void 0?be.filter(se=>B===""?!se.location:se.location===B):be;if(ce){const se=ce.toLowerCase();j=j.filter(ne=>ne.competitorDomains.some(ze=>ze.toLowerCase()===se))}return L?j.map(se=>{const ne=L.get(`${se.query}::${se.provider}`)??L.get(`${se.query}::`);return ne?{...se,runHistory:ne}:se}):j},[be,B,ce,L]);async function Oe(){try{await je.mutateAsync({projectName:E,projectLabel:re,sourceAction:"project-run"}),n()}catch{}}async function at(){S(!0);try{await No(E),Y({title:"Project deleted",detail:`${re} was removed.`,tone:"positive",dedupeKey:`project:delete:${E}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(j){console.error("Failed to delete project:",j)}finally{S(!1)}}async function Le(){const j=N.split(`
|
|
7
|
-
`).map(se=>se.trim()).filter(Boolean);if(j.length!==0){G(!0);try{await Ao(E,j),n(),b("")}finally{G(!1)}}}async function it(j){z(j);try{await Co(E,[j]),n()}catch(se){Y({title:"Could not remove query",detail:se instanceof Error?se.message:`Failed to remove "${j}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{z(null)}}async function rt(){const j=_.trim();if(j){y(!0);try{await So(E,[j]),n(),ee(""),A(!1)}finally{y(!1)}}}async function _t(j){const se=s.competitors.find(ne=>ne.domain===j);if(!se){Y({title:"Could not remove competitor",detail:`Could not find ${j} in the tracked competitor list`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"});return}try{await ko(E,se.id),n()}catch(ne){Y({title:"Could not remove competitor",detail:ne instanceof Error?ne.message:`Failed to remove ${se.domain}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function $t(){const j=$.trim();if(j){le(!0);try{const se=s?.project.ownedDomains??[];await Jn(E,[...se,j]),n(),q(""),K(!1)}finally{le(!1)}}}async function rs(j){le(!0);try{const se=s?.project.ownedDomains??[];await Jn(E,se.filter(ne=>ne!==j)),n()}finally{le(!1)}}async function De(){const j=ue.trim();if(j){k(!0);try{const se=s?.project.aliases??[],ne=j.toLowerCase();if(se.some(ze=>ze.toLowerCase()===ne)){H(""),fe(!1);return}await Xn(E,[...se,j]),n(),H(""),fe(!1)}finally{k(!1)}}}async function os(j){k(!0);try{const se=s?.project.aliases??[];await Xn(E,se.filter(ne=>ne!==j)),n()}finally{k(!1)}}async function Be(j,se){const ne=await $o(j,se);return await r.invalidateQueries({queryKey:Oa({client:W})}),r.setQueryData(Po({client:W,path:{name:j}}),ne),Md(r,ne),ne}const We=`/projects/${encodeURIComponent(s.project.name)}`,Pt=[{key:"overview",label:"Overview",href:We},{key:"search-console",label:"Search Engines",href:`${We}/search-console`},{key:"activity",label:"Activity",href:`${We}/activity`},{key:"technical-aeo",label:"Technical AEO",href:`${We}/technical-aeo`},{key:"local",label:"Local Presence",href:`${We}/local`},{key:"discovery",label:"Query Discovery",href:`${We}/discovery`},{key:"backlinks",label:"Backlinks",href:`${We}/backlinks`}],yt=[{key:"report",label:"Report",href:`${We}/report`},{key:"history",label:"Change History",href:`${We}/history`}],ls=Pt.filter(j=>sn(j.key,l)),Lt=yt.filter(j=>sn(j.key,l)),ct=sn("settings",l)?{key:"settings",label:"Settings",href:`${We}/settings`}:null;function Fe(j,se=!1){const ne=document.getElementById(j);if(!ne)return;se&&ne instanceof HTMLDetailsElement&&(ne.open=!0);const ze=window.matchMedia("(prefers-reduced-motion: reduce)").matches;window.requestAnimationFrame(()=>{ne.scrollIntoView({behavior:ze?"auto":"smooth",block:"start"}),(ne instanceof HTMLDetailsElement?ne.querySelector("summary"):ne)?.focus({preventScroll:!0})})}return e.jsxs("div",{className:"page-container",children:[m?e.jsxs(V,{className:"surface-card p-6 mb-6 border-negative-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-negative-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-secondary mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-strong",children:s.project.displayName||s.project.name})," and all its queries, competitors, runs, and snapshots. This cannot be undone."]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(R,{type:"button",variant:"destructive",disabled:d,onClick:de(at),children:d?"Deleting...":"Yes, delete project"}),e.jsx(R,{type:"button",variant:"outline",disabled:d,onClick:()=>p(!1),children:"Cancel"})]})]}):null,e.jsxs("div",{className:"page-header",children:[e.jsxs("div",{className:"page-header-left",children:[e.jsx("h1",{className:"page-title",children:s.project.displayName||s.project.name}),e.jsxs("p",{className:"page-subtitle",children:[s.project.canonicalDomain,!T()&&(s.project.ownedDomains??[]).length===0&&!g&&e.jsx("button",{type:"button",className:"ml-2 rounded px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-secondary hover:text-strong hover:bg-surface-inset transition-colors",onClick:()=>K(!0),children:"+ add domain"})," "," · ",s.contextLabel]}),!T()&&e.jsxs("div",{className:"tag-row",children:[e.jsx("span",{className:"tag",children:s.project.country}),e.jsx("span",{className:"tag",children:s.project.language.toUpperCase()}),s.project.tags.map(j=>e.jsx("span",{className:"tag",children:j},j))]}),((s.project.ownedDomains??[]).length>0||g)&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] uppercase tracking-wide text-muted mr-1",children:"Also tracking"}),(s.project.ownedDomains??[]).map(j=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-strong/60 bg-surface-inset-hover px-2 py-0.5 text-xs text-neutral",children:[j,!T()&&e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-muted hover:bg-mono-700/40 hover:text-strong transition-colors",disabled:Z,onClick:()=>{rs(j)},"aria-label":`Remove ${j}`,children:"×"})]},j)),T()?null:g?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-1.5 py-0.5 text-xs text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none w-40",type:"text",placeholder:"docs.example.com",value:$,onChange:j=>q(j.target.value),onKeyDown:j=>{j.key==="Enter"&&$t()},autoFocus:!0}),e.jsx(R,{type:"button",size:"sm",disabled:!$.trim()||Z,onClick:de($t),children:Z?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-neutral",onClick:()=>{K(!1),q("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-strong px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted hover:text-neutral hover:border-mono-500 transition-colors",onClick:()=>K(!0),children:"+ domain"})]}),(!T()||(s.project.aliases??[]).length>0)&&e.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] uppercase tracking-wide text-muted mr-1",children:["Also known as",e.jsx(Te,{text:"Extra brand names checked against LLM answer text alongside the project name. Use for product names, prior names, or DBAs (e.g. add Meta as an alias to facebook.com). Changing these recomputes mentions on historical runs."})]}),(s.project.aliases??[]).map(j=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-strong/60 bg-surface-inset-hover px-2 py-0.5 text-xs text-neutral",children:[j,!T()&&e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-muted hover:bg-mono-700/40 hover:text-strong transition-colors",disabled:xe,onClick:()=>{os(j)},"aria-label":`Remove ${j}`,children:"×"})]},j)),T()?null:te?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-strong bg-transparent px-1.5 py-0.5 text-xs text-strong placeholder-mono-600 focus:border-mono-500 focus:outline-none w-40",type:"text",placeholder:"LlamaParse",value:ue,onChange:j=>H(j.target.value),onKeyDown:j=>{j.key==="Enter"&&De()},autoFocus:!0}),e.jsx(R,{type:"button",size:"sm",disabled:!ue.trim()||xe,onClick:de(De),children:xe?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-muted hover:text-neutral",onClick:()=>{fe(!1),H("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-strong px-2 py-0.5 text-[10px] uppercase tracking-wide text-muted hover:text-neutral hover:border-mono-500 transition-colors",onClick:()=>fe(!0),children:"+ alias"})]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-muted",children:s.dateRangeLabel}),!T()&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R,{type:"button",variant:"outline",size:"icon",onClick:()=>p(!0),"aria-label":"Delete project",children:e.jsx(Ho,{className:"h-4 w-4 text-secondary"})}),e.jsx(R,{type:"button",disabled:je.isPending||pe,onClick:de(Oe),children:je.isPending?"Starting…":pe?"Sweep running…":"Run now"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[ls.map(j=>e.jsx(ft,{to:j.href,className:`project-subnav-link ${j.key===h?"project-subnav-link-active":""}`,"aria-current":j.key===h?"page":void 0,children:j.label},j.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Qd,{items:Lt,activeTab:h}),ct&&e.jsx(ft,{to:ct.href,className:`project-subnav-link ${h==="settings"?"project-subnav-link-active":""}`,"aria-current":h==="settings"?"page":void 0,children:ct.label},ct.key)]})]}),h==="overview"?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"page-section-divider",children:e.jsx(Gc,{projectName:s.project.name,competitorDomains:u,analyticsRevision:a})}),e.jsx(Fd,{model:s,sweepRunning:pe,onJumpToEvidence:()=>Fe("evidence-section",!0),onJumpToActions:()=>Fe("action-queue")}),e.jsxs("section",{className:"page-section-divider",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Competitive"}),e.jsx("h2",{children:"Where competitors are winning"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),!T()&&e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>A(!x),children:x?"Cancel":"+ Add competitor"})]})]}),e.jsxs("div",{className:"aeo-hero competitive-summary",children:[e.jsxs("div",{className:"aeo-hero-rows",children:[e.jsx(ys,{label:"Mention share",summary:s.mentionShareSummary,tooltip:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the percentage that were you. Measured from the latest sweep."}),e.jsx(ys,{label:"Mention gaps",summary:s.mentionGaps,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was mentioned in the answer but your brand was not."}),e.jsx(ys,{label:"Citation gaps",summary:s.gapQueries,displayValue:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-primary",children:s.gapQueries.value}),e.jsxs("span",{className:"text-faint",children:[" / ",s.queryCounts.total]})]}),tooltip:"Queries where a competitor was cited as a source but you were not."})]}),e.jsx(_d,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name})]}),x&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[e.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:"competitor.com",value:_,onChange:j=>ee(j.target.value),onKeyDown:j=>{j.key==="Enter"&&rt()}}),e.jsx(R,{type:"button",size:"sm",disabled:!_.trim()||oe,onClick:de(rt),children:oe?"Adding...":"Add"})]}),s.competitors.length>0&&e.jsxs("details",{className:"inline-disclosure mt-4",children:[e.jsx("summary",{children:"Review tracked competitors"}),e.jsx("div",{className:"mt-3",children:e.jsx(bl,{competitors:s.competitors,onSelectCompetitor:j=>{P(j),Fe("evidence-section",!0)},onRemoveCompetitor:T()?void 0:j=>{_t(j)},activeFilter:ce})})]})]}),e.jsxs(fn,{id:"evidence-section",eyebrow:"Tracked coverage",title:"Query evidence",meta:`${s.queryCounts.total} ${s.queryCounts.total===1?"query":"queries"}`,defaultOpen:T(),children:[!T()&&e.jsx("div",{className:"mb-3 flex items-center justify-end",children:e.jsx(R,{type:"button",variant:"outline",size:"sm",onClick:()=>C(!f),children:f?"Done":"Manage queries"})}),!T()&&f&&e.jsxs("div",{className:"mb-3 rounded-lg border border-base bg-bg-elevated/40 p-3",children:[Pe.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-mono-800/60 overflow-y-auto rounded border border-default",children:Pe.map(j=>e.jsxs("li",{className:"flex items-center justify-between gap-3 px-3 py-2",children:[e.jsx("span",{className:"min-w-0 truncate text-sm text-strong",title:j,children:j}),e.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 ${j}`,title:`Stop tracking "${j}"`,disabled:M!==null,onClick:()=>{it(j)},children:M===j?"Removing…":"Remove"})]},j))}):e.jsx("p",{className:"mb-3 text-xs text-muted",children:"No queries tracked yet. Add some below."}),e.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:N,onChange:j=>b(j.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-muted",children:[N.split(`
|
|
8
|
-
`).filter(j=>j.trim()).length," to add"]}),e.jsx(R,{type:"button",size:"sm",disabled:!N.trim()||I,onClick:de(Le),children:I?"Adding...":"Add queries"})]})]}),s.project.locations.length>0&&e.jsxs("div",{className:"filter-row mb-3",role:"toolbar","aria-label":"Location filters",children:[e.jsx("button",{className:`filter-chip ${B===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":B===void 0,onClick:()=>{v(void 0)},children:"All locations"}),s.project.locations.map(j=>e.jsx("button",{className:`filter-chip ${B===j.label?"filter-chip-active":""}`,type:"button","aria-pressed":B===j.label,onClick:()=>{v(j.label),F(!1)},children:j.label},j.label)),Se&&e.jsx("button",{className:`filter-chip ${B===""?"filter-chip-active":""}`,type:"button","aria-pressed":B==="",onClick:()=>{v(""),F(!1)},children:"No location"}),Qe.length>1&&B===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${J?"filter-chip-active":""}`,type:"button","aria-pressed":J,onClick:()=>F(j=>!j),title:"Side-by-side location comparison",children:"Compare"})]}),ce&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-negative-900/40 bg-negative-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-negative-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-strong",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:ce})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-secondary hover:text-strong",onClick:()=>P(null),children:"Clear filter ×"})]}),e.jsx(hl,{evidence:Ne,compareLocations:J})]}),e.jsxs(fn,{eyebrow:"Analysis",title:"Citation and engine diagnostics",meta:"Deep dive",defaultOpen:T(),children:[e.jsx(oc,{projectName:s.project.name}),s.providerScores.length>1&&e.jsxs("section",{className:"page-section-divider",children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Model breakdown"}),e.jsxs("h2",{children:["Citation rate by model ",e.jsx(Te,{text:"Per-model citation rate in the latest sweep. The same query set can perform differently across engines."})]})]})}),e.jsx("div",{className:"evidence-table-wrap",children:e.jsxs("table",{className:"evidence-table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{scope:"col",children:"Model"}),e.jsx("th",{scope:"col",children:"Citation rate"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(j=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Xt,{provider:j.provider}),j.model&&e.jsx("span",{className:"text-[11px] font-mono text-muted",children:j.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:"font-semibold text-strong",children:[j.score,"%"]})}),e.jsxs("td",{className:"text-muted",children:[j.cited," of ",j.total]})]},`${j.provider}::${j.model??"unknown"}`))})]})})]})]}),!T()&&e.jsx(fn,{eyebrow:"Run history",title:"Recent execution history",meta:`${s.recentRuns.length} recent`,children:e.jsx("div",{className:"run-list",children:s.recentRuns.map(j=>e.jsx(Bo,{run:j},j.id))})}),e.jsxs("section",{id:"action-queue",className:"page-section-divider scroll-mt-24 rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mono-500/60",tabIndex:-1,children:[e.jsx("div",{className:"section-head section-head-inline",children:e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Action queue"}),e.jsx("h2",{children:"What needs your attention"})]})}),e.jsx(Gd,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:E})]})]}):h==="settings"?e.jsxs(e.Fragment,{children:[e.jsx($d,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:async(j,se)=>{await Be(j,se)},onRefresh:()=>{n()}}),e.jsx(Ld,{project:s.project,onSave:async j=>{await Be(s.project.name,j)}}),e.jsx(Rd,{projectName:s.project.name}),e.jsx(Td,{projectName:s.project.name})]}):h==="report"?e.jsx(md,{projectName:s.project.name}):h==="discovery"?e.jsx(Jc,{projectName:E}):h==="technical-aeo"?e.jsx(od,{projectName:s.project.name,projectId:s.project.id}):h==="history"?e.jsx(ld,{projectName:s.project.name}):h==="activity"?e.jsx(wl,{projectName:s.project.name}):h==="backlinks"?e.jsx(rc,{projectName:s.project.name}):h==="local"?e.jsx(Ml,{projectName:s.project.name,projectId:s.project.id}):e.jsx(Od,{projectName:s.project.name})]})}export{su as ProjectPage,Md as patchProjectDashboardCache};
|