@ainyc/canonry 4.75.0 → 4.76.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.
@@ -1,6 +1,6 @@
1
- import{j as e,r,L as dt,n as mt,u as De,o as Kt,A as vi,h as Ni}from"./vendor-tanstack-Dq7p98wZ.js";import{c as ps,T as ie,t as wi,a as zi,u as Tn,C as Si,b as gs,P as $t,B as C,h as ki,d as Ci,e as Ai,f as Je,g as U,i as Z,I as Ne,j as Ut,k as Li,l as _,m as Di,n as $i,o as Ii,p as Pi,q as En,r as Ri,s as Ti,S as ft,v as Ei,w as Mi,x as Oi,y as Fi,z as rn,A as Gi,G as Ce,D as Bs,E as Bi,F as qi,H as _i,J as Ui,K as Qi,L as se,M as cn,N as Mn,O as Ki,Q as Vi,R as Hi,U as Wi,V as Yi,W as Ji,X as Xi,Y as Zi,Z as ea,_ as ta,$ as sa,a0 as na,a1 as ia,a2 as aa,a3 as ds,a4 as ra,a5 as ca,a6 as ln,a7 as la,a8 as oa,a9 as da,aa as xa,ab as xs,ac as ma,ad as ua,ae as ha,af as Ms,ag as pa,ah as ga,ai as fa,aj as ja,ak as ba,al as Vt,am as On,an as Fn,ao as ya,ap as Gn,aq as va,ar as Na,as as wa,at as za,au as Sa,av as ka,aw as Bn,ax as Ca,ay as qn,az as Aa,aA as La,aB as Da,aC as $a,aD as _n,aE as Ia,aF as Pa,aG as Ra,aH as Ta,aI as Ea,aJ as Ma,aK as Oa,aL as Fa,aM as Ga,aN as Ba,aO as qa,aP as _a,aQ as Ua,aR as Qa,aS as Ka,aT as Va,aU as Ha,aV as Ns,aW as Wa,aX as Ya,aY as on,aZ as Ja,a_ as Xa,a$ as Za,b0 as er,b1 as tr,b2 as sr,b3 as nr,b4 as ir,b5 as ar,b6 as rr,b7 as dn,b8 as cr,b9 as lr,ba as or,bb as dr,bc as xn,bd as mn,be as xr,bf as mr,bg as ur,bh as hr,bi as pr,bj as gr,bk as fr,bl as jr,bm as br,bn as Un,bo as Qn,bp as yr,bq as Kn,br as vr,bs as Vn,bt as Nr,bu as wr,bv as ns,bw as zr,bx as Sr,by as kr,bz as un}from"./index-DYsYdWV8.js";import{R as Cr}from"./RunRow-YFN2PwH-.js";import{f as It,C as st,a as He,b as jt,c as xt,d as Be,e as Ge,g as ms,h as Ar,i as qs,p as Lr}from"./ChartPrimitives-EGp5HFxn.js";import{u as Dr,t as $r,R as us}from"./server-traffic-BzIFKqGS.js";import{R as Pt,C as Rt,X as Tt,Y as Et,T as Mt,L as Hn,A as kt,a as _s,b as Ir,d as Us}from"./vendor-recharts-ClRVR6aX.js";import{C as Wn,D as Qs,a as Pr,T as Rr}from"./trash-2-DKCkbZUb.js";import"./vendor-radix-B57xfQbP.js";import"./vendor-markdown-DK7fbRNb.js";const Tr=[["path",{d:"M5 12h14",key:"1ays0h"}]],Er=ps("minus",Tr);const Mr=[["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"}]],Or=ps("scan-search",Mr);const Fr=[["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"}]],Gr=ps("unplug",Fr);const Br=[["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"}]],qr=ps("upload",Br),_r=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function Yn(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Jn(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 Xn(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(Yn).map(Jn).filter(Boolean)):new Set}function Zn(t,s){const n=Yn(t).map(Jn).filter(Boolean).filter(i=>!_r.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Ur(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Qr(t,s){const n=Xn(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const l of s){if(l.category!=="content"){a.push(l);continue}const o=Zn(Ur(l),n);!o||i.has(o)||(i.add(o),a.push(l))}return a}function Kr(t){const s=Xn(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const l=Zn(a.query,s);return!l||i.has(l)?!1:(i.add(l),!0)})}function ws(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 Vr(t,s){return s<=0?null:Math.round((t-s)/s*100)}function zs(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${ws(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${ws(t.prior)} ${s})`:`Flat ${n} (${ws(t.prior)} ${s})`}function Os({state:t,label:s}){return e.jsx(ie,{tone:zi(t),children:s??wi(t)})}function hn({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"No data"});const i={cited:"bg-emerald-400","not-cited":"bg-zinc-600",lost:"bg-rose-400",emerging:"bg-amber-400 ring-1 ring-amber-300/60"},a=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"});return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:a}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,children:n.map((o,u)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[o.citationState]??"bg-zinc-700"} ${o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[o.citationState,new Date(o.createdAt).toLocaleDateString(),o.model?`model ${o.model}`:null,o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},u))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:l})]})}function Hr(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const l=s.get(a.createdAt);l?l.states.push(a.citationState):s.set(a.createdAt,{states:[a.citationState],runId:a.runId})}return[...s.entries()].sort(([i],[a])=>i.localeCompare(a)).map(([i,{states:a,runId:l}])=>({runId:l,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const Wr=320;function pn(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 gn(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 fn(t,s){const n=s==="mentions"?"mentioned":"cited",i=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const a=t[t.length-1].citationState,l=t[t.length-2].citationState;if(l!=="cited"&&a==="cited")return`Newly ${n}`;if(l==="cited"&&a!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===a;u--)o++;return a==="cited"?o<=1?`${i} in latest run`:`${i} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Yr(t,s){return s==="citations"?t:t.map(n=>({...n,citationState:pn(n,s),runHistory:n.runHistory.map(i=>({...i,citationState:pn(i,s)}))}))}function Jr({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=Tn(),[a,l]=r.useState(new Set),[o,u]=r.useState("mentions"),[m,p]=r.useState(n),f=r.useMemo(()=>{const b=Yr(t,o),k=new Map;for(const $ of b){const M=$.query,R=s?$.location??null:null,y=s?JSON.stringify([M,R]):M,j=k.get(y)??{key:y,phrase:M,location:R,items:[]};j.items.push($),k.set(y,j)}return[...k.values()]},[t,o,s]),d=b=>{l(k=>{const $=new Set(k);return $.has(b)?$.delete(b):$.add(b),$})},A=o==="mentions"?"mentioned":"cited",L=o==="mentions"?"Mention History":"Citation History",D=o==="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-zinc-500",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",children:o==="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-zinc-400 hover:text-zinc-200",onClick:()=>{l(b=>b.size===f.length?new Set:new Set(f.map(k=>k.key)))},children:a.size===f.length&&f.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-zinc-500",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":m==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("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:L}),e.jsx("th",{scope:"col",children:"Change"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.map(({key:b,phrase:k,location:$,items:M})=>{const R=a.has(b),y=M.map(E=>E.citationState),j=y.includes("cited")?"cited":y.includes("emerging")?"emerging":y.includes("lost")?"lost":y.every(E=>E==="pending")?"pending":"not-cited",x=Hr(M),T=M.filter(E=>E.citationState===Si.cited||E.citationState==="emerging").length,B=fn(x,o);return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>d(b),onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),d(b))},tabIndex:0,role:"button","aria-expanded":R,children:[e.jsx("td",{children:e.jsx(gs,{size:14,className:`transition-transform duration-150 text-zinc-500 ${R?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:k}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:$??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:M.map(E=>e.jsx($t,{provider:E.provider},E.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Os,{state:j,label:gn(j,o)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${T} of ${M.length} engines ${D}`,children:[T,"/",M.length]})]})}),e.jsx("td",{children:e.jsx(hn,{history:x})}),e.jsx("td",{className:"evidence-change-cell",children:B}),e.jsx("td",{})]}),R&&M.map(E=>e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"bg-zinc-900/30",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx($t,{provider:E.provider})}),e.jsx("td",{children:e.jsx(Os,{state:E.citationState,label:gn(E.citationState,o)})}),e.jsx("td",{children:e.jsx(hn,{history:E.runHistory})}),e.jsx("td",{className:"evidence-change-cell",children:fn(E.runHistory,o)}),e.jsx("td",{children:e.jsx(C,{variant:"ghost",size:"sm",type:"button",onClick:F=>{F.stopPropagation(),i(E.id)},children:"View"})})]}),m==="detailed"&&e.jsxs("tr",{className:"bg-zinc-900/20",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(ec,{item:E,onViewFull:()=>i(E.id)})})]})]},E.id))]},b)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",A==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Xr(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const l=Ci(a);return l.length>=4?[l]:[]}),...t.recommendedCompetitors??[]].filter(a=>a.trim().length>2),i=[];return s.length>0&&i.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&i.push({terms:n,className:"answer-highlight-competitor"}),i}function Zr(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 ec({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-zinc-500 italic",children:"No answer text captured for this run."});const{body:i,truncated:a}=Zr(t.answerSnippet,Wr),l=Xr(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-zinc-300",children:ki(i,l)}),(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-zinc-500",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-900/60 px-2 py-0.5 text-[11px] text-zinc-300",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-zinc-500",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-rose-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-rose-900/40 bg-rose-950/30 px-2 py-0.5 text-[11px] text-rose-300",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.competitorDomains.length-4," more"]})]})]}),a&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-emerald-400 hover:text-emerald-300",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function tc({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:i}){if(t.length===0)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No competitors configured. Add competitors to track overlap."});const a=s!=null,l=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"}),l&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=i!=null&&i.toLowerCase()===o.domain.toLowerCase(),m=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",u?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:m,onClick:a?()=>s(o.domain):void 0,title:a?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:o.domain}),e.jsx("td",{children:e.jsx(ie,{tone:Ai(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),l&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-zinc-500 transition-colors hover:text-rose-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-rose-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:p=>{p.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function jn({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:l,coverageValue:o,note:u,updatedAt:m,active:p,onClick:f}){return e.jsxs("button",{type:"button",onClick:f,className:`surface-card w-full text-left transition-colors ${p?"border-zinc-200 bg-zinc-900/50":"hover:border-zinc-700 hover:bg-zinc-900/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(ie,{tone:i,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:a}),e.jsx("p",{className:"mt-1 truncate text-sm text-zinc-200",children:l})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:o})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-zinc-500 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:u}),e.jsx("span",{children:m?`Updated ${Je(m)}`:"No recent sync yet"})]})]})}function is({label:t,value:s,tone:n}){const i=n==="positive"?"text-emerald-400":n==="negative"?"text-rose-400":"text-zinc-200";return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${i}`,children:s})]})}const sc=6,Ot="__other__",Lt="_socialTotal";function nc(t,s=sc){const n=new Map;for(const f of t)n.set(f.source,(n.get(f.source)??0)+f.sessions);const i=[...n.entries()].sort((f,d)=>d[1]!==f[1]?d[1]-f[1]:f[0].localeCompare(d[0])),a=i.slice(0,s),l=new Set(a.map(([f])=>f)),o=Math.max(0,i.length-s),u=new Map;for(const f of t){let d=u.get(f.date);d||(d={date:f.date,[Lt]:0},u.set(f.date,d));const A=l.has(f.source)?f.source:Ot;d[A]=(d[A]??0)+f.sessions,d[Lt]=(d[Lt]??0)+f.sessions}const m=[...u.values()].sort((f,d)=>String(f.date).localeCompare(String(d.date))),p=a.map(([f])=>f);return o>0&&p.push(Ot),{data:m,sources:p,otherCount:o}}function Dt(t){return t.replace(/\+/g," ")}function ei(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const ic=["7d","30d","90d","all"],ot=Ge,Fs=Be.textDim,ti=Be.textFaint,Qt=25;function as(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function si(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function ac({projectName:t}){const{data:s,isLoading:n,isError:i}=Dr(t);if(n)return e.jsx(U,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(U,{className:"p-5",children:e.jsx("div",{className:"text-sm text-rose-400",children:"Failed to load server activity."})});const a=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-zinc-50",children:"Crawler hits, AI fetches & AI referral sessions"}),e.jsxs("p",{className:"text-xs text-zinc-500 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."," ",e.jsx(dt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(U,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(dt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})}):e.jsx(U,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-zinc-900/50 text-[10px] uppercase tracking-wide text-zinc-500",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:a.map(l=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(ie,{tone:$r(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:l.lastSyncedAt?si(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(dt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function rc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(ac,{projectName:t}),e.jsx(cc,{projectName:t})]})}function cc({projectName:t}){const s=mt(),[n,i]=r.useState(null),[a,l]=r.useState(null),[o,u]=r.useState(!0),[m,p]=r.useState(!1),[f,d]=r.useState(!1),[A,L]=r.useState(null),[D,b]=r.useState(null),[k,$]=r.useState("sessions"),[M,R]=r.useState("desc"),[y,j]=r.useState("sessions"),[x,T]=r.useState("desc"),[B,E]=r.useState("sessions"),[F,S]=r.useState("desc"),[I,G]=r.useState("sessions"),[w,J]=r.useState("desc"),[ae,fe]=r.useState([]),[Q,Y]=r.useState([]),[xe,pe]=r.useState([]),[g,O]=r.useState(!1),[H,oe]=r.useState("30d");async function ge(N){u(!0),L(null);try{const V=await s.fetchQuery({...Li({client:_,path:{name:t}}),staleTime:Ut});if(N.current)return;if(i(V),!V.connected){l(null),fe([]),Y([]),pe([]),u(!1);return}const q=H==="all"?void 0:H,[W,Te,at,he]=await Promise.all([s.fetchQuery({...Di({client:_,path:{name:t},query:q?{window:q}:void 0}),staleTime:Ut}).then(me=>me),s.fetchQuery({...$i({client:_,path:{name:t},query:q?{window:q}:void 0}),staleTime:Ut}).catch(()=>[]),s.fetchQuery({...Ii({client:_,path:{name:t},query:q?{window:q}:void 0}),staleTime:Ut}).catch(()=>[]),s.fetchQuery({...Pi({client:_,path:{name:t},query:q?{window:q}:void 0}),staleTime:Ut}).catch(()=>[])]);if(N.current)return;l(W),fe(Te),Y(at),pe(he),u(!1)}catch(V){if(N.current)return;L(V instanceof Error?V.message:"Failed to load GA4 data"),u(!1)}}r.useEffect(()=>{const N={current:!1};return ge(N),()=>{N.current=!0}},[t,H,s]);async function Ie(){p(!0),L(null),b(null);try{const N=await En(t);b(`Synced ${N.rowCount.toLocaleString()} page rows, ${N.aiReferralCount.toLocaleString()} AI and ${N.socialReferralCount.toLocaleString()} social referral rows (${N.days} days)`),await s.invalidateQueries({predicate:V=>{const q=V.queryKey[0];return typeof q?._id=="string"&&q._id.startsWith("getApiV1ProjectsByNameGa")}}),await ge({current:!1})}catch(N){L(N instanceof Error?N.message:"Sync failed")}finally{p(!1)}}async function Ae(){d(!0),L(null),b(null);try{await Ri(t),await s.invalidateQueries({predicate:N=>{const V=N.queryKey[0];return typeof V?._id=="string"&&V._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),b("GA4 disconnected")}catch(N){L(N instanceof Error?N.message:"Disconnect failed")}finally{d(!1)}}function ne(N){k===N?R(V=>V==="desc"?"asc":"desc"):($(N),R("desc"))}function ee(N){y===N?T(V=>V==="desc"?"asc":"desc"):(j(N),T("desc"))}function be(N){B===N?S(V=>V==="desc"?"asc":"desc"):(E(N),S("desc"))}function Se(N){I===N?J(V=>V==="desc"?"asc":"desc"):(G(N),J("desc"))}const ke=r.useMemo(()=>a?.topPages?[...a.topPages].sort((N,V)=>{const q=N[k],W=V[k];return typeof q=="string"&&typeof W=="string"?M==="asc"?q.localeCompare(W):W.localeCompare(q):M==="asc"?q-W:W-q}):[],[a?.topPages,k,M]),$e=r.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((N,V)=>{const q=N[y],W=V[y];return typeof q=="string"&&typeof W=="string"?x==="asc"?q.localeCompare(W):W.localeCompare(q):x==="asc"?q-W:W-q}):[],[a?.aiReferrals,y,x]),ce=r.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((N,V)=>{const q=N[I],W=V[I];return typeof q=="string"&&typeof W=="string"?w==="asc"?q.localeCompare(W):W.localeCompare(q):w==="asc"?q-W:W-q}):[],[a?.aiReferralLandingPages,I,w]),ye=r.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((N,V)=>{const q=N[B],W=V[B];return typeof q=="string"&&typeof W=="string"?F==="asc"?q.localeCompare(W):W.localeCompare(q):F==="asc"?q-W:W-q}):[],[a?.socialReferrals,B,F]),{socialChartData:We,socialChartSources:z,socialOtherCount:P}=r.useMemo(()=>{const N=nc(xe);return{socialChartData:N.data,socialChartSources:N.sources,socialOtherCount:N.otherCount}},[xe]),{chartData:qe,chartSources:Me,dateRange:Pe}=r.useMemo(()=>{const N=[...new Set(ae.map(he=>he.source))],V=new Map;for(const he of Q)V.set(he.date,{_totalSessions:he.sessions,_organicSessions:he.organicSessions});const q=new Map;for(const he of ae){const me=`${he.date}::${he.source}`,vt=q.get(me)??0;q.set(me,Math.max(vt,he.sessions))}for(const[he,me]of q){const[vt,Wt]=he.split("::");let pt=V.get(vt);pt||(pt={_totalSessions:0,_organicSessions:0},V.set(vt,pt)),pt[Wt]=(pt[Wt]??0)+me}const W=[...V.entries()].sort(([he],[me])=>he.localeCompare(me)).map(([he,me])=>({date:he,...me})),Te=W.map(he=>he.date),at=Te.length>0?{start:Te[0],end:Te[Te.length-1]}:null;return{chartData:W,chartSources:N,dateRange:at}},[ae,Q]);if(o&&!n)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(lc,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:N=>{const V=N.queryKey[0];return typeof V?._id=="string"&&V._id.startsWith("getApiV1ProjectsByNameGa")}}),await ge({current:!1})))()}});const ut=a?.organicSharePctDisplay??"0%",bt=a?.channelBreakdown?.organic.sharePctDisplay??ut,nt=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,ht=a?.aiSessionsDeduped??0,_e=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Ze=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",it=a?new Set(a.aiReferrals.map(N=>N.source.toLowerCase())).size:0,Xe=$e[0]??null,yt=a?.totalDirectSessions??0,Ft=a?.directSharePctDisplay??"0%",we=a?.channelBreakdown?.direct.sessions??yt,Oe=a?.channelBreakdown?.direct.sharePctDisplay??Ft,Fe=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,Gt=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",Ue=a?.socialSessions??0,h=a?.socialSharePctDisplay??"0%",K=a?.channelBreakdown?.social.sessions??Ue,le=a?.channelBreakdown?.social.sharePctDisplay??h,Re=a?new Set(a.socialReferrals.map(N=>N.source.toLowerCase())).size:0,te=ye[0]??null;return e.jsxs(e.Fragment,{children:[A&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:A}),D&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-emerald-900/20 border border-emerald-800/60 text-sm text-emerald-300",children:D}),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-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Property ",e.jsx("span",{className:"text-zinc-300",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-zinc-500",children:n.clientEmail})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",disabled:m,onClick:Z(Ie),children:[e.jsx(us,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(C,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:f,onClick:Z(Ae),children:[e.jsx(Gr,{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-zinc-500 mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Site Traffic",e.jsx(Ne,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${a?.periodStart&&a?.periodEnd?` Data available: ${new Date(a.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(a.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:ic.map(N=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${H===N?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>oe(N),children:N==="all"?"All":N},N))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ss,{value:as(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ss,{value:as(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${ut} of total`,tone:"positive"}),e.jsx(Ss,{value:as(a.totalUsers),label:"Total Users",subtitle:a.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-zinc-800/60",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-3",children:"No traffic data yet."}),e.jsxs(C,{variant:"outline",size:"sm",disabled:m,onClick:Z(Ie),children:[e.jsx(us,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),"Sync from GA4"]})]})]}),a&&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-zinc-500 mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ne,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed. Other channels are the remaining GA4 session default channel groups, such as Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, and Paid Other."})]})]}),Pe&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(Pe.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Pe.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),qe.length>0&&e.jsxs(U,{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-zinc-100",children:Me.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Me.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Me.length===0&&e.jsx("p",{className:"text-xs text-zinc-500",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Rt,{data:qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Tt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:st},tickFormatter:It}),e.jsx(Et,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Mt,{...xt,labelFormatter:jt,formatter:(N,V)=>{const q=typeof N=="number"?N.toLocaleString():String(N??0),W=String(V??"");return W==="_totalSessions"?[q,"Total Sessions"]:W==="_organicSessions"?[q,"Organic Sessions"]:[q,W]}}),e.jsx(Hn,{wrapperStyle:{fontSize:11,color:Be.text},formatter:N=>N==="_totalSessions"?"Total Sessions":N==="_organicSessions"?"Organic Sessions":N}),e.jsx(kt,{type:"monotone",dataKey:"_totalSessions",stroke:Be.textFaint,fill:Be.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Me.map((N,V)=>e.jsx(kt,{type:"monotone",dataKey:N,stackId:"ai",stroke:ot[V%ot.length],fill:ot[V%ot.length],fillOpacity:.4,strokeWidth:1.5},N))]})})})]}),e.jsxs(U,{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-zinc-100",children:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Ye,{label:"Organic",value:bt,hint:`${nt.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(Ye,{label:"Social",value:le,hint:`${K.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(Ye,{label:"Direct",value:Oe,hint:`${we.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(Ye,{label:"Known AI referrers (lower bound)",value:Ze,hint:`${_e.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). These sessions are removed from their native GA4 channel in this card grid so the five buckets stay disjoint. This is a strict lower bound: most AI traffic strips the referrer and falls into Direct, so the true AI share is typically higher than what's shown here. The detail table below also surfaces firstUserSource and UTM-tagged AI signals."}),e.jsx(Ye,{label:"Other channels",value:Gt,hint:`${Fe.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."})]}),Xe&&e.jsxs("div",{className:"mt-4 rounded-lg border border-emerald-800/40 bg-emerald-500/6 px-4 py-3 text-sm text-emerald-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:Xe.source})," via ",Xe.medium,", accounting for ",Xe.sessions.toLocaleString()," sessions."]})]}),e.jsxs(U,{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-zinc-100",children:"Known AI referrers — sources detected"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.aiReferrals.length>0?`${it} unique sources, ${a.aiReferrals.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(Le,{label:"Source",sortKey:"source",current:y,dir:x,onSort:ee,align:"left"}),e.jsx(Le,{label:"Medium",sortKey:"medium",current:y,dir:x,onSort:ee,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Le,{label:"Sessions",sortKey:"sessions",current:y,dir:x,onSort:ee,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Le,{label:"Users",sortKey:"users",current:y,dir:x,onSort:ee,align:"right"})]})}),e.jsx("tbody",{children:$e.map(N=>e.jsx(dc,{referral:N,totalSessions:ht},`${N.source}:${N.medium}:${N.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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(U,{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-zinc-100",children:"Known AI referrers — landing pages"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:ce.length>0?`${ce.length} rows`:"No landing-page rows"})]}),ce.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-zinc-500",children:[e.jsx(Le,{label:"Landing Page",sortKey:"landingPage",current:I,dir:w,onSort:Se,align:"left"}),e.jsx(Le,{label:"Source",sortKey:"source",current:I,dir:w,onSort:Se,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Le,{label:"Sessions",sortKey:"sessions",current:I,dir:w,onSort:Se,align:"right"}),e.jsx(Le,{label:"Users",sortKey:"users",current:I,dir:w,onSort:Se,align:"right"})]})}),e.jsx("tbody",{children:ce.map(N=>e.jsx(xc,{row:N},`${N.landingPage}:${N.source}:${N.medium}:${N.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),a&&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-zinc-500 mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ne,{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."})]})]}),We.length>0&&e.jsxs(U,{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-zinc-100",children:"Social sessions over time"})]}),P>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",z.length-1," sources · ",P," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Rt,{data:We,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Tt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:st},tickFormatter:It}),e.jsx(Et,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Mt,{...xt,labelFormatter:jt,formatter:(N,V)=>{const q=typeof N=="number"?N.toLocaleString():String(N??0),W=String(V??"");if(W===Lt)return[q,"Total Social"];if(W===Ot){const Te=`Other (${P} source${P===1?"":"s"})`;return[q,Te]}return[q,Dt(W)]}}),e.jsx(kt,{type:"monotone",dataKey:Lt,stroke:ti,fill:Be.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),z.map((N,V)=>{const W=N===Ot?Fs:ot[V%ot.length];return e.jsx(kt,{type:"monotone",dataKey:N,stackId:"social",stroke:W,fill:W,fillOpacity:.4,strokeWidth:1.5},N)})]})})}),e.jsx(uc,{sources:z,otherCount:P})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(U,{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-zinc-100",children:"Social media visits"})]}),a.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Ye,{label:"Social Sessions",value:as(Ue),hint:`${Ue.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Ye,{label:"Share of Traffic",value:h,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Ye,{label:"Platforms",value:String(Re),hint:`${a.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),te&&e.jsxs("div",{className:"mt-4 rounded-lg border border-sky-800/40 bg-sky-500/6 px-4 py-3 text-sm text-sky-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-sky-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${te.source} via ${te.medium}`,children:ei(Dt(te.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:te.medium,children:["via ",Dt(te.medium)," · ",te.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(Ye,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Ye,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Ye,{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-zinc-800/60 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-400",children:[e.jsx("p",{className:"mb-1.5 text-zinc-300",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-zinc-500",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(U,{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-zinc-100",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.socialReferrals.length>0?ye.length>Qt&&!g?`Top ${Qt} of ${ye.length}`:`${ye.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(Le,{label:"Source",sortKey:"source",current:B,dir:F,onSort:be,align:"left"}),e.jsx(Le,{label:"Medium",sortKey:"medium",current:B,dir:F,onSort:be,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Le,{label:"Sessions",sortKey:"sessions",current:B,dir:F,onSort:be,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Le,{label:"Users",sortKey:"users",current:B,dir:F,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:(g?ye:ye.slice(0,Qt)).map(N=>e.jsx(mc,{referral:N,totalSessions:Ue},`${N.source}:${N.medium}:${N.channelGroup}`))})]})}),ye.length>Qt&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>O(N=>!N),className:"text-xs text-zinc-400 hover:text-zinc-200 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 transition-colors",children:g?`Show top ${Qt}`:`Show all ${ye.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-zinc-400 mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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."})]})]})]})]})]}),a&&a.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-zinc-500 mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ne,{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-zinc-500",children:[e.jsx(Le,{label:"Landing Page",sortKey:"landingPage",current:k,dir:M,onSort:ne,align:"left"}),e.jsx(Le,{label:"Sessions",sortKey:"sessions",current:k,dir:M,onSort:ne,align:"right"}),e.jsx(Le,{label:"Organic",sortKey:"organicSessions",current:k,dir:M,onSort:ne,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Le,{label:"Users",sortKey:"users",current:k,dir:M,onSort:ne,align:"right"})]})}),e.jsx("tbody",{children:ke.map(N=>e.jsx(oc,{page:N},N.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-zinc-500",children:[e.jsx("span",{children:a?.lastSyncedAt?`Last synced ${si(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function lc({projectName:t,onConnected:s}){const[n,i]=r.useState(""),[a,l]=r.useState(null),[o,u]=r.useState(null),[m,p]=r.useState(!1),[f,d]=r.useState(null),A=r.useRef(null),L=r.useCallback(b=>{const k=b.target.files?.[0];if(!k)return;d(null),l(k.name);const $=new FileReader;$.onload=()=>{const M=$.result;try{const R=JSON.parse(M);if(!R.client_email||!R.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)."),u(null);return}u(M)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},$.onerror=()=>{d("Failed to read file."),u(null)},$.readAsText(k)},[]);async function D(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!o){d("Please upload a service account key file.");return}p(!0);try{await Ti(t,{propertyId:n.trim(),keyJson:o});try{await En(t)}catch{}s()}catch(b){d(b instanceof Error?b.message:"Failed to connect GA4")}finally{p(!1)}}return e.jsxs(U,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-50 mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-zinc-400 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."}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:f}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-zinc-400 mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:b=>i(b.target.value),className:"w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 px-3 py-2 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:ring-1 focus:ring-zinc-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",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-zinc-400 mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:A,type:"file",accept:".json,application/json",onChange:L,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>A.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 border-dashed px-4 py-3 text-sm text-zinc-400 hover:border-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:[e.jsx(qr,{className:"w-4 h-4 shrink-0"}),a?e.jsx("span",{className:"text-zinc-200 truncate",children:a}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-zinc-400",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(C,{variant:"default",size:"sm",disabled:m||!n.trim()||!o,onClick:Z(D),children:m?"Connecting & syncing…":"Connect GA4"})]})}function Le({label:t,sortKey:s,current:n,dir:i,onSort:a,align:l}){const o=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-zinc-300 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded",onClick:()=>a(s),"aria-label":`Sort by ${t}${o?` (currently ${i==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})})}const ni={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Ss({value:t,label:s,subtitle:n,tone:i}){return e.jsxs("div",{className:"rounded-lg bg-zinc-900/30 border border-zinc-800/60 px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${ni[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Ye({value:t,label:s,hint:n,tone:i,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1 flex items-center gap-1",children:[s,a&&e.jsx(Ne,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${ni[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function oc({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[s,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}const ii={session:"Session",first_user:"First Visit",manual_utm:"UTM"},ai={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 dc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=ii[t.sourceDimension]??t.sourceDimension,a=ai[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-200 max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-zinc-500 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 border-zinc-700 text-zinc-400",title:a,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function xc({row:t}){const s=ii[t.sourceDimension]??t.sourceDimension,n=ai[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[360px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-zinc-200 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-zinc-700 text-zinc-400",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function mc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Dt(t.source),l=Dt(t.medium);return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 pr-3 text-zinc-200 truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500 truncate",title:t.medium,children:l}),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-zinc-700 text-zinc-400",title:`GA4 channel group: ${t.channelGroup}`,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-sky-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function uc({sources:t,otherCount:s}){const n=[{key:Lt,color:ti,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===Ot)n.push({key:Ot,color:Fs,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Dt(a);n.push({key:a,color:ot[i%ot.length]??Fs,label:ei(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-zinc-400",children:n.map(i=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:i.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:i.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:i.label})]},i.key))})}const hc=["7d","30d","90d","all"],rs=500,ct=25;function pc({projectName:t,refreshNonce:s}){const n=mt(),[i,a]=r.useState(!1),[l,o]=r.useState([]),[u,m]=r.useState([]),[p,f]=r.useState([]),[d,A]=r.useState(null),[L,D]=r.useState([]),[b,k]=r.useState([]),[$,M]=r.useState(null),[R,y]=r.useState(""),[j,x]=r.useState(""),[T,B]=r.useState("30"),[E,F]=r.useState(!1),[S,I]=r.useState("30d"),[G,w]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[J,ae]=r.useState(0),[fe,Q]=r.useState(!1),[Y,xe]=r.useState(0),[pe,g]=r.useState(!1),[O,H]=r.useState(""),[oe,ge]=r.useState(!0),[Ie,Ae]=r.useState(!1),[ne,ee]=r.useState(!1),[be,Se]=r.useState(!1),[ke,$e]=r.useState(!1),[ce,ye]=r.useState(!1),[We,z]=r.useState(!1),[P,qe]=r.useState(null),[Me,Pe]=r.useState(!1),[ut,bt]=r.useState(!1),[nt,ht]=r.useState(null),[_e,Ze]=r.useState(""),[it,Xe]=r.useState(!1),[yt,Ft]=r.useState(!1),[we,Oe]=r.useState("indexed"),[Fe,Gt]=r.useState(null),Ue=!!(G.query.trim()||G.page.trim()||Fe),h=Fe!==null,K=r.useMemo(()=>{if(!Fe)return p;const{key:c,dir:v}=Fe;return[...p].sort((X,re)=>{const ze=c===ft.CTR?Number.isFinite(X.ctr)?X.ctr:0:X[c],Ee=c===ft.CTR?Number.isFinite(re.ctr)?re.ctr:0:re[c];return v==="asc"?ze-Ee:Ee-ze})},[p,Fe]),[le,Re]=r.useState([]),[te,N]=r.useState(null),[V,q]=r.useState(1);r.useEffect(()=>{q(1)},[P,we,te]);const W=r.useMemo(()=>te?(P?.reasonGroups??[]).find(c=>c.reason===te):void 0,[P,te]),Te=r.useMemo(()=>P?we==="indexed"?P.indexed:we==="deindexed"?P.deindexed:we==="notIndexed"?te?W?.urls??[]:(P.reasonGroups??[]).length===0?P.notIndexed:[]:[]:[],[P,we,te,W]),at=Math.max(1,Math.ceil(Te.length/ct)),he=Math.min(Math.max(1,V),at),me=(he-1)*ct,vt=Te.length>ct,Wt=Te.length===0?0:me+1,pt=Math.min(me+ct,Te.length),ri=r.useMemo(()=>P?.indexed.slice(me,me+ct)??[],[P,me]),ci=r.useMemo(()=>P?.notIndexed.slice(me,me+ct)??[],[P,me]),li=r.useMemo(()=>P?.deindexed.slice(me,me+ct)??[],[P,me]),oi=r.useMemo(()=>(W?.urls??[]).slice(me,me+ct),[W,me]),[Bt,Yt]=r.useState(!1),[Ws,de]=r.useState(null),[Ys,et]=r.useState(null),je=l.find(c=>c.connectionType==="gsc"),di=p.length>0||L.length>0||b.length>0,bs=Ei(),qt=Mi(),ys=Oi();async function Js(c){if(!c){m([]),y("");return}ee(!0);try{const{sites:v}=await n.fetchQuery({...Yi({client:_,path:{name:t}}),staleTime:Ce});m(v),y(c.propertyId??v[0]?.siteUrl??"")}catch(v){m([]),de(v instanceof Error?v.message:"Failed to load Search Console properties")}finally{ee(!1)}}async function Nt(c){$e(!0);const v=c??J;try{const X=parseInt(G.limit,10)||20,re=Ue?rs:X+1,ze=Ue?0:v,Ee={limit:String(re)};G.startDate&&(Ee.startDate=G.startDate),G.endDate&&(Ee.endDate=G.endDate),G.query&&(Ee.query=G.query),G.page&&(Ee.page=G.page),ze>0&&(Ee.offset=String(ze)),S&&S!=="all"&&!G.startDate&&(Ee.window=S);const Qe=await n.fetchQuery({...Bi({client:_,path:{name:t},query:Ee}),staleTime:Ce});Ue?(Q(!1),f(Qe),xe(Qe.length),g(!0)):(Q(Qe.length>X),f(Qe.slice(0,X)),xe(0),g(!1))}catch(X){f([]),Q(!1),xe(0),de(X instanceof Error?X.message:"Failed to load GSC performance data")}finally{$e(!1)}}async function vs(){try{const c={};G.startDate&&(c.startDate=G.startDate),G.endDate&&(c.endDate=G.endDate),S&&S!=="all"&&!G.startDate&&(c.window=S);const v=await n.fetchQuery({...qi({client:_,path:{name:t},query:c}),staleTime:Ce});A(v)}catch{A(null)}}async function Jt(){ye(!0);try{const c=O.trim()||void 0,v={limit:"20"};c&&(v.url=c);const[X,re]=await Promise.all([n.fetchQuery({...Hi({client:_,path:{name:t},query:v}),staleTime:Ce}),n.fetchQuery({...Wi({client:_,path:{name:t}}),staleTime:Ce})]);D(X),k(re)}catch(c){D([]),k([]),de(c instanceof Error?c.message:"Failed to load GSC inspection history")}finally{ye(!1)}}async function Xs(){Pe(!0);try{const[c,v]=await Promise.all([n.fetchQuery({...Mn({client:_,path:{name:t}}),staleTime:Ce}),n.fetchQuery({...Ki({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>[])]);qe(c),Re(v)}catch(c){qe(null),Re([]),de(c instanceof Error?c.message:"Failed to load coverage data")}finally{Pe(!1)}}async function Zs(c){Yt(!0),de(null);try{const v=await cn(t,{urls:c}),{succeeded:X,failed:re,total:ze}=v.summary;se({title:"Indexing requested",detail:re===0?`${X} URL${X!==1?"s":""} submitted for indexing.`:`${X}/${ze} submitted successfully, ${re} failed.`,tone:re===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(v){de(v instanceof Error?v.message:"Failed to request indexing")}finally{Yt(!1)}}async function xi(){Yt(!0),de(null);try{const c=await cn(t,{urls:[],allUnindexed:!0}),{succeeded:v,failed:X,total:re}=c.summary;se({title:"Indexing requested",detail:X===0?`${v} unindexed URL${v!==1?"s":""} submitted for indexing.`:`${v}/${re} submitted successfully, ${X} failed.`,tone:X===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){de(c instanceof Error?c.message:"Failed to request indexing")}finally{Yt(!1)}}async function Xt(){if(_e.trim()){Xe(!0),de(null);try{await Qi(t,"gsc",_e.trim()),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(v=>v.connectionType==="gsc"?{...v,sitemapUrl:_e.trim()}:v)),se({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),Ze("")}catch(c){de(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{Xe(!1)}}}async function en(){de(null);try{const c=await qt.mutateAsync({projectName:t,projectLabel:t});ht(c.sitemaps),o(v=>v.map(X=>X.connectionType==="gsc"?{...X,sitemapUrl:c.primarySitemapUrl}:X))}catch{}}async function mi(){bt(!0),de(null);try{const c=await Xi(t);n.setQueryData(Zi({client:_,path:{name:t}}),c),ht(c.sitemaps),c.sitemaps.length===0&&et("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(c){de(c instanceof Error?c.message:"Failed to list sitemaps")}finally{bt(!1)}}async function tn(){ge(!0),de(null);try{const[c,v]=await Promise.all([Gi().catch(()=>null),n.fetchQuery({...Bs({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>[])]);a(!!c?.google?.configured),o(v);const X=v.find(re=>re.connectionType==="gsc");await Promise.all([Js(X),Nt(),vs(),Jt(),Xs()])}finally{ge(!1)}}r.useEffect(()=>{tn()},[t,s]),r.useEffect(()=>{ae(0),Nt(0),vs()},[S]);const sn=r.useRef(!1);r.useEffect(()=>{if(!sn.current){sn.current=!0;return}ae(0),Nt(0)},[h]);async function ui(){if(!i){de("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Ae(!0),de(null),et(null);try{const{authUrl:c}=await Ui(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){de("Unexpected OAuth redirect URL. Please try again.");return}const v=window.open(c,"_blank","width=600,height=700");if(!v){window.location.assign(c);return}et("Finish the Google consent flow in the popup, then close it to refresh this project.");const X=window.setInterval(()=>{v.closed&&(window.clearInterval(X),et(null),n.invalidateQueries({predicate:re=>{const ze=re.queryKey[0];return typeof ze?._id=="string"&&ze._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),tn())},1e3)}catch(c){de(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{Ae(!1)}}async function hi(){de(null),et(null);try{await _i(t,"gsc"),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(v=>v.connectionType!=="gsc")),m([]),y("")}catch(c){de(c instanceof Error?c.message:"Failed to disconnect")}}async function pi(){if(R){Se(!0),de(null);try{await Ji(t,"gsc",R),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(v=>v.connectionType==="gsc"?{...v,propertyId:R}:v)),se({title:"GSC property updated",detail:`${t} is now linked to ${R}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){de(c instanceof Error?c.message:"Failed to save GSC property")}finally{Se(!1)}}}async function gi(){de(null),et(null);try{await bs.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(T,10)||void 0,full:E||void 0}}),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function nn(){if(j.trim()){z(!0),de(null),et(null);try{const c=await Vi(t,j.trim());await n.invalidateQueries({predicate:v=>{const X=v.queryKey[0];return typeof X?._id=="string"&&X._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),M(c),x(""),await Jt()}catch(c){de(c instanceof Error?c.message:"Failed to inspect URL")}finally{z(!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"})]})}),Ws&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[Ws,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>de(null),children:"×"})]}),Ys&&e.jsxs("div",{className:"mb-3 rounded-lg border border-emerald-800/40 bg-emerald-950/20 px-3 py-2 text-sm text-emerald-300",children:[Ys,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>et(null),children:"×"})]}),oe?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[je?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-zinc-500",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-emerald-500"}),e.jsx("span",{className:"text-zinc-300",children:"Authorized"})]}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsx("code",{className:"text-zinc-400",children:je.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Je(je.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:Z(hi),children:"Disconnect"})]}):e.jsxs(U,{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(ie,{tone:i?"caution":"negative",children:i?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-5",children:[e.jsx("p",{className:"text-sm text-zinc-300",children:i?"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."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[i?e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:Ie,onClick:Z(ui),children:Ie?"Opening…":"Connect Google Search Console"}):e.jsx(C,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(dt,{to:"/settings",children:"Open Settings"})}),!i&&e.jsx("p",{className:"text-xs text-zinc-500",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),je&&!je.sitemapUrl&&e.jsx("div",{className:"rounded-lg border border-amber-800/40 bg-amber-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-amber-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-amber-300",children:"Set your sitemap URL"}),e.jsx("p",{className:"mt-1 text-xs text-amber-400/70",children:"Canonry uses your sitemap to discover URLs for index coverage inspection. Auto-discover from GSC or enter it manually."}),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(C,{type:"button",size:"sm",disabled:qt.isPending||!je.propertyId,onClick:Z(en),children:qt.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-amber-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-amber-800/40 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-500 focus:border-amber-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:_e,onChange:c=>Ze(c.target.value),onKeyDown:c=>c.key==="Enter"&&void Xt()}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:it||!_e.trim(),onClick:Z(Xt),children:it?"Saving…":"Save sitemap URL"})]})]})]})]})}),(je||di)&&e.jsxs(e.Fragment,{children:[e.jsxs(U,{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:[P&&P.notIndexed.length>0&&e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:Bt,onClick:()=>{xi()},children:Bt?"Requesting…":`Request indexing (${P.notIndexed.length})`}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:Me,onClick:()=>{Xs()},children:Me?"Loading…":"Refresh coverage"})]})]}),P&&P.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=P.summary.indexed+P.summary.notIndexed,v=c>0?P.summary.indexed/c:0,X=c>0?P.summary.notIndexed/c:0,re=54,ze=2*Math.PI*re,Ee=ze*(1-v),Qe=ze*X,wt=ze*v;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:re,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:re,fill:"none",stroke:ms.positiveDeep,strokeWidth:"14",strokeDasharray:ze,strokeDashoffset:Ee,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),P.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:re,fill:"none",stroke:Be.textFaint,strokeWidth:"14",strokeDasharray:`${Qe} ${ze-Qe}`,strokeDashoffset:-wt,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-zinc-50",children:[(v*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-zinc-500 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-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:P.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-zinc-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-zinc-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:P.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",(P.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",(P.reasonGroups??[]).length," ",(P.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),P.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-zinc-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-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:P.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex gap-1",children:["indexed","notIndexed","deindexed"].map(c=>{const v=c==="indexed"?P.indexed.length:c==="notIndexed"?P.notIndexed.length:P.deindexed.length,X=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${we===c?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Oe(c),N(null)},children:[X," (",v,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[we==="indexed"&&P.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:ri.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),we==="notIndexed"&&!te&&(P.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:(P.reasonGroups??[]).map(c=>e.jsxs("tr",{className:"cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>N(c.reason),onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),N(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.count})]},c.reason))})]}),we==="notIndexed"&&!te&&(P.reasonGroups??[]).length===0&&P.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:ci.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"})]},c.id))})]}),we==="notIndexed"&&te&&(()=>{const c=(P.reasonGroups??[]).find(v=>v.reason===te);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-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>N(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:c.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[c.count," affected page",c.count!==1?"s":""]})]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:Bt,onClick:()=>{Zs(c.urls.map(v=>v.url))},children:Bt?"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"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:oi.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:v.url}),e.jsx("td",{className:"text-zinc-400",children:v.crawlTime?v.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-200 transition-colors",disabled:Bt,onClick:()=>{Zs([v.url])},title:"Request indexing",children:"Index"})})]},v.id))})]})]}):null})(),we==="deindexed"&&P.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:li.map((c,v)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState}),e.jsx("td",{className:"text-zinc-400",children:c.currentState}),e.jsx("td",{className:"text-zinc-400",children:c.transitionDate.split("T")[0]})]},`${c.url}-${v}`))})]}),(we==="indexed"&&P.indexed.length===0||we==="notIndexed"&&!te&&P.notIndexed.length===0||we==="deindexed"&&P.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-zinc-500",children:"No URLs in this category."}),vt&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-zinc-400",children:[e.jsxs("p",{className:"tabular-nums",children:["Showing ",e.jsx("span",{className:"text-zinc-300",children:Wt.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:pt.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:Te.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>q(c=>Math.max(1,c-1)),disabled:he<=1,"aria-label":"Previous page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:[e.jsx(Ar,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:he})," of"," ",e.jsx("span",{className:"text-zinc-200",children:at})]}),e.jsxs("button",{type:"button",onClick:()=>q(c=>Math.min(at,c+1)),disabled:he>=at,"aria-label":"Next page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:["Next",e.jsx(gs,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Me?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(U,{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:hc.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":S===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${S===c?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>I(c),children:c==="all"?"All":c},c))}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:ke,onClick:()=>{ae(0),Nt(0),vs()},children:ke?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,v=Math.max(...c.map(ue=>ue.impressions),1),{clicks:X,impressions:re,ctr:ze}=d.totals,Ee=(ze*100).toFixed(1),Qe=700,wt=220,Ke={top:12,bottom:36,left:48,right:12},fi=Qe-Ke.left-Ke.right,zt=wt-Ke.top-Ke.bottom,_t=fi/c.length,Zt=Math.max(Math.min(_t*.35,24),4),an=Math.max(Zt*.15,1),ji=ue=>{if(ue<=0)return 1;const tt=Math.pow(10,Math.floor(Math.log10(ue))),Ve=ue/tt,rt=Ve<=1.5?1.5:Ve<=3?3:Ve<=5?5:10;return Math.ceil(rt*tt)},es=4,ts=Math.ceil(ji(v)/es)*es,bi=Array.from({length:es+1},(ue,tt)=>ts/es*tt),yi=ue=>ue>=1e3?`${(ue/1e3).toFixed(ue>=1e4?0:1)}k`:String(ue);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-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Clicks ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:X.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-blue-400"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Impressions ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:re.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[Ee,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Qe} / ${wt}`},children:e.jsxs("svg",{viewBox:`0 0 ${Qe} ${wt}`,className:"h-full w-full",children:[bi.map((ue,tt)=>{const Ve=Ke.top+zt-ue/ts*zt;return e.jsxs("g",{children:[e.jsx("line",{x1:Ke.left,y1:Ve,x2:Qe-Ke.right,y2:Ve,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Ke.left-6,y:Ve+3.5,textAnchor:"end",fill:Be.text,fontSize:"10",fontFamily:"inherit",children:yi(ue)})]},`t-${tt}`)}),c.map((ue,tt)=>{const Ve=Ke.left+_t*tt+_t/2,rt=ue.impressions/ts*zt,ss=ue.clicks/ts*zt;return e.jsxs("g",{children:[e.jsx("title",{children:`${ue.date}
2
- Clicks: ${ue.clicks}
3
- Impressions: ${ue.impressions}
4
- CTR: ${(ue.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Ve-Zt-an/2,y:Ke.top+zt-rt,width:Zt,height:Math.max(rt,1),rx:2,fill:Ge[1],opacity:.85}),e.jsx("rect",{x:Ve+an/2,y:Ke.top+zt-ss,width:Zt,height:Math.max(ss,1),rx:2,fill:ms.positiveDeep,opacity:.85})]},ue.date)}),(()=>{const ue=Math.min(c.length,7);return Array.from({length:ue},(tt,Ve)=>{const rt=c.length===1?0:Math.round(Ve/(ue-1)*(c.length-1)),ss=Ke.left+_t*rt+_t/2;return e.jsx("text",{x:ss,y:wt-8,textAnchor:"middle",fill:Be.textDim,fontSize:"10",fontFamily:"inherit",children:c[rt].date.slice(5)},`xl-${rt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-5",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:G.startDate,onChange:c=>w(v=>({...v,startDate:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:G.endDate,onChange:c=>w(v=>({...v,endDate:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:G.query,onChange:c=>w(v=>({...v,query:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:G.page,onChange:c=>w(v=>({...v,page:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:G.limit,onChange:c=>w(v=>({...v,limit:c.target.value}))})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. When a filter or column sort is active, up to ",rs.toLocaleString()," matching rows load so sorting covers the full set."]}),p.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(ft).map(c=>e.jsx("th",{className:"text-right","aria-sort":Fe?.key===c?Fe.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-zinc-200 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded px-1 -mx-1",onClick:()=>Gt(v=>v?.key===c?v.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"}),children:[Fi[c],Fe?.key===c?Fe.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:K.map((c,v)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-400",children:c.date}),e.jsx("td",{className:"max-w-xs truncate text-zinc-200",children:c.query}),e.jsx("td",{className:"max-w-xs truncate text-zinc-400",children:c.page}),e.jsx("td",{className:"text-right tabular-nums text-zinc-300",children:c.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-400",children:[(Number.isFinite(c.ctr)?c.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.position.toFixed(1)})]},`${c.date}:${c.query}:${c.page}:${v}`))})]})}),pe?e.jsx("div",{className:"mt-3 text-xs text-zinc-500",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",Y.toLocaleString()," matching row",Y===1?"":"s",Y>=rs?` (capped at ${rs.toLocaleString()} — narrow the filter to see more)`:""]})}):(J>0||fe)&&(()=>{const c=parseInt(G.limit,10)||20,v=J+1,X=J+p.length;return e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-zinc-500",children:[e.jsxs("span",{className:"tabular-nums",children:["Showing ",v.toLocaleString()," – ",X.toLocaleString(),fe?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:ke||J===0,onClick:()=>{const re=Math.max(0,J-c);ae(re),Nt(re)},children:"Previous"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:ke||!fe,onClick:()=>{const re=J+c;ae(re),Nt(re)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No performance rows match the current filters yet."})]}),e.jsxs(U,{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"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:j,onChange:c=>x(c.target.value),onKeyDown:c=>c.key==="Enter"&&void nn()}),e.jsx(C,{type:"button",size:"sm",disabled:We||!je?.propertyId||!j.trim(),onClick:Z(nn),children:We?"Inspecting…":"Inspect URL"})]}),$&&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-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:$.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:$.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:rn($.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:Je($.crawlTime)})]})]})]}),e.jsxs(U,{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.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:ce,onClick:()=>{Jt()},children:ce?"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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:O,onChange:c=>H(c.target.value)}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:ce,onClick:()=>{Jt()},children:"Apply filter"})]}),L.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:L.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-300",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:rn(c.isMobileFriendly??null)}),e.jsx("td",{className:"text-zinc-400",children:Je(c.inspectedAt)})]},c.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No inspection history yet."})]}),e.jsxs(U,{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"})]})}),b.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:b.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState??"Unknown"}),e.jsx("td",{className:"text-zinc-300",children:c.currentState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Je(c.transitionDate)})]},`${c.url}:${c.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No deindexed transitions recorded."})]})]}),je&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-zinc-800/60 pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>Ft(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-zinc-500 transition-transform ${yt?"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-zinc-500",children:"Setup & Configuration"})]})}),yt&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(U,{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-zinc-500",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:R,disabled:ne||u.length===0,onChange:c=>y(c.target.value),children:u.length===0?e.jsx("option",{value:"",children:ne?"Loading properties…":"No properties available"}):u.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.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:ne,onClick:()=>{Js(je)},children:ne?"Refreshing…":"Refresh properties"}),e.jsx(C,{type:"button",size:"sm",disabled:!R||be,onClick:Z(pi),children:be?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(U,{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-zinc-500",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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",value:T,onChange:c=>B(c.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-zinc-800/60 bg-zinc-900/20 px-3 py-2 text-sm text-zinc-300",children:[e.jsx("input",{type:"checkbox",checked:E,onChange:c=>F(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(C,{type:"button",size:"sm",disabled:bs.isPending||!je.propertyId,onClick:Z(gi),children:bs.isPending?"Queueing…":"Queue sync"}),!je.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(U,{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:[je.sitemapUrl&&e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Current sitemap URL"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200 break-all",children:je.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:ut||!je.propertyId,onClick:()=>{mi()},children:ut?"Loading…":"Browse sitemaps from GSC"}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:qt.isPending||!je.propertyId,onClick:Z(en),children:qt.isPending?"Discovering…":"Auto-discover and queue inspection"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Browse lists available sitemaps without queueing a run. Auto-discover saves the primary sitemap and queues an inspection."}),nt&&nt.length>0&&e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:["Sitemaps (",nt.length,")"]}),nt.map(c=>{const v=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-zinc-200 break-all",children:c.path}),c.lastSubmitted&&e.jsxs("p",{className:"text-zinc-500",children:["Submitted: ",c.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[v&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-zinc-300",children:[v.indexed," / ",v.submitted]}),e.jsx("p",{className:"text-zinc-500",children:"indexed"})]}),e.jsx("button",{type:"button",className:"text-xs text-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>Ze(c.path),children:"Use"})]})]},c.path)})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:je.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:_e,onChange:c=>Ze(c.target.value),onKeyDown:c=>c.key==="Enter"&&_e.trim()&&void Xt()}),e.jsx(C,{type:"button",size:"sm",disabled:it||!_e.trim(),onClick:Z(Xt),children:it?"Saving…":je.sitemapUrl?"Update":"Save"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"Sitemap URL for inspection (leave empty for saved default)",id:`gsc-sitemap-inspect-${t}`}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:ys.isPending||!je.propertyId,onClick:Z(async()=>{const v=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||je.sitemapUrl||void 0;de(null),et(null);try{await ys.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:v}})}catch{}}),children:ys.isPending?"Queueing…":"Inspect sitemap"})]}),!je.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}function gc({projectName:t,projectId:s}){const n=mt(),[i,a]=r.useState(null),[l,o]=r.useState(!1),u=De(Bs({client:_,path:{name:t}})),m=u.data?.find(w=>w.connectionType==="gbp"),p=!!m,f=i?{locationName:i}:void 0,d=De({...ea({client:_,path:{name:t}}),enabled:p}),A=De({...ta({client:_,path:{name:t},query:f}),enabled:p}),L=De({...sa({client:_,path:{name:t},query:f}),enabled:p}),D=De({...na({client:_,path:{name:t},query:f}),enabled:p}),b=De({queryKey:["gbp-section-insights",t],queryFn:()=>ia(t),enabled:p});function k(){n.invalidateQueries({predicate:w=>{const J=w.queryKey[0];return typeof J?._id=="string"&&J._id.startsWith("getApiV1ProjectsByNameGbp")}})}const $=Kt({...ra(),onSuccess:w=>{aa({id:w.runId,projectId:s,kind:ds["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),se({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),M=r.useSyncExternalStore(ca,ln,ln),R=Object.values(M.runs).some(w=>w.kind===ds["gbp-sync"]&&w.projectId===s),y=$.isPending||R,j=Kt({...la(),onSuccess:()=>k()});if(r.useEffect(()=>{if(!i||!d.data)return;const w=d.data.locations.filter(J=>J.selected);(w.length<=1||!w.some(J=>J.locationName===i))&&a(null)},[i,d.data]),u.isLoading)return null;if(!m){const w=[{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-zinc-900/80 px-1 py-0.5 font-mono text-[11px] text-zinc-400",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-zinc-900/80 px-1 py-0.5 font-mono text-[11px] text-zinc-400",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(U,{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-zinc-500",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:w.map((J,ae)=>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-zinc-800 text-xs font-medium tabular-nums text-zinc-300","aria-hidden":"true",children:ae+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:J.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-zinc-900/80 px-2 py-1 font-mono text-xs text-zinc-300",children:J.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-zinc-500",children:J.note})]})]},J.title))})]})})}const x=A.data,T=d.data?.locations??[],B=T.filter(w=>w.selected),E=L.data?.keywords??[],F=D.data?.places??[],S=T.length>0?T[0].accountName:m.domain,I=i?T.find(w=>w.locationName===i)?.displayName??null:null,G=(b.data??[]).filter(w=>!w.dismissed&&(w.type==="gbp-listing-discrepancy"||w.type==="gbp-lodging-gap")&&(!I||w.query===i||w.title.startsWith(I)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(U,{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(Ne,{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(ie,{tone:"positive",children:"Connected"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:y,onClick:()=>$.mutate({client:_,path:{name:t},body:{}}),children:y?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-zinc-500",children:[S?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-zinc-400",children:S})," · "]}):null,d.data?`${d.data.totalSelected} of ${d.data.totalDiscovered} locations tracked`:"Loading locations…"]}),B.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(bn,{label:"All locations",active:i===null,onClick:()=>a(null)}),B.map(w=>e.jsx(bn,{label:w.displayName,active:i===w.locationName,onClick:()=>a(w.locationName)},w.id))]}),B.length===0?e.jsxs("p",{className:"text-sm text-zinc-500",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-zinc-300",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[G.length>0&&e.jsx("div",{className:"mb-6 grid gap-2",children:G.map(w=>e.jsx("div",{className:"insight-card insight-card-negative rounded-r-lg border border-zinc-800/60 bg-zinc-900/30 p-3 pl-4",children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-zinc-200",children:[w.title,w.recommendation?.reason&&e.jsx(Ne,{text:w.recommendation.reason})]})},w.id))}),x&&e.jsx(fc,{performance:x.performance,freshness:x.freshness,timeseries:x.timeseries}),F.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Public listing · Google Maps"}),e.jsx("div",{className:"grid gap-2",children:F.map(w=>{const J=T.find(ae=>ae.locationName===w.locationName);return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:J?.displayName??w.locationName}),e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[w.amenities.length," amenit",w.amenities.length===1?"y":"ies"," advertised"]})]}),w.amenities.length>0?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:w.amenities.map(ae=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 px-2 py-0.5 text-[11px] text-zinc-400",children:ae},ae))}):e.jsx("p",{className:"mt-1 text-sm text-zinc-500",children:"Public listing advertises no structured amenities."}),J?.mapsUri&&e.jsx("a",{href:J.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-block text-[11px] text-zinc-500 hover:text-zinc-300",children:"View on Google Maps →"})]},w.locationName)})})]}),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"}),L.data&&L.data.total>0&&e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[L.data.thresholdedPct,"% privacy-thresholded"]})]}),E.length===0?e.jsx("p",{className:"text-sm text-zinc-500",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"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:E.slice(0,25).map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-300",children:w.keyword}),e.jsx("td",{className:"text-right font-mono text-zinc-200",children:w.valueCount!==null?w.valueCount.toLocaleString():e.jsxs("span",{className:"text-zinc-500",title:"Privacy floor — Google withheld the exact count",children:["<",w.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-zinc-600",children:[w.periodStart,"–",w.periodEnd]})]},`${w.locationName}:${w.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-zinc-800/60 pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-zinc-400 hover:text-zinc-200",onClick:()=>o(w=>!w),"aria-expanded":l,children:[e.jsx("span",{"aria-hidden":"true",children:l?"▾":"▸"})," Manage locations (",T.length,")"]}),l&&e.jsx("div",{className:"mt-3",children:T.length===0?e.jsxs("p",{className:"text-sm text-zinc-500",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"}),e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-200",children:w.displayName}),e.jsx("td",{className:"text-zinc-500",children:w.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ie,{tone:w.selected?"positive":"neutral",children:w.selected?"Tracked":"Not tracked"})}),e.jsx("td",{className:"text-right",children:e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:j.isPending,onClick:()=>j.mutate({client:_,path:{name:t,locationName:w.locationName},body:{selected:!w.selected}}),children:w.selected?"Untrack":"Track"})})]},w.id))})]})})]})]})})}function bn({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-zinc-500 bg-zinc-800 text-zinc-100":"border-zinc-700/60 text-zinc-400 hover:border-zinc-600 hover:text-zinc-200"}`,children:t})}function fc({performance:t,freshness:s,timeseries:n}){const i=t.totals,a=oa.filter(D=>(i[D]??0)>0),l=da.filter(D=>(i[D]??0)>0),o=Object.keys(i).filter(D=>(i[D]??0)>0&&xa(D)==="other").sort((D,b)=>(i[b]??0)-(i[D]??0)),u=Object.keys(i).filter(D=>(i[D]??0)===0).sort(),m=n.map(D=>{const b={date:D.date};for(const[k,$]of Object.entries(D.metrics))b[k]=$;return b}),p=n.find(D=>D.pending)?.date,f=n.length>0?n[n.length-1].date:void 0,d=m.length>0,A=s.dataThroughDate?`Data through ${jt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,L=[...a,...o];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:"Conversions · daily"}),A&&e.jsx("span",{className:"text-[11px] text-zinc-500",children:A})]}),!d||a.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No conversion activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(yn,{data:m,metrics:a,kind:"line",firstPending:p,lastDate:f}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:L.map(D=>e.jsxs("span",{className:"text-sm text-zinc-400",children:[xs(D)," ",e.jsx("span",{className:"font-mono text-zinc-100",children:(i[D]??0).toLocaleString()})]},D))})]})]}),d&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(yn,{data:m,metrics:l,kind:"area",firstPending:p,lastDate:f})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Not active: ",u.map(D=>xs(D)).join(", ")]})]})}function yn({data:t,metrics:s,kind:n,firstPending:i,lastDate:a}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Rt,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(_s,{stroke:qs,vertical:!1}),e.jsx(Tt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:st},tickFormatter:It,minTickGap:24}),e.jsx(Et,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(Mt,{...xt,labelFormatter:jt,formatter:(l,o)=>[typeof l=="number"?l.toLocaleString():String(l??0),xs(String(o??""))]}),e.jsx(Hn,{wrapperStyle:{fontSize:11,color:Be.text},formatter:l=>xs(l)}),i&&a&&e.jsx(Ir,{x1:i,x2:a,fill:Be.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Be.textDim,fontSize:10}}),s.map((l,o)=>n==="line"?e.jsx(Us,{type:"monotone",dataKey:l,stroke:Ge[o%Ge.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx(kt,{type:"monotone",dataKey:l,stackId:"reach",stroke:Ge[o%Ge.length],fill:Ge[o%Ge.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function ks({children:t,label:s="More info",placement:n="top",className:i}){const a=r.useId(),[l,o]=r.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${i??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?a:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-zinc-500 hover:text-zinc-200 focus:text-zinc-200 focus:outline-none focus-visible:ring-1 focus-visible:ring-zinc-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Pr,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:a,role:"tooltip",className:`absolute z-50 w-64 rounded border border-zinc-700 bg-zinc-900 px-3 py-2 text-xs font-normal leading-relaxed text-zinc-200 shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const gt=50;function St(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function cs(t){return t.toLocaleString()}function jc(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function bc(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function yc(t){const s=t.filter(n=>n.kind===ds["backlink-extract"]&&!On(n.status));return s.length===0?null:s.reduce((n,i)=>n.createdAt>i.createdAt?n:i)}function vc(t,s){const n=new Date(t??s).getTime(),i=Math.max(0,Math.floor((Date.now()-n)/1e3));if(i<60)return`${i}s`;const a=Math.floor(i/60),l=i%60;return l===0?`${a}m`:`${a}m ${l}s`}function Nc({projectName:t}){const[s,n]=r.useState(null),[i,a]=r.useState(null),[l,o]=r.useState([]),[u,m]=r.useState(null),[p,f]=r.useState(null),[d,A]=r.useState(null),[L,D]=r.useState(Date.now()),[b,k]=r.useState(0),[$,M]=r.useState(!0),[R,y]=r.useState(!1),[j,x]=r.useState(null),T=r.useRef(null),B=r.useCallback(async()=>{M(!0),x(null);try{const[Q,Y,xe,pe,g]=await Promise.all([ma().catch(()=>null),ua(t,{excludeCrawlers:!0}).catch(()=>null),ha(t,{limit:gt,offset:b,excludeCrawlers:!0}).catch(H=>{if(H instanceof Ms&&H.code==="NOT_FOUND")return null;throw H}),pa(t).catch(()=>[]),ga(t).catch(()=>[])]);m(Q),n(Y),a(xe),o(pe);const O=yc(g);f(O),T.current=O?.id??null}catch(Q){x(Q instanceof Error?Q.message:"Failed to load backlinks")}finally{M(!1)}},[t,b]);r.useEffect(()=>{B()},[B]),r.useEffect(()=>{if(!p)return;const Q=p.id;let Y=!1;const xe=async()=>{try{const g=await Fn(Q);if(Y)return;On(g.status)?(f(null),A(g),await B()):f(O=>O?.id===g.id?{...O,...g}:O)}catch{}},pe=window.setInterval(()=>{xe()},3e3);return()=>{Y=!0,window.clearInterval(pe)}},[p,B]),r.useEffect(()=>{if(!p)return;const Q=window.setInterval(()=>D(Date.now()),1e3);return()=>window.clearInterval(Q)},[p]),r.useEffect(()=>{if(!d||d.status==="failed")return;const Q=window.setTimeout(()=>A(null),1e4);return()=>window.clearTimeout(Q)},[d]);async function E(){y(!0),x(null);try{const Q=await ya(t);f(Q),T.current=Q.id}catch(Q){Q instanceof Ms&&Q.code==="MISSING_DEPENDENCY"?x("DuckDB is not installed. Visit the Backlinks admin page to install it."):x(Q instanceof Error?Q.message:"Failed to trigger extract")}finally{y(!1)}}const F=r.useMemo(()=>l.slice().sort((Q,Y)=>Q.queriedAt.localeCompare(Y.queriedAt)).map(Q=>({date:Q.queriedAt,linkingDomains:Q.totalLinkingDomains})),[l]),S=i?.rows??[],I=i?.total??0,G=s?.excludedLinkingDomains??0,w=I>gt,J=Math.floor(b/gt)+1,ae=Math.max(1,Math.ceil(I/gt));return r.useEffect(()=>{b>0&&b>=I&&k(0)},[b,I]),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-zinc-500 mt-1 max-w-2xl",children:["Domains linking to "," ",e.jsx("span",{className:"text-zinc-300",children:t}),", extracted from the Common Crawl hyperlink graph. Updates when a release sync completes — no live scraping, no paid API."]})]})}),j&&e.jsx(U,{className:"surface-card p-4 mb-4 border-rose-800/60",children:e.jsx("p",{className:"text-sm text-rose-300",children:j})}),p&&e.jsx(U,{className:"surface-card p-4 mb-4 border-sky-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(fa,{className:"h-5 w-5 text-sky-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-zinc-100",children:"Extract running"}),e.jsx(ie,{tone:"neutral",children:p.status}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:[vc(p.startedAt??null,p.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",L]})]}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Re-querying the cached Common Crawl release for"," ",e.jsx("span",{className:"text-zinc-300",children:t}),". No re-download — the ~16 GB dump already lives at"," ",e.jsx("code",{className:"text-zinc-400",children:"~/.canonry/cache/commoncrawl/"}),". Typically takes ~5 minutes."]})]})]})}),d&&!p&&e.jsx(U,{className:`surface-card p-4 mb-4 ${d.status==="failed"?"border-rose-800/60":"border-emerald-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[d.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-rose-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(Wn,{className:"h-5 w-5 text-emerald-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${d.status==="failed"?"text-rose-300":"text-emerald-300"}`,children:d.status==="failed"?"Extract failed":"Extract complete"}),d.error?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:ja(d.error)}):d.status!=="failed"?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),fe()]});function fe(){if($)return e.jsx(U,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading backlinks…"})});const Q=s!==null&&s.totalLinkingDomains>0,Y=d?.status==="failed",xe=s!==null&&s.totalLinkingDomains===0&&!Y,pe=u?.status==="ready",g=u?.status==="failed",O=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return Q?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-zinc-50",children:cs(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Total linking hosts"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-zinc-50",children:cs(s.totalHosts)})}),e.jsx("p",{className:"metric-card-sub",children:"aggregate host count 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-zinc-50",children:jc(s.top10HostsShare)})}),e.jsx("p",{className:"metric-card-sub",children:"share of hosts from the 10 largest linking domains"})]})]}),e.jsxs("p",{className:"text-xs text-zinc-600 mt-2",children:["Release ",e.jsx("code",{className:"text-zinc-400",children:s.release})," · queried ",bc(s.queriedAt),G>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-zinc-500",children:[G," crawler/proxy domain",G===1?"":"s"," hidden"]})]})]}),F.length>=2&&e.jsxs(U,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over releases"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Rt,{data:F,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:Ge[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Ge[0],stopOpacity:0})]})}),e.jsx(Tt,{dataKey:"date",tick:He,stroke:st,tickFormatter:It}),e.jsx(Et,{tick:He,stroke:st,allowDecimals:!1}),e.jsx(Mt,{contentStyle:xt.contentStyle,labelStyle:xt.labelStyle,itemStyle:xt.itemStyle,labelFormatter:jt}),e.jsx(kt,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Ge[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"}),w&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Page ",J," of ",ae," · ",cs(I)," total"]})]}),e.jsx(U,{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-zinc-800 text-left text-xs uppercase tracking-wide text-zinc-600",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:"Linking hosts"})]})}),e.jsxs("tbody",{children:[S.map(H=>e.jsxs("tr",{className:"border-b border-zinc-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-zinc-200",children:H.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-zinc-400 tabular-nums",children:cs(H.numHosts)})]},H.linkingDomain)),S.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-zinc-500",colSpan:2,children:G>0&&I===0?`Every referring domain in this release was a crawler/proxy host (${G} hidden).`:"No referring domains in this release."})})]})]})}),w&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:b===0,onClick:()=>k(H=>Math.max(0,H-gt)),children:"Previous"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:b+gt>=I,onClick:()=>k(H=>H+gt),children:"Next"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(C,{type:"button",variant:"outline",size:"sm",disabled:R||p!==null,onClick:Z(E),children:[e.jsx(Qs,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),p?"Extract running…":R?"Queuing…":"Re-run extract"]}),e.jsxs(ks,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the ",e.jsx("span",{className:"text-zinc-200",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-zinc-300",children:"~/.canonry/cache/commoncrawl/"})," for ",e.jsx("span",{className:"text-zinc-200",children:t}),". Replaces existing backlink rows for this project under the current release."]}),e.jsxs("span",{className:"mt-2 block text-zinc-400",children:[e.jsx("span",{className:"text-zinc-200",children:"No re-download"})," of the ~16 GB dump. Typically ",e.jsx("span",{className:"text-zinc-200",children:"~5 min"}),"."]})]}),e.jsx(C,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:St("/backlinks"),children:"Open admin"})})]})]}):e.jsx(U,{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-zinc-900 text-zinc-400",children:e.jsx(ba,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!u&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),e.jsx("div",{className:"mt-4",children:e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:St("/backlinks"),children:"Set up backlinks"})})})]}),O&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["A workspace release sync is running (",u.status,u.phaseDetail?` — ${u.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),e.jsx("div",{className:"mt-4",children:e.jsx(C,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:St("/backlinks"),children:"View sync status"})})})]}),g&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:u.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),e.jsx("div",{className:"mt-4",children:e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:St("/backlinks"),children:"Go to Backlinks admin"})})})]}),pe&&!O&&!xe&&!Y&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["Release ",e.jsx("code",{className:"text-zinc-300",children:u.release})," is ready but no backlinks have been extracted for"," ",e.jsx("code",{className:"text-zinc-300",children:t}),". Run an extract to populate data using the cached release."]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(C,{type:"button",size:"sm",disabled:R||p!==null,onClick:Z(E),children:[e.jsx(Vt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),p?"Extract running…":R?"Queuing…":"Run extract"]}),e.jsxs(ks,{label:"What does Run extract do?",children:[e.jsxs("span",{className:"block",children:["Runs a DuckDB query against the ",e.jsx("span",{className:"text-zinc-200",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-zinc-300",children:"~/.canonry/cache/commoncrawl/"})," to find referring domains for ",e.jsx("span",{className:"text-zinc-200",children:t}),"."]}),e.jsxs("span",{className:"mt-2 block text-zinc-400",children:["No re-download. Typically takes ",e.jsx("span",{className:"text-zinc-200",children:"~5 min"}),"."]})]})]})]}),Y&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Last extract failed"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["See the error above for details. If the cache files for release"," ",e.jsx("code",{className:"text-zinc-300",children:u?.release})," are missing, re-sync the release from the Backlinks admin to restore the ~16 GB dump, then re-run the extract."]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:St("/backlinks"),children:"Go to Backlinks admin"})})})]}),xe&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["The last extract against release ",e.jsx("code",{className:"text-zinc-300",children:s.release})," found"," ",e.jsx("span",{className:"text-zinc-300",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-zinc-300",children:s.targetDomain}),". This can happen when:"]}),e.jsxs("ul",{className:"mt-2 space-y-1 text-xs text-zinc-500 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-zinc-500 mt-3",children:"Try syncing a newer release — each Common Crawl dump is a different snapshot of the web graph."}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:St("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(C,{type:"button",variant:"outline",size:"sm",disabled:R||p!==null,onClick:Z(E),children:[e.jsx(Vt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),p?"Extract running…":R?"Queuing…":"Re-run extract"]}),e.jsxs(ks,{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-zinc-200",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-zinc-400",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 wc({projectName:t}){const s=De({...va({client:_,path:{name:t}}),staleTime:Gn}),n=s.data??null,i=s.error;if(s.isLoading&&!n)return null;if(i)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-rose-400",children:i instanceof Error?i.message:String(i)})]});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-zinc-500",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:a,providersMentioning:l,providersConfigured:o}=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 ",a," of ",o," engines",e.jsx(Ne,{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-zinc-300 flex items-center gap-2",children:["Mentioned in ",l," of ",o," engine answers",e.jsx(Ne,{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(zc,{data:n}),e.jsx(Sc,{data:n}),n.competitorGaps.length>0&&e.jsx(Lc,{data:n})]})}function zc({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:i,queriesMentionedOnly:a,queriesInvisible:l}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(ls,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(ls,{label:"Cited only",value:`${i} / ${s}`,helper:"In sources, not named in answer",tone:i>0?"positive-dim":"neutral"}),e.jsx(ls,{label:"Mentioned only",value:`${a} / ${s}`,helper:"Named in answer, no source link",tone:a>0?"caution":"neutral"}),e.jsx(ls,{label:"Invisible",value:`${l} / ${s}`,helper:"No engine cites or mentions",tone:l>0?"negative":"neutral"})]})}function ls({label:t,value:s,helper:n,tone:i}){const a=i==="positive"?"text-emerald-300":i==="positive-dim"?"text-emerald-400/70":i==="caution"?"text-amber-300":i==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:n})]})}function Sc({data:t}){const s=r.useMemo(()=>{const n=new Set;for(const i of t.byQuery)for(const a of i.providers)n.add(a.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(kc,{}),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($t,{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-zinc-100",children:n.query}),s.map(i=>{const a=n.providers.find(l=>l.provider===i);return e.jsx("td",{className:"text-center",children:a==null?e.jsx(Er,{className:"inline h-3.5 w-3.5 text-zinc-700","aria-label":"no data"}):e.jsx(Cc,{provider:a})},i)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-emerald-300":n.citedCount>0?"text-emerald-400/70":"text-zinc-500",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-sky-300":n.mentionedCount>0?"text-sky-400/70":"text-zinc-500",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function kc(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-zinc-500",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ct,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ct,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Ct,{active:!1,tone:"cited"}),e.jsx(Ct,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Cc({provider:t}){const s=Ac(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Ct,{active:t.cited,tone:"cited"}),e.jsx(Ct,{active:t.mentioned,tone:"mentioned"})]})}function Ac(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 Ct({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-zinc-700/80 bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-emerald-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-sky-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Lc({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-zinc-200 mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Ne,{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-zinc-500",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-zinc-100",children:s.query}),e.jsx("td",{children:e.jsx($t,{provider:s.provider})}),e.jsx("td",{className:"text-zinc-300",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const fs="__cited__",js="__mentioned__";function vn(t){return Math.round(t*1e3)/10}function Dc(t,s,n){const i=t.buckets.length>0,a=t.buckets.length===1;if(n==="overall"){const m=s==="cited"?fs:js,p=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[m]:vn(d[p])})),series:[m],hasData:i,singleBucket:a}}const l=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(m=>Object.keys(m.byProvider??{})))].sort();return{rows:t.buckets.map(m=>{const p={date:m.startDate};for(const f of o){const d=m.byProvider?.[f];p[f]=d?vn(d[l]):null}return p}),series:o,hasData:i,singleBucket:a}}function $c(t,s){for(let n=t.length-1;n>=0;n--){const i=t[n][s];if(typeof i=="number"&&Number.isFinite(i))return i}return null}function Nn(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function wn(t){return t>0?`+${t}`:`${t}`}function Ic(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${wn(n.delta)} on ${Nn(n.date)}`).join(", ")}`;const s=[...t].sort((n,i)=>i.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${wn(s.delta)} on ${Nn(s.date)})`}const Pc=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Rc=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Tc=[{value:"mentioned",label:"Mentioned"},{value:"cited",label:"Cited"}],Ec="#18181b",Mc={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Oc(t){return Mc[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Cs(t){return Math.round(t*10)/10}function Fc(t){return t===fs||t===js}function zn(t){return t===fs?"Cited":t===js?"Mentioned":Oc(t)}function As(t,s){return t===fs?ms.positive:t===js?Ge[1]:Lr(t,s)}function Ls({options:t,value:s,onChange:n,ariaLabel:i,className:a}){return e.jsx("div",{role:"group","aria-label":i,className:`segmented ${a??""}`,children:t.map(l=>{const o=s===l.value;return e.jsx("button",{type:"button","aria-pressed":o,className:`segmented-option ${o?"segmented-option-active":""}`,onClick:()=>n(l.value),children:l.label},l.value)})})}function Gc({projectName:t}){const[s,n]=r.useState("all"),[i,a]=r.useState("mentioned"),[l,o]=r.useState("byProvider"),u=De({queryKey:["analytics-metrics",t,s],queryFn:()=>Na(t,s),staleTime:Gn}),m=u.data??null,p=u.error,f=r.useMemo(()=>m?Dc(m,i,l):null,[m,i,l]),d=l==="byProvider",A=i==="cited"?"citationRate":"mentionRate",L=i==="cited"?"Cited":"Mentioned",D=i==="cited"?ms.positive:Ge[1],b=d?Be.textDim:D,k=m?.buckets??[],$=k.length>0?Cs(k[k.length-1][A]*100):null,M=k.length>0?Cs(k[0][A]*100):null,R=$!==null&&M!==null&&k.length>1?Cs($-M):null,y=e.jsxs(e.Fragment,{children:[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:["Citations & mentions over time",e.jsx(Ne,{text:"How often AI engines cited your domain as a source (Cited) and named your brand in the answer text (Mentioned), across all tracked queries, over time. Each point is a sweep bucket; rates are the share of (query × provider) snapshots in that bucket."})]})]}),$!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:b},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:L}),d&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[$,"%"]}),R!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${R>0?"text-emerald-400":R<0?"text-rose-400":"text-zinc-500"}`,children:[R>0?"+":"",R.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Ls,{options:Tc,value:i,onChange:a,ariaLabel:"Metric"}),e.jsx(Ls,{options:Rc,value:l,onChange:o,ariaLabel:"Series"}),e.jsx(Ls,{options:Pc,value:s,onChange:n,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let j;if(p)j=e.jsx("p",{className:"text-sm text-rose-400",children:p instanceof Error?p.message:String(p)});else if(u.isLoading&&!m)j=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-zinc-900/40","aria-hidden":"true"});else if(!m||!f)j=null;else{const{rows:x,series:T,hasData:B,singleBucket:E}=f,F=Ic(m.queryChanges);if(!B)j=e.jsx("p",{className:"text-sm text-zinc-400",children:"Run a sweep to start tracking citations and mentions over time."});else if(l==="byProvider"&&T.length===0)j=e.jsxs("p",{className:"text-sm text-zinc-400",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-zinc-200",children:"All engines"})," to see the trend."]});else{const S=`${L} rate across ${x.length} ${x.length===1?"sweep":"sweeps"}. Latest ${$}%${R!==null?`, ${R>=0?"up":"down"} ${Math.abs(R).toFixed(1)} points over the period`:""}.`;j=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:S}),l==="byProvider"&&T.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:T.map((I,G)=>{const w=$c(x,I);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:As(I,G)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:zn(I)}),w!==null&&e.jsxs("span",{className:"trend-legend-value",children:[w,"%"]})]},I)})}),e.jsx("div",{className:"visibility-trend-chart",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Rt,{data:x,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(_s,{stroke:qs,vertical:!1}),e.jsx(Tt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:st},tickFormatter:It,minTickGap:24}),e.jsx(Et,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:I=>`${I}%`,tick:He,tickLine:!1,axisLine:!1,width:40}),e.jsx(Mt,{...xt,cursor:{stroke:st,strokeWidth:1},labelFormatter:jt,formatter:(I,G)=>[I==null?"no data":`${I}%`,zn(String(G))]}),T.map((I,G)=>e.jsx(Us,{type:"monotone",dataKey:I,name:I,stroke:As(I,G),strokeWidth:Fc(I)?2.5:2,dot:{r:2.5,fill:As(I,G),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Ec},connectNulls:!0,isAnimationActive:!1},I))]})})}),E&&e.jsx("p",{className:"visibility-trend-note",children:"Only one sweep so far. The trend line fills in after the next run."}),F&&e.jsx("p",{className:"visibility-trend-note",children:F})]})}}return e.jsxs("section",{className:"visibility-trend",children:[y,j]})}const Gs=new Set(["queued","seeding","probing"]);function Bc({projectName:t}){const s=mt(),[n,i]=r.useState(null),[a,l]=r.useState(""),[o,u]=r.useState("100"),m=De({...wa({client:_,path:{name:t},query:{limit:"10"}}),refetchInterval:y=>y.state.data?.some(x=>Gs.has(x.status))?3e3:!1}),p=m.data??[];r.useEffect(()=>{!n&&p[0]&&i(p[0].id)},[n,p]);const f=p.find(y=>y.id===n)??null,d=De({...za({client:_,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:f&&Gs.has(f.status)?3e3:!1}),A=d.data??null,L=De({...Sa({client:_,path:{name:t,id:n??""}}),enabled:!!(n&&f?.status==="completed")}),D=Kt({mutationFn:()=>{const y={},j=a.trim();j&&(y.icpDescription=j);const x=Number.parseInt(o,10);return Number.isFinite(x)&&x>0&&(y.maxProbes=x),ka(t,y)},onSuccess:async y=>{i(y.sessionId),l(""),await kn(s,t,y.sessionId),se({title:"Discovery started",detail:`Run ${Ds(y.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${y.sessionId}`,dedupeMode:"replace"})},onError:y=>{se({title:"Discovery failed to start",detail:y instanceof Error?y.message:"Could not start discovery.",tone:"negative"})}}),b=Kt({mutationFn:y=>{if(!n)throw new Error("Select a completed discovery session first.");return Ca(t,n,y)},onSuccess:async y=>{await kn(s,t,y.sessionId),s.invalidateQueries({queryKey:Bn({client:_})}),s.invalidateQueries({predicate:j=>Array.isArray(j.queryKey)&&j.queryKey[0]==="projects"&&j.queryKey.length>1}),se({title:"Queries added",detail:Qc(y),tone:"positive",dedupeKey:`discovery:promote:${y.sessionId}`,dedupeMode:"replace"})},onError:y=>{se({title:"Could not add queries",detail:y instanceof Error?y.message:"Could not add queries from this run.",tone:"negative"})}}),k=A??f,$=L.data??null,M=($?.queriesByBucket.cited.length??0)+($?.queriesByBucket.aspirational.length??0),R=r.useMemo(()=>(A?.probes??[]).slice(0,30),[A?.probes]);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:"Discovery"}),e.jsx("h2",{children:"Find new queries to track"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"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(C,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{m.refetch()},children:[e.jsx(us,{size:14}),"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(U,{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(ie,{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-zinc-500",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:a,onChange:y=>l(y.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-zinc-500",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",inputMode:"numeric",value:o,onChange:y=>u(y.target.value)}),e.jsx("span",{className:"mt-1 block text-[11px] text-zinc-600",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),e.jsxs(C,{type:"button",size:"sm",disabled:D.isPending,onClick:()=>D.mutate(),children:[e.jsx(Vt,{size:14}),D.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(U,{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"})]}),m.isFetching&&e.jsx(ie,{tone:"neutral",children:"Loading"})]}),p.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:p.map(y=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===y.id?"border-zinc-600 bg-zinc-900/70":"border-zinc-800/60 bg-zinc-950/40 hover:border-zinc-700 hover:bg-zinc-900/40"}`,onClick:()=>i(y.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:Ds(y.id)}),e.jsx(ie,{tone:Sn(y.status),children:y.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-[11px] text-zinc-500",children:[e.jsxs("span",{children:["Cited ",y.citedCount??0]}),e.jsxs("span",{children:["Opportunity ",y.aspirationalCount??0]}),e.jsxs("span",{children:["Low value ",y.wastedCount??0]})]})]},y.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(U,{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:k?Ds(k.id):"No run selected"})]}),k&&e.jsx(ie,{tone:Sn(k.status),children:k.status})]}),k?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(lt,{label:"Questions tested",value:k.probeCount??0}),e.jsx(lt,{label:"Already cited",value:k.citedCount??0,tone:"positive"}),e.jsx(lt,{label:"Opportunities",value:k.aspirationalCount??0,tone:"caution"}),e.jsx(lt,{label:"Low value",value:k.wastedCount??0,tone:"negative"})]}),k.error&&e.jsx("div",{className:"rounded-md border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:k.error}),k.icpDescription&&e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-300",children:k.icpDescription})]}),k.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.competitorMap.slice(0,8).map(y=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[y.domain," ",e.jsx("span",{className:"text-zinc-500",children:y.hits})]},y.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),k?.status==="completed"&&e.jsxs(U,{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"})]}),e.jsxs(C,{type:"button",size:"sm",disabled:b.isPending||M===0,onClick:()=>b.mutate(void 0),children:[e.jsx(Wn,{size:14}),b.isPending?"Adding…":"Add recommended queries"]})]}),L.isLoading?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading recommendations…"}):$?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(lt,{label:"Queries to add",value:M,tone:"positive"}),e.jsx(lt,{label:"Already cited",value:$.queriesByBucket.cited.length,tone:"positive"}),e.jsx(lt,{label:"Opportunities",value:$.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(lt,{label:"Low value (skipped)",value:$.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-xs leading-5 text-zinc-500",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."}),$.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:$.suggestedCompetitors.map(y=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[y.domain," ",e.jsx("span",{className:"text-zinc-500",children:y.hits})]},y.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"No recommendations available for this run."})]}),e.jsxs(U,{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(ie,{tone:"neutral",children:"Loading"})]}),R.length===0?e.jsx("p",{className:"text-sm text-zinc-500",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:R.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-zinc-100",children:y.query}),e.jsx("td",{children:e.jsx(ie,{tone:qc(y.bucket),children:Uc(y.bucket)})}),e.jsx("td",{className:"text-zinc-400",children:y.citedDomains.length>0?y.citedDomains.slice(0,3).join(", "):"-"})]},y.id))})]})})]})]})]})]})}function lt({label:t,value:s,tone:n="neutral"}){const i=n==="positive"?"text-emerald-300":n==="caution"?"text-amber-300":n==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s})]})}function Sn(t){return t==="completed"?"positive":t==="failed"?"negative":Gs.has(t)?"caution":"neutral"}function qc(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const _c={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function Uc(t){return t?_c[t]:"Not classified"}function Ds(t){return t.length>8?t.slice(0,8):t}function Qc(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,i=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${i>0?`; ${i} already tracked`:""}.`}async function kn(t,s,n){await Promise.all([t.invalidateQueries({predicate:i=>{const a=i.queryKey[0];return typeof a?._id=="string"&&a._id.startsWith("getApiV1ProjectsByNameDiscover")}}),t.invalidateQueries({queryKey:qn({client:_})})])}const Cn=100,$s=12;function Is(t){return t>=70?"positive":t>=40?"caution":"negative"}function Ps(t){return t>=70?"text-emerald-400":t>=40?"text-amber-400":"text-rose-400"}function Kc(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function os(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function Vc({projectName:t}){const s=mt(),[n,i]=r.useState(!1),[a,l]=r.useState(null),o=De(Aa({client:_,path:{name:t}})),u=De(La({client:_,path:{name:t},query:{limit:30}})),m=De(Da({client:_,path:{name:t},query:{limit:Cn,sort:"score-asc"}})),p=Kt({mutationFn:()=>$a(t),onSuccess:()=>{se({title:"Technical audit started",detail:"The audit re-reads your sitemap in the background. Refresh in a minute to see the score.",tone:"positive"}),s.invalidateQueries({queryKey:qn({client:_})})},onError:x=>{se({title:"Could not start technical audit",detail:x instanceof Error?x.message:"Failed to start technical audit.",tone:"negative"})}}),f=()=>{s.invalidateQueries({queryKey:Pa({client:_,path:{name:t}})}),s.invalidateQueries({queryKey:Ra({client:_,path:{name:t},query:{limit:30}})}),s.invalidateQueries({queryKey:Ta({client:_,path:{name:t},query:{limit:Cn,sort:"score-asc"}})})},d=o.data;if(o.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!d||!d.hasData)return e.jsxs(U,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Or,{className:"mx-auto mb-3 h-8 w-8 text-zinc-500","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-zinc-100",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."}),e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(C,{type:"button",onClick:()=>p.mutate(),disabled:p.isPending,children:[e.jsx(Vt,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),p.isPending?"Starting…":"Run first audit"]})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-600",children:["Or from the CLI: ",e.jsxs("code",{className:"text-zinc-400",children:["canonry technical-aeo run ",t," --wait"]})]})]});const A=d.deltaScore==null?null:`${d.deltaScore>=0?"+":""}${d.deltaScore} vs previous`,L=d.trend==="up"?"positive":d.trend==="down"?"negative":"neutral",D=u.data?.points.map(x=>({date:x.auditedAt,score:x.aggregateScore}))??[],b=m.data?.pages??[],k=b.filter(x=>x.status==="success"),$=d.pagesErrored>0,M=n&&$,R=M?b.filter(x=>x.status==="error"):b,y=d.pagesAudited>b.length;function j(x){const T=[];for(const B of k){const E=B.factors.find(F=>F.id===x);E&&E.score<70&&T.push({url:B.url,score:E.score})}return T.sort((B,E)=>B.score-E.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-zinc-800/60 bg-zinc-900/30 p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${Ps(d.aggregateScore)}`,children:d.aggregateScore}),e.jsx("span",{className:"text-lg text-zinc-500",children:"/ 100"}),e.jsx(ie,{tone:Is(d.aggregateScore),children:os(d.aggregateScore)}),A?e.jsx(ie,{tone:L,children:A}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[d.pagesDiscovered," URL",d.pagesDiscovered===1?"":"s"," in sitemap · ",d.pagesAudited," audited · ",d.pagesSkipped," skipped · ",d.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-zinc-500",children:[e.jsx("span",{className:"text-zinc-600",children:"Sitemap:"}),e.jsx("a",{href:d.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-zinc-400 underline decoration-zinc-700 underline-offset-2 hover:text-zinc-200",children:d.sitemapUrl}),e.jsx(Ne,{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>`."})]}),d.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-zinc-600",children:["Audited ",new Date(d.auditedAt).toLocaleString()]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{type:"button",variant:"outline",size:"sm",onClick:f,children:[e.jsx(us,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),"Refresh"]}),e.jsxs(C,{type:"button",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,children:[e.jsx(Vt,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),p.isPending?"Starting…":"Re-run audit"]})]})]}),D.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.jsx("div",{className:"mt-3 h-56",children:e.jsx(Pt,{width:"100%",height:"100%",children:e.jsxs(Rt,{data:D,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(_s,{stroke:qs,vertical:!1}),e.jsx(Tt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:st},tickFormatter:It,minTickGap:24}),e.jsx(Et,{domain:[0,100],ticks:[0,25,50,75,100],tick:He,tickLine:!1,axisLine:!1,width:32}),e.jsx(Mt,{...xt,cursor:{stroke:st,strokeWidth:1},labelFormatter:jt,formatter:x=>[`${x}/100`,"Site score"]}),e.jsx(Us,{type:"monotone",dataKey:"score",name:"score",stroke:"#34d399",strokeWidth:2.5,dot:{r:2.5,fill:"#34d399",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(Ne,{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:d.factors.map(x=>{const T=a===x.id,B=d.crossCuttingIssues.find(S=>S.factorId===x.id),E=T?j(x.id):[],F=x.pagesPartial+x.pagesFailing;return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:T?"bg-zinc-900/30":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left font-medium text-zinc-200 hover:text-zinc-50","aria-expanded":T,onClick:()=>l(T?null:x.id),children:[T?e.jsx(_n,{className:"h-3.5 w-3.5 shrink-0 text-zinc-500","aria-hidden":"true"}):e.jsx(gs,{className:"h-3.5 w-3.5 shrink-0 text-zinc-500","aria-hidden":"true"}),x.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-500",children:[x.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-200",children:x.avgScore}),e.jsx("td",{children:e.jsx(ie,{tone:Kc(x.status),children:os(x.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-zinc-400",children:[e.jsx("span",{className:"text-emerald-400",children:x.pagesPassing})," / ",e.jsx("span",{className:"text-amber-400",children:x.pagesPartial})," / ",e.jsx("span",{className:"text-rose-400",children:x.pagesFailing})]})]}),T?e.jsx("tr",{className:"bg-zinc-900/30",children:e.jsx("td",{colSpan:5,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"space-y-4 border-l border-zinc-800 pl-4",children:[B&&B.topRecommendations.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-1.5 text-zinc-500",children:"How to fix"}),e.jsx("ul",{className:"space-y-1",children:B.topRecommendations.map((S,I)=>e.jsxs("li",{className:"flex gap-2 text-sm text-zinc-300",children:[e.jsx("span",{className:"select-none text-zinc-600",children:"→"}),e.jsx("span",{children:S})]},I))})]}):F===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"Every audited page passes this factor."}):null,F>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-zinc-500",children:["Pages below pass (",F,")"]}),e.jsx("ul",{className:"space-y-1",children:E.slice(0,$s).map(S=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${Ps(S.score)}`,children:S.score}),e.jsx("a",{href:S.url,target:"_blank",rel:"noreferrer",className:"truncate text-zinc-300 hover:text-zinc-100",title:S.url,children:S.url})]},S.url))}),E.length>$s?e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["+ ",E.length-$s," more below pass"]}):null,y?e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["Showing the worst ",b.length," audited pages."]}):null]}):null]})})}):null]},x.id)})})]})})]}),d.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(Ne,{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-zinc-800/60 overflow-hidden rounded-lg border border-zinc-800/60",children:d.crossCuttingIssues.map(x=>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-zinc-100",children:x.factorName}),e.jsx(ie,{tone:Is(x.avgScore),children:os(x.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-zinc-500",children:["avg ",x.avgScore," · affects ",x.affectedPages," of ",x.totalPages," pages (",x.affectedPct,"%)"]})]}),x.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:x.topRecommendations.map((T,B)=>e.jsxs("li",{className:"flex gap-2 text-sm text-zinc-400",children:[e.jsx("span",{className:"select-none text-zinc-600",children:"→"}),e.jsx("span",{children:T})]},B))}):null]},x.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"})]}),$?e.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-800/60 p-0.5",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>i(!1),"aria-pressed":!M,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${M?"text-zinc-500 hover:text-zinc-300":"bg-zinc-800 text-zinc-100"}`,children:["All ",d.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>i(!0),"aria-pressed":M,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${M?"bg-rose-500/15 text-rose-300":"text-zinc-500 hover:text-zinc-300"}`,children:["Errors ",d.pagesErrored]})]}):null]}),R.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",{children:"URL"})]})}),e.jsx("tbody",{children:R.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:x.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-rose-400",children:[e.jsx(Ia,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:Ps(x.overallScore),children:x.overallScore})}),e.jsx("td",{children:x.status==="error"?e.jsx(ie,{tone:"negative",children:"Error"}):e.jsx(ie,{tone:Is(x.overallScore),children:os(x.overallScore)})}),e.jsx("td",{className:"max-w-0",children:e.jsx("a",{href:x.url,target:"_blank",rel:"noreferrer",className:"block truncate text-zinc-300 hover:text-zinc-100",title:x.status==="error"?x.error??x.url:x.url,children:x.url})})]},x.url))})]})}),y?e.jsxs("p",{className:"mt-2 text-xs text-zinc-600",children:["Showing the worst ",b.length," of ",d.pagesAudited," audited pages."]}):null]})]})]})}const Hc={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ve(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 Wc(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 Yc(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Jc({projectName:t}){const[s,n]=r.useState(!1),[i,a]=r.useState(null),l=De(Ea({client:_,path:{name:t}}));async function o(){n(!0),a(null);try{await Ma(t,"client")}catch(m){const p=m instanceof Ms||m instanceof Error?m.message:"Download failed";a(p)}finally{n(!1)}}if(l.isLoading)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading report…"});if(l.error){const m=l.error instanceof Error?l.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-rose-400",children:m})})}const u=l.data;return u?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:u.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[u.meta.project.canonicalDomain," · ",u.meta.project.country," / ",u.meta.project.language.toUpperCase(),u.meta.location?` · Location: ${Yc(u.meta.location)}`:" · No location set"," · ","Generated ",Wc(u.meta.generatedAt)]}),i&&e.jsx("p",{className:"mt-2 text-xs text-rose-400",children:i})]}),e.jsx("div",{className:"page-header-right",children:e.jsxs(C,{variant:"secondary",size:"sm",onClick:Z(o),disabled:s,children:[e.jsx(Qs,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})})]}),e.jsx(il,{report:u}),e.jsx(xl,{report:u,audience:"client"}),e.jsx(el,{report:u}),e.jsx(cl,{report:u,audience:"client",projectName:t}),e.jsx(ll,{report:u})]}):null}const An="AI Visibility — Server-Side",Ln="AI engine attention",Xc="What AI engines actually do in your server logs over the last 7 days — the other half of citations.",Zc="Live telemetry from your server logs.";function el({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ht,{eyebrow:Ln,title:An,subtitle:Zc}),e.jsx("p",{className:"text-sm text-zinc-500",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:Vr(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},i=zs(n,"requests"),a=`${ve(s.verifiedCrawlerHits.current)} verified · ${ve(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,l=zs(s.aiUserFetchHits,"requests"),o=zs(s.referralArrivals,"sessions"),u=s.byOperator.filter(m=>m.verifiedHits>0||m.unverifiedHits>0||m.userFetchHits>0||m.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ht,{eyebrow:Ln,title:An,subtitle:Xc}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Es,{label:"AI bot requests observed",value:ve(n.current),subtitle:a}),e.jsx(Es,{label:"AI user-fetch requests",value:ve(s.aiUserFetchHits.current),subtitle:l||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Es,{label:"AI referral sessions",value:ve(s.referralArrivals.current),subtitle:o})]}),u.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.jsx("th",{children:"Bot requests (7d)"}),e.jsx("th",{children:"User fetches (7d)"}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:u.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:m.operator}),e.jsx("td",{children:ve(m.verifiedHits+m.unverifiedHits)}),e.jsx("td",{children:ve(m.userFetchHits)}),e.jsx("td",{children:ve(m.referralArrivals)})]},m.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-zinc-500",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 tl(t,s){return t.audience==="both"||t.audience===s}const sl={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function hs(t){return sl[t]??t.charAt(0).toUpperCase()+t.slice(1)}function nl(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 il({report:t}){const s=t.executiveSummary,n=t.citationScorecard,i=s.totalQueryCount,a=i>0?`${s.citationRate}%`:"—",l=i>0?`When customers asked AI ${i} ${i===1?"question":"questions"} about your industry, AI linked to your website in ${s.citedQueryCount} of ${i===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.",o=nl(t.whatsChanged.citationRate),u=n.providers.length>0?n.providers.map(hs).join(", "):`${ve(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-zinc-800/60 bg-zinc-900/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-zinc-50 sm:text-7xl",children:a}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-zinc-300 sm:text-lg",children:l}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-emerald-400":o.tone==="negative"?"text-rose-400":"text-zinc-400"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(Rs,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:i>0?`Says your name in ${s.mentionedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(Rs,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:i>0?`Cites your site as a source in ${s.citedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(Rs,{label:"AI tools tested",value:ve(s.providerCount),subtitle:u})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-semibold text-zinc-200",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-zinc-200",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-zinc-200",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-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Customer questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",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((m,p)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2 text-sm text-zinc-200",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-zinc-500",children:String(p+1).padStart(2,"0")}),e.jsxs("span",{children:['"',m,'"']})]},p))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"How often each AI tool links to your website"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Higher is better. Each bar shows the share of customer questions where the AI cited your site."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(m=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:hs(m.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500/70",style:{width:`${Math.max(m.citationRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-zinc-100",children:[m.citationRate,"% ",e.jsxs("span",{className:"font-normal text-zinc-500",children:["(",m.citedCount,"/",m.totalCount,")"]})]})]},m.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((m,p)=>e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2 text-xs text-zinc-400",children:m},p))})]})}function Rs({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-zinc-50 sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",children:n})]})}function al(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function rl(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function cl({report:t,audience:s,projectName:n}){const i=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(d=>tl(d,s)),a=Qr(t,i),l=s==="client",o=Oa(),[u,m]=r.useState(new Set),p=u.size>0?a.filter(d=>!d.targetRef||!u.has(d.targetRef)):a,f=d=>{if(!d.targetRef)return;const A=d.targetRef;m(L=>new Set(L).add(A)),o.mutate({projectName:n,body:{targetRef:A}},{onSuccess:()=>{se({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:L=>{se({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(L)}),m(D=>{const b=new Set(D);return b.delete(A),b})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ht,{eyebrow:l?"Action plan":"Agency actions",title:l?"What to do next":"Agency Action Plan",subtitle:l?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),p.length===0?e.jsx(Hs,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:p.map((d,A)=>{const L=d.evidence.length>0?d.evidence:d.why,D=d.why.length>0||d.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 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-zinc-800/80 text-sm font-semibold text-zinc-100",title:"Priority — 1 will move the needle fastest",children:A+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(ie,{tone:Ga(d),children:l?al(d.horizon):Fa(d.horizon)}),!l&&e.jsx(ie,{tone:"neutral",children:Ba(d.category)}),e.jsx(ie,{tone:"neutral",children:l?rl(d.confidence):`${qa(d.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-zinc-100",children:d.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-zinc-400",children:d.action}),e.jsx(ml,{items:L,limit:3,className:"mt-3"}),D&&e.jsxs("details",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("summary",{className:"cursor-pointer text-zinc-500 hover:text-zinc-300",children:l?"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:l?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.why.map((b,k)=>e.jsx("li",{children:b},k))})]}),d.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:l?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.evidence.map((b,k)=>e.jsx("li",{children:b},k))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-zinc-800/60 pt-3 text-xs text-zinc-300",children:[e.jsx("span",{className:"font-medium",children:l?"What success looks like:":"Win condition:"})," ",d.successMetric]}),d.targetRef&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>f(d),className:"rounded-md border border-zinc-700/60 bg-zinc-900/50 px-2.5 py-1 text-[11px] font-medium text-zinc-300 hover:border-zinc-600 hover:bg-zinc-800/70 hover:text-zinc-100",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 Dn({label:t,value:s,displayValue:n,max:i,barClass:a}){const l=i>0?Math.max(s/i*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-zinc-300",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a}`,style:{width:`${l}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-zinc-100",children:n})]})}function ll({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,i=t.indexingHealth,a=Kr(t).slice(0,5),l=s.length>0?Math.max(...s.map(m=>m.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(m=>m.impressions),1):0,u=s.length>0||n!==null||i!==null||a.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Ht,{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."}),u?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",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(m=>e.jsx(Dn,{label:m.domain+(m.isCompetitor?" (competitor)":""),value:m.count,displayValue:`${ve(m.count)}×`,max:l,barClass:"bg-zinc-400/70"},m.domain))})]}),i&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",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 ${i.indexedPct>=90?"text-emerald-400":i.indexedPct>=70?"text-amber-400":"text-rose-400"}`,children:[i.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[ve(i.indexed)," of ",ve(i.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${i.indexedPct>=90?"bg-emerald-500/70":i.indexedPct>=70?"bg-amber-500/70":"bg-rose-500/70"}`,style:{width:`${Math.max(i.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-medium text-zinc-200",children:ve(i.notIndexed)})," ",i.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ve(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ve(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(m=>e.jsx(Dn,{label:m.query,value:m.impressions,displayValue:`${ve(m.impressions)} ${m.impressions===1?"search":"searches"}`,max:o,barClass:"bg-sky-500/70"},m.query))})]}),a.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",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-zinc-300",children:a.map((m,p)=>e.jsxs("li",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-zinc-100",children:m.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-zinc-400",children:[_a(m.action),m.winnabilityClass==="ceded"&&e.jsx(ie,{tone:"caution",children:"Ceded surface"})]})]},p))})]})]}):e.jsx(Hs,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}const ol=14;function Ks(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function Vs(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Ts({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"No prior data"})]});const i=n==="%"?"%":"",a=s.deltaAbs>0?"+":"",l=Ks(s.direction),o=l==="positive"?"text-emerald-400":l==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,i," ",e.jsx("span",{className:"text-sm font-medium",children:Vs(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[a,n==="%"?s.deltaAbs.toFixed(1):s.deltaAbs,i," vs ",s.prior,i]})]})}function $n({label:t,delta:s,countLabel:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"Not enough trend data"})]});const i=s.deltaAbs>0?"+":"",a=Ks(s.direction),l=a==="positive"?"text-emerald-400":a==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${l}`,children:[ve(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:Vs(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[i,ve(s.deltaAbs)," ",n," vs prior ",ol," days"]})]})}function dl({movements:t,audience:s}){const n=t.filter(a=>a.direction!=="flat");if(n.length===0)return null;const i=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:i?"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:i?"AI tool":"Engine"}),e.jsx("th",{children:i?"Was":"Prior"}),e.jsx("th",{children:i?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(a=>{const l=a.deltaAbs>0?"+":"",o=Ks(a.direction),u=o==="positive"?"text-emerald-400":o==="negative"?"text-rose-400":"text-zinc-300";return e.jsxs("tr",{children:[e.jsx("td",{children:i?hs(a.provider):a.provider}),e.jsxs("td",{children:[a.prior,"%"]}),e.jsxs("td",{children:[a.current,"%"]}),e.jsxs("td",{className:u,children:[l,a.deltaAbs.toFixed(1),"% ",Vs(a.direction)]})]},a.provider)})})]})})]})}function In({insights:t,heading:s,emptyMessage:n,audience:i}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-zinc-500",children:n})]});const a=i==="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:[!a&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:a?"What changed":"Title"}),e.jsx("th",{children:a?"Customer question":"Query"}),e.jsx("th",{children:a?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[!a&&e.jsxs("td",{children:[e.jsx(ie,{tone:Hc[l.severity],children:Ua(l.severity)}),l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[l.title,a&&l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsx("td",{className:"text-xs text-zinc-400",children:l.query}),e.jsx("td",{className:"text-xs text-zinc-400",children:a?hs(l.provider):l.provider})]},l.id))})]})})]})}function xl({report:t,audience:s}){const n=t.whatsChanged,i=s==="client",a=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,l=e.jsx(Ht,{eyebrow:i?"Since last check":"Section 2",title:i?"What's different since last check":"What's Changed",subtitle:i?void 0:n.headline});return a?e.jsxs("section",{className:"page-section-divider",children:[l,e.jsx(Hs,{message:i?"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:[l,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Ts,{label:i?"AI links to your website":"Citation rate",delta:n.citationRate,unit:"%"}),e.jsx(Ts,{label:i?"AI mentions your name":"Mention rate",delta:n.mentionRate,unit:"%"}),e.jsx(Ts,{label:i?"Questions AI answered with you":"Cited queries",delta:n.citedQueryCount,unit:"count"}),e.jsx($n,{label:i?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:i?"visits":"clicks"}),e.jsx($n,{label:i?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:i?"visits":"sessions"})]}),e.jsx(dl,{movements:n.providerMovements,audience:s}),e.jsx(In,{insights:n.wins,heading:i?"What got better":"Wins",emptyMessage:i?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(In,{insights:n.regressions,heading:i?"What got worse":"Regressions",emptyMessage:i?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function Es({label:t,value:s,tone:n,subtitle:i}){const a=n==="positive"?"text-emerald-400":n==="caution"?"text-amber-400":n==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${a}`,children:s}),i&&e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:i})]})}function Ht({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 ml({items:t,limit:s=3,className:n}){if(t.length===0)return null;const i=t.slice(0,s),a=t.length-i.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[i.map((l,o)=>e.jsx("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-300",children:l},o)),a>0&&e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-400",children:["+",a," more"]})]})}function Hs({message:t}){return e.jsx("p",{className:"text-sm text-zinc-500 py-4 text-center",children:t})}function ul({project:t,onUpdateProject:s,onRefresh:n}){const[i,a]=r.useState(!1),[l,o]=r.useState(!1),[u,m]=r.useState(null),[p,f]=r.useState(t.displayName),[d,A]=r.useState(t.canonicalDomain),[L,D]=r.useState(t.country),[b,k]=r.useState(t.language),[$,M]=r.useState(t.ownedDomains??[]),[R,y]=r.useState(""),[j,x]=r.useState(t.aliases??[]),[T,B]=r.useState(""),[E,F]=r.useState(null),[S,I]=r.useState(!1),[G,w]=r.useState(!1),[J,ae]=r.useState(""),[fe,Q]=r.useState(""),[Y,xe]=r.useState(""),[pe,g]=r.useState(""),[O,H]=r.useState("");r.useEffect(()=>{i||(f(t.displayName),A(t.canonicalDomain),D(t.country),k(t.language),M(t.ownedDomains??[]),x(t.aliases??[]))},[t,i]);function oe(){a(!1),m(null),f(t.displayName),A(t.canonicalDomain),D(t.country),k(t.language),M(t.ownedDomains??[]),x(t.aliases??[]),y(""),B("")}function ge(){const z=R.trim();z&&($.includes(z)||M([...$,z]),y(""))}function Ie(z){M($.filter(P=>P!==z))}function Ae(){const z=T.trim();if(!z)return;const P=z.toLowerCase();j.some(qe=>qe.toLowerCase()===P)||x([...j,z]),B("")}function ne(z){x(j.filter(P=>P!==z))}async function ee(){if(!(!p.trim()||!d.trim()||!L.trim()||!b.trim())){o(!0),m(null);try{await s(t.name,{displayName:p.trim(),canonicalDomain:d.trim(),ownedDomains:$,aliases:j,country:L.trim(),language:b.trim()}),a(!1),se({title:"Project settings saved",detail:`${p.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(z){m(z instanceof Error?z.message:"Failed to save")}finally{o(!1)}}}async function be(){const z=J.trim(),P=fe.trim(),qe=Y.trim(),Me=pe.trim();if(!(!z||!P||!qe||!Me)){I(!0),F(null);try{const Pe={label:z,city:P,region:qe,country:Me};O.trim()&&(Pe.timezone=O.trim()),await Va(t.name,Pe),n(),ae(""),Q(""),xe(""),g(""),H(""),w(!1),se({title:"Location added",detail:`${z} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${z}`,dedupeMode:"drop"})}catch(Pe){F(Pe instanceof Error?Pe.message:"Failed to add location")}finally{I(!1)}}}async function Se(z){I(!0),F(null);try{await Ka(t.name,z),n(),se({title:"Location removed",detail:`${z} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${z}`,dedupeMode:"drop"})}catch(P){F(P instanceof Error?P.message:"Failed to remove location")}finally{I(!1)}}async function ke(z){I(!0),F(null);try{await Qa(t.name,z),n(),se({title:"Default location updated",detail:`${z} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(P){F(P instanceof Error?P.message:"Failed to set default location")}finally{I(!1)}}const $e=p!==t.displayName||d!==t.canonicalDomain||L!==t.country||b!==t.language||JSON.stringify($)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(j)!==JSON.stringify(t.aliases??[]),ce="w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",ye="block text-xs font-medium text-zinc-400 mb-1",We=J.trim()&&fe.trim()&&Y.trim()&&pe.trim();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:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!i&&e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),u&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[u,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>m(null),children:"×"})]}),i?e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/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:ye,children:"Display name"}),e.jsx("input",{className:ce,type:"text",value:p,onChange:z=>f(z.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Canonical domain"}),e.jsx("input",{className:ce,type:"text",value:d,onChange:z=>A(z.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Country"}),e.jsx("input",{className:ce,type:"text",value:L,onChange:z=>D(z.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Language"}),e.jsx("input",{className:ce,type:"text",value:b,onChange:z=>k(z.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:$.map(z=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[z,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>Ie(z),"aria-label":`Remove ${z}`,children:"×"})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${ce} flex-1`,type:"text",placeholder:"docs.example.com",value:R,onChange:z=>y(z.target.value),onKeyDown:z=>z.key==="Enter"&&(z.preventDefault(),ge())}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:!R.trim(),onClick:ge,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:ye,children:"Aliases"}),e.jsx("p",{className:"text-[11px] text-zinc-500 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:j.map(z=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[z,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ne(z),"aria-label":`Remove ${z}`,children:"×"})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${ce} flex-1`,type:"text",placeholder:"Facebook",value:T,onChange:z=>B(z.target.value),onKeyDown:z=>z.key==="Enter"&&(z.preventDefault(),Ae())}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:!T.trim(),onClick:Ae,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-zinc-800/60",children:[e.jsx(C,{type:"button",disabled:l||!$e||!p.trim()||!d.trim(),onClick:Z(ee),children:l?"Saving...":"Save changes"}),e.jsx(C,{type:"button",variant:"outline",disabled:l,onClick:oe,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 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(z=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:z},z))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 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(z=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:z},z))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.country})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[E&&e.jsxs("div",{className:"mb-2 rounded border border-rose-800/40 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:[E,e.jsx("button",{type:"button",className:"ml-1 text-rose-400 hover:text-rose-200",onClick:()=>F(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-zinc-600",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(z=>e.jsxs("tr",{className:"border-t border-zinc-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 ${z.label===t.defaultLocation?"border-emerald-700/60 bg-emerald-950/30 text-emerald-300":"border-zinc-700/60 bg-zinc-800/40 text-zinc-300"}`,children:[z.label,z.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:z.city}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:z.region}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:z.country}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500",children:z.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[z.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:S,onClick:()=>{ke(z.label)},className:"text-[10px] text-zinc-500 hover:text-emerald-400 transition-colors disabled:opacity-40","aria-label":`Set ${z.label} as default location`,children:"Set default"}),e.jsx("button",{type:"button",disabled:S,onClick:()=>{Se(z.label)},className:"text-[10px] text-zinc-500 hover:text-rose-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${z.label}`,children:"Remove"})]})})]},z.label))})]}):e.jsx("p",{className:"text-zinc-500 text-xs mb-2",children:"No locations configured"}),G?e.jsxs("div",{className:"mt-2 rounded border border-zinc-800 bg-zinc-900/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-zinc-500",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-zinc-500 mb-0.5",children:"Label *"}),e.jsx("input",{className:ce,type:"text",value:J,onChange:z=>ae(z.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"City *"}),e.jsx("input",{className:ce,type:"text",value:fe,onChange:z=>Q(z.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Region *"}),e.jsx("input",{className:ce,type:"text",value:Y,onChange:z=>xe(z.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Country *"}),e.jsx("input",{className:ce,type:"text",value:pe,onChange:z=>g(z.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Timezone (optional)"}),e.jsx("input",{className:ce,type:"text",value:O,onChange:z=>H(z.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(C,{type:"button",size:"sm",disabled:S||!We,onClick:Z(be),children:S?"Adding...":"Add location"}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:S,onClick:()=>{w(!1),F(null)},children:"Cancel"})]})]}):e.jsx(C,{type:"button",size:"sm",variant:"outline",onClick:()=>w(!0),children:"+ Add location"})]})]})]})})})]})}const hl=[{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"}],Pn=["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 pl({projectName:t}){const[s,n]=r.useState("loading"),[i,a]=r.useState(!1),[l,o]=r.useState("daily"),[u,m]=r.useState(6),[p,f]=r.useState(""),[d,A]=r.useState("UTC"),[L,D]=r.useState(!1),[b,k]=r.useState(""),[$,M]=r.useState(!1),[R,y]=r.useState(!1),[j,x]=r.useState(null);r.useEffect(()=>{Ha(t).then(n).catch(()=>n(null))},[t]);const T=()=>{if(s&&s!=="loading"){const S=Ya(s.preset??null,s.cronExpr);o(S.freq),m(S.hour),f(S.customCron);const I=Pn.includes(s.timezone);A(I?s.timezone:"Other"),D(!I),k(I?"":s.timezone)}else o("daily"),m(6),f(""),A("UTC"),D(!1),k("");x(null),a(!0)},B=async()=>{M(!0),x(null);try{const I={timezone:L?b.trim()||"UTC":d};l==="custom"?I.cron=p.trim():I.preset=Xa(l,u);const G=await on(t,I);n(G),a(!1),se({title:"Schedule saved",detail:Ns(G.preset??null,G.cronExpr,G.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(S){x(S instanceof Error?S.message:"Failed to save schedule")}finally{M(!1)}},E=async()=>{if(!(!s||s==="loading")){M(!0),x(null);try{const S={timezone:s.timezone,enabled:!s.enabled};s.preset?S.preset=s.preset:S.cron=s.cronExpr;const I=await on(t,S);n(I),se({title:I.enabled?"Schedule resumed":"Schedule paused",detail:Ns(I.preset??null,I.cronExpr,I.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(S){x(S instanceof Error?S.message:"Failed to update schedule")}finally{M(!1)}}},F=async()=>{y(!0),x(null);try{await Ja(t),n(null),a(!1),se({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(S){x(S instanceof Error?S.message:"Failed to remove schedule")}finally{y(!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"})]}),s!=="loading"&&!i&&e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:T,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!i&&s===null&&e.jsx(U,{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"&&!i&&s!==null&&e.jsxs(U,{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-zinc-200",children:Ns(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(ie,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:Z(E),children:s.enabled?"Pause":"Resume"}),e.jsx(C,{type:"button",variant:"ghost",size:"sm",disabled:R,onClick:Z(F),children:R?"Removing...":"Remove"})]})]}),j&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:j})]}),i&&e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/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-zinc-400",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:l,onChange:S=>o(S.target.value),children:hl.map(S=>e.jsx("option",{value:S.value,children:S.label},S.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none disabled:opacity-40",value:u,disabled:l==="twice-daily"||l==="custom",onChange:S=>m(parseInt(S.target.value)),children:Array.from({length:24},(S,I)=>e.jsx("option",{value:I,children:Wa(I)},I))})]})]}),l==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 font-mono focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:p,onChange:S=>f(S.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:L?"Other":d,onChange:S=>{S.target.value==="Other"?(D(!0),A("Other")):(D(!1),A(S.target.value))},children:[Pn.map(S=>e.jsx("option",{value:S,children:S},S)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),L&&e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:b,onChange:S=>k(S.target.value)})]}),j&&e.jsx("p",{className:"text-rose-400 text-sm",children:j}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),x(null)},children:"Cancel"}),e.jsx(C,{type:"button",size:"sm",disabled:$||l==="custom"&&!p.trim(),onClick:Z(B),children:$?"Saving...":"Save schedule"})]})]})]})}const gl=[{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 fl({projectName:t}){const[s,n]=r.useState("loading"),[i,a]=r.useState(!1),[l,o]=r.useState(""),[u,m]=r.useState(["citation.lost","citation.gained"]),[p,f]=r.useState(!1),[d,A]=r.useState(null),[L,D]=r.useState({}),[b,k]=r.useState(new Set);r.useEffect(()=>{Za(t).then(n).catch(()=>n([]))},[t]);const $=j=>{m(x=>x.includes(j)?x.filter(T=>T!==j):[...x,j])},M=async()=>{if(!(!l.trim()||u.length===0)){f(!0),A(null);try{const j=await er(t,{channel:"webhook",url:l.trim(),events:u});n(x=>x==="loading"?[j]:[...x,j]),o(""),m(["citation.lost","citation.gained"]),a(!1),se({title:"Webhook added",detail:`Notifications will be sent to ${j.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(j){A(j instanceof Error?j.message:"Failed to add webhook")}finally{f(!1)}}},R=async j=>{if(!b.has(j)){k(x=>new Set(x).add(j));try{await sr(t,j),n(x=>x==="loading"?x:x.filter(T=>T.id!==j)),se({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${j}`,dedupeMode:"drop"})}catch(x){A(x instanceof Error?x.message:"Failed to remove webhook")}finally{k(x=>{const T=new Set(x);return T.delete(j),T})}}},y=async j=>{D(x=>({...x,[j]:{state:"testing"}}));try{const x=await tr(t,j);D(T=>({...T,[j]:{state:x.ok?"ok":"fail",status:x.status}})),x.ok&&se({title:"Test notification sent",detail:`Webhook returned status ${x.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${j}`,dedupeMode:"replace"})}catch{D(x=>({...x,[j]:{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"})]}),s!=="loading"&&e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!i),A(null)},children:i?"Cancel":"+ Add webhook"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/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-zinc-400",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:j=>o(j.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:gl.map(j=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-zinc-600 bg-zinc-800",checked:u.includes(j.value),onChange:()=>$(j.value)}),e.jsx("span",{className:"text-sm text-zinc-300",children:j.label})]},j.value))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),A(null)},children:"Cancel"}),e.jsx(C,{type:"button",size:"sm",disabled:p||!l.trim()||u.length===0,onClick:Z(M),children:p?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!i&&e.jsx(U,{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(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-zinc-300 break-all",title:j.urlHost,children:j.urlDisplay??j.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:j.events.map(x=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-zinc-700 bg-zinc-800/60 px-2 py-0.5 text-[10px] font-medium text-zinc-400 uppercase tracking-wide",children:x.replace("."," ")},x))})}),e.jsx("td",{children:e.jsx(ie,{tone:j.enabled?"positive":"neutral",children:j.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[L[j.id]&&(()=>{const x=L[j.id],T=x.state==="testing"?"Sending…":x.state==="ok"?`Delivered${x.status?` (${x.status})`:""}`:`Failed${x.status?` (${x.status})`:""}`;return e.jsx(ie,{tone:x.state==="ok"?"positive":x.state==="fail"?"negative":"neutral",children:T})})(),e.jsx(C,{variant:"ghost",size:"sm",type:"button",disabled:L[j.id]?.state==="testing",onClick:()=>{y(j.id)},children:"Test"}),e.jsx(C,{variant:"ghost",size:"sm",type:"button",disabled:b.has(j.id),onClick:()=>{R(j.id)},children:b.has(j.id)?"Removing…":"Remove"})]})})]},j.id))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:d})]})]})}function At(t,s){return t.invalidateQueries({predicate:n=>{const i=n.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith(s)}})}function jl({projectName:t,refreshNonce:s}){const n=mt(),[i,a]=r.useState(null),[l,o]=r.useState([]),[u,m]=r.useState(null),[p,f]=r.useState([]),[d,A]=r.useState([]),[L,D]=r.useState(null),[b,k]=r.useState(""),[$,M]=r.useState(""),[R,y]=r.useState(""),[j,x]=r.useState(!0),[T,B]=r.useState(!1),[E,F]=r.useState(null),[S,I]=r.useState("performance");r.useEffect(()=>{G()},[t,s]);async function G(){x(!0),F(null);try{const g=await n.fetchQuery({...Un({client:_,path:{name:t}}),staleTime:Ce});if(a(g),g.connected){const[O,H,oe,ge]=await Promise.all([n.fetchQuery({...Qn({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>null),n.fetchQuery({...Kn({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>[]),n.fetchQuery({...Nr({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>[]),g.siteUrl?Promise.resolve([]):n.fetchQuery({...wr({client:_,path:{name:t}}),staleTime:Ce}).then(Ie=>Ie.sites).catch(()=>[])]);m(O),f(H),A(oe),o(ge)}else m(null),f([]),A([]),o([])}catch(g){F(g instanceof Error?g.message:"Failed to load Bing data")}finally{x(!1)}}async function w(){if($.trim()){F(null);try{const g=await zr(t,$.trim());await At(n,"getApiV1ProjectsByNameBing"),M(""),g.availableSites.length>0&&o(g.availableSites),await G()}catch(g){F(g instanceof Error?g.message:"Failed to connect")}}}async function J(){try{await Sr(t),await At(n,"getApiV1ProjectsByNameBing"),a(null),o([]),m(null),f([]),A([]),D(null),y(""),F(null)}catch(g){F(g instanceof Error?g.message:"Failed to disconnect")}}async function ae(){if(R)try{await kr(t,R),await At(n,"getApiV1ProjectsByNameBing"),await G()}catch(g){F(g instanceof Error?g.message:"Failed to set site")}}async function fe(){if(b.trim())try{const g=await Vn(t,b.trim());await At(n,"getApiV1ProjectsByNameBing"),D(g),f(O=>[g,...O])}catch(g){F(g instanceof Error?g.message:"Inspection failed")}}async function Q(g){B(!0),F(null);try{const O=await un(t,{urls:[g]}),{succeeded:H,failed:oe,total:ge}=O.summary;se({title:"Bing submission requested",detail:oe===0?`${H} URL submitted to Bing.`:`${H}/${ge} submitted successfully, ${oe} failed.`,tone:oe===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${g}`,dedupeMode:"replace"})}catch(O){const H=O instanceof Error?O.message:"Submission failed";F(H),se({title:"Bing submission failed",detail:H,tone:"negative",dedupeKey:`bing:indexing:${t}:${g}`,dedupeMode:"replace"})}finally{B(!1)}}async function Y(){B(!0),F(null),se({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const g=await un(t,{allUnindexed:!0}),{succeeded:O,failed:H,total:oe}=g.summary;se({title:"Bing submissions requested",detail:H===0?`${O}/${oe} URL${oe!==1?"s":""} submitted to Bing.`:`${O}/${oe} submitted successfully, ${H} failed.`,tone:H===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(g){const O=g instanceof Error?g.message:"Batch submission failed";F(O),se({title:"Bing submissions failed",detail:O,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{B(!1)}}if(j)return e.jsx(U,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-zinc-400",children:"Loading Bing data..."})});if(!i?.connected)return e.jsxs(U,{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(ie,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-zinc-300",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-zinc-500",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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:$,onChange:g=>M(g.target.value),onKeyDown:g=>{g.key==="Enter"&&w()}}),e.jsx(C,{size:"sm",disabled:!$.trim(),onClick:Z(w),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-300 underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:E})]});if(!i.siteUrl)return e.jsxs(U,{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(ie,{tone:"positive",children:"Connected"}),e.jsx(C,{size:"sm",variant:"ghost",onClick:Z(J),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 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-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",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-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.domain})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?Je(i.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Select site"}),l.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-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:R,onChange:g=>y(g.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(g=>e.jsxs("option",{value:g.url,children:[g.url,g.verified?" (verified)":""]},g.url))]}),e.jsx(C,{size:"sm",disabled:!R,onClick:Z(ae),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-zinc-500",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:E})]});const xe=[{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"}],pe=xe.find(g=>g.key===S)??xe[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(U,{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(ie,{tone:"positive",children:"Connected"}),e.jsx(C,{size:"sm",variant:"ghost",onClick:Z(J),children:"Disconnect"})]})]}),E&&e.jsx("p",{className:"mb-3 text-xs text-rose-400",children:E}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 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-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Canonry stores Bing connections per canonical domain. This project is currently mapped to ",e.jsx("code",{children:i.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?Je(i.updatedAt):"—"})]})]})]})]}),e.jsxs(U,{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:pe.eyebrow}),e.jsx("h3",{children:pe.title})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:u?.lastInspectedAt?`Last inspected ${Je(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-zinc-800",children:xe.map(g=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${S===g.key?"border-zinc-200 text-zinc-200":"border-transparent text-zinc-500 hover:text-zinc-300"}`,onClick:()=>I(g.key),children:g.label},g.key))}),S==="coverage"&&u&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(is,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(is,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(is,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(is,{label:"Coverage",value:`${u.summary.percentage}%`,tone:"neutral"})]}),u.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-zinc-400",children:["Not Indexed (",u.notIndexed.length,")"]}),e.jsx(C,{size:"sm",variant:"ghost",disabled:T,onClick:Z(Y),children:T?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"HTTP"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:u.notIndexed.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:T,onClick:()=>{Q(g.url)},children:"Submit"})})]},g.id))})]})})]}),(u.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-zinc-400",children:["Unknown — not yet confirmed (",(u.unknown??[]).length,")"]}),e.jsx(C,{size:"sm",variant:"ghost",disabled:T,onClick:Z(Y),children:T?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(u.unknown??[]).map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.lastCrawledDate?Je(g.lastCrawledDate):"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:T,onClick:()=>{Q(g.url)},children:"Submit"})})]},g.id))})]})})]}),u.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-zinc-400",children:["Indexed (",u.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:u.indexed.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.lastCrawledDate?Je(g.lastCrawledDate):"—"})]},g.id))})]})})]})]}),S==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"No coverage data yet. Inspect URLs to build coverage data."}),S==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"URL to inspect",value:b,onChange:g=>k(g.target.value),onKeyDown:g=>{g.key==="Enter"&&fe()}}),e.jsx(C,{size:"sm",disabled:!b.trim(),onClick:Z(fe),children:"Inspect"})]}),L&&e.jsxs("div",{className:"rounded border border-zinc-800 bg-zinc-900/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-zinc-200",children:L.url}),e.jsxs("div",{className:"text-zinc-400",children:["In Index: ",e.jsx("span",{className:L.inIndex?"text-emerald-400":"text-rose-400",children:L.inIndex?"Yes":"No"})," · ","HTTP: ",L.httpCode??"—"," · ","Crawled: ",L.lastCrawledDate??"—"]})]}),p.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:p.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ie,{tone:g.inIndex?"positive":"negative",children:g.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:Je(g.inspectedAt)})]},g.id))})]})})]}),S==="performance"&&e.jsx("div",{className:"mt-4",children:d.length===0?e.jsx("p",{className:"text-xs text-zinc-500",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:ns[ft.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:ns[ft.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:ns[ft.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:ns[ft.Position]})]})}),e.jsx("tbody",{children:d.map((g,O)=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-200",children:g.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:g.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:[(Number.isFinite(g.ctr)?g.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:g.averagePosition.toFixed(1)})]},O))})]})})})]})]})}function bl({projectName:t}){const s=mt(),[n,i]=r.useState("google"),[a,l]=r.useState(!0),[o,u]=r.useState("idle"),[m,p]=r.useState(null),f=r.useRef(null),[d,A]=r.useState(!1),[L,D]=r.useState(null),[b,k]=r.useState(null),[$,M]=r.useState(!1),[R,y]=r.useState(null),[j,x]=r.useState(null),[T,B]=r.useState(0);async function E(g=!1){g||l(!0),p(null);try{const[O,H,oe]=await Promise.all([s.fetchQuery(br({client:_})).catch(()=>null),s.fetchQuery({...Bs({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>[]),s.fetchQuery({...Un({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>null)]),ge=H.find(ne=>ne.connectionType==="gsc")??null;A(!!O?.google?.configured),M(!!O?.bing?.configured),D(ge),y(oe);const[Ie,Ae]=await Promise.all([ge?s.fetchQuery({...Mn({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>null):Promise.resolve(null),oe?.connected?s.fetchQuery({...Qn({client:_,path:{name:t}}),staleTime:Ce}).catch(()=>null):Promise.resolve(null)]);k(Ie),x(Ae)}catch(O){p(O instanceof Error?O.message:"Failed to load search console overview")}finally{l(!1)}}async function F(){if(o!=="idle")return;f.current?.abort();const g=new AbortController;f.current=g;const O=g.signal;u("syncing"),p(null);const H=[];try{async function oe(){if(!L)return;const ne=await yr(t);if(!ne?.id)return;const ee=2e3,Se=Date.now()+12e4;for(;Date.now()<Se;){if(O.aborted||(await new Promise($e=>setTimeout($e,ee)),O.aborted))return;const ke=await Fn(ne.id).catch(()=>null);if(!ke)break;if(["completed","failed","cancelled"].includes(ke.status)){ke.status!=="completed"&&H.push(`Google sync ${ke.status}`);break}}}const ge=10;async function Ie(){if(!R?.connected)return;const ne=await s.fetchQuery({...Kn({client:_,path:{name:t}}),staleTime:0}).catch(()=>[]),ee=[...new Set(ne.map(be=>be.url))];if(ee.length===0){await vr(t).catch(()=>null);return}for(let be=0;be<ee.length;be+=ge){if(O.aborted)return;const Se=ee.slice(be,be+ge),$e=(await Promise.allSettled(Se.map(ce=>Vn(t,ce)))).filter(ce=>ce.status==="rejected").length;$e>0&&H.push(`${$e} Bing inspection(s) failed`)}}const Ae=await Promise.allSettled([oe(),Ie()]);for(const ne of Ae)ne.status==="rejected"&&H.push(ne.reason instanceof Error?ne.reason.message:"Sync failed");if(O.aborted)return;u("reloading"),await Promise.all([At(s,"getApiV1ProjectsByNameGoogleGsc"),At(s,"getApiV1ProjectsByNameBing")]),await E(!0),B(ne=>ne+1),H.length>0&&p(`Partial refresh: ${H.join("; ")}`)}catch(oe){O.aborted||p(oe instanceof Error?oe.message:"Refresh failed")}finally{O.aborted||u("idle")}}r.useEffect(()=>(E(),()=>{f.current?.abort()}),[t]);const S=L?"positive":d?"caution":"negative",I=L?"Connected":d?"Ready to connect":"Needs setup",G=b?`${b.summary.percentage}% indexed`:L?"Awaiting coverage":"No coverage data",w=b?`${b.summary.notIndexed} not indexed${b.summary.deindexed>0?` · ${b.summary.deindexed} deindexed`:""}`:L?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",J=b?.lastSyncedAt??b?.lastInspectedAt??L?.updatedAt??null,ae=R?.connected?"positive":$?"caution":"negative",fe=R?.connected?"Connected":$?"Ready to connect":"Needs setup",Q=j?`${j.summary.percentage}% indexed`:R?.connected?"Awaiting coverage":"No coverage data",Y=j?j.summary.notIndexed+(j.summary.unknown??0):0,xe=j?`${Y} not in index`:R?.connected?"Inspect URLs to populate coverage":$?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",pe=j?.lastInspectedAt??R?.updatedAt??null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(U,{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-zinc-500",children:"Scan both engines at a glance, then open the Google or Bing workspace when you need to inspect coverage or take action."})]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:a||o!=="idle",onClick:()=>{F()},children:a?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"})]}),m&&e.jsx("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:m}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(jn,{eyebrow:"Google",title:"Google Search Console",status:a?"Loading…":I,tone:a?"neutral":S,targetLabel:"Selected property",targetValue:L?.propertyId??"No property selected",coverageValue:a?"Loading…":G,note:a?"Loading overview…":w,updatedAt:J,active:n==="google",onClick:()=>i("google")}),e.jsx(jn,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:a?"Loading…":fe,tone:a?"neutral":ae,targetLabel:"Selected site",targetValue:R?.siteUrl??"No site selected",coverageValue:a?"Loading…":Q,note:a?"Loading overview…":xe,updatedAt:pe,active:n==="bing",onClick:()=>i("bing")})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([g,O])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===g,className:`project-subnav-link ${n===g?"project-subnav-link-active":""}`,onClick:()=>i(g),children:O},g))}),n==="google"&&e.jsx(pc,{projectName:t,refreshNonce:T}),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(jl,{projectName:t,refreshNonce:T})]})]})}function yl({summary:t,onJumpToEvidence:s}){if(!t.hasPreviousRun)return e.jsxs("section",{className:"movement-banner",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),e.jsx("span",{className:"text-zinc-500",children:"First run — no comparison yet"})]});const n=t.gained,i=t.lost,a=n===0&&i===0?"· no changes":n>i?"· improving":i>n?"· declining":"";return e.jsxs("section",{className:"movement-banner",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),n>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-emerald-400 font-medium",onClick:s,title:"Jump to the queries that gained citations",children:["+",n," gained"]}):e.jsx("span",{className:"text-zinc-500",children:"+0 gained"}),e.jsx("span",{className:"text-zinc-700 mx-1",children:"·"}),i>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-rose-400 font-medium",onClick:s,title:"Jump to the queries that lost citations",children:["−",i," lost"]}):e.jsx("span",{className:"text-zinc-500",children:"−0 lost"}),e.jsx("span",{className:"text-zinc-400 ml-2",children:a})]}),t.gainedQueries?.length||t.lostQueries?.length?e.jsxs("div",{className:"movement-banner-detail",children:[t.gainedQueries&&t.gainedQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-emerald-500/90",children:"Gained:"})," ",e.jsx("span",{className:"text-zinc-300",children:Rn(t.gainedQueries)})]}),t.lostQueries&&t.lostQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-rose-500/90",children:"Lost:"})," ",e.jsx("span",{className:"text-zinc-300",children:Rn(t.lostQueries)})]})]}):null]})}function Rn(t,s=4){return t.length<=s?t.map(i=>`"${i}"`).join(", "):`${t.slice(0,s).map(i=>`"${i}"`).join(", ")}, and ${t.length-s} more`}function vl({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const i=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(i===0)return null;const a=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,u)=>u.mentions-o.mentions),l=a[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:a.map(o=>{const u=o.mentions/i*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-zinc-100 font-medium":"text-zinc-400"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-emerald-500/70":"bg-zinc-500/60"}`,style:{width:`${Math.max(o.mentions/l*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[u.toFixed(1),"%"]})]},o.label)})})]})}const Nl={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 wl({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:i}=Tn(),[a,l]=r.useState(null),o=s.rows.length>0;if(t.length===0&&!o)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No outstanding opportunities. Trigger a sweep to surface fresh signals."});const u=["write","investigate","monitor"],m=new Map;for(const p of t){const f=m.get(p.actionGroup)??[];f.push(p),m.set(p.actionGroup,f)}return e.jsxs("div",{className:"opportunities-grid",children:[u.map(p=>{const f=m.get(p);if(!f||f.length===0)return null;const d=Nl[p];return e.jsxs("div",{className:`opportunity-card opportunity-card-${p}`,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:f.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:d.subtitle}),e.jsx("div",{className:"opportunity-card-list",children:f.map(A=>{const L=a===A.id,D=A.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${A.tone} ${D?"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400":""}`,onClick:D?()=>l(L?null:A.id):void 0,onKeyDown:D?b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l(L?null:A.id))}:void 0,tabIndex:D?0:void 0,role:D?"button":void 0,"aria-expanded":D?L:void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[D&&e.jsx(gs,{size:12,className:`mt-1 shrink-0 text-zinc-500 transition-transform duration-150 ${L?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug",children:A.title}),A.detail&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:A.detail})]})]})}),L&&e.jsx("div",{className:"opportunity-item-detail",children:A.affectedPhrases.map((b,k)=>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(Os,{state:b.citationState}),e.jsx("span",{className:"text-xs text-zinc-300 truncate",children:b.query}),b.provider&&e.jsx($t,{provider:b.provider})]}),b.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 whitespace-nowrap",onClick:$=>{$.stopPropagation(),i(b.evidenceId)},children:"View →"})]},b.evidenceId||`${A.id}-${k}`))})]},A.id)})})]},p)}),o&&e.jsx(zl,{suggestedQueries:s,projectName:n})]})}function zl({suggestedQueries:t,projectName:s}){const n=jr(),[i,a]=r.useState(new Set),l=f=>{a(d=>new Set(d).add(f)),n.mutate({projectName:s,queries:[f]},{onSuccess:()=>{se({tone:"positive",title:`Tracking "${f}"`}),a(d=>{const A=new Set(d);return A.delete(f),A})},onError:d=>{se({tone:"negative",title:`Couldn't add "${f}"`,detail:String(d)}),a(A=>{const L=new Set(A);return L.delete(f),L})}})},{rows:o,totalCandidates:u,skippedAlreadyTracked:m}=t,p=m>0?`GSC queries you're getting impressions for · ${m} 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:u>o.length?`${o.length} of ${u}`:o.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:p}),e.jsx("div",{className:"opportunity-card-list",children:o.map(f=>{const d=i.has(f.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-zinc-100 leading-snug truncate",title:f.query,children:f.query}),e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:f.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:d,onClick:()=>l(f.query),children:d?"Adding…":"+ Track"})]},f.query)})})]})}function El(t){const{projectId:s}=vi({from:"/projects/$projectId"}),i=nr()?.dashboard.projects.find(d=>d.project.id===s)?.project.name??null,a=De({...ir({client:_}),enabled:!i}),l=i??a.data?.find(d=>d.id===s)?.name??null,{commandCenter:o,isLoading:u,refetch:m}=ar(l),p=!i&&a.isLoading||u;return!l&&!i&&a.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(U,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project with ID "',s,'".']}),e.jsx(C,{asChild:!0,children:e.jsx(dt,{to:"/",children:"Return to overview"})})]})}):!o||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(d=>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"})]},d))}),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(d=>e.jsx("div",{className:"skeleton-text-sm w-full"},d))})]})]}):e.jsx(kl,{model:o,refetch:m,...t})}function Sl({items:t,activeTab:s}){const[n,i]=r.useState(!1),a=r.useRef(null);if(r.useEffect(()=>{if(!n)return;const o=m=>{a.current&&!a.current.contains(m.target)&&i(!1)},u=m=>{m.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const l=t.some(o=>o.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:a,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${l?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>i(o=>!o),children:["More",e.jsx(_n,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(dt,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>i(!1),children:o.label},o.key))}):null]})}function kl({tab:t,model:s,refetch:n}){const i=Ni(),a=mt(),[l,o]=r.useState(!1),[u,m]=r.useState(!1),[p,f]=r.useState(!1),[d,A]=r.useState(""),[L,D]=r.useState(!1),[b,k]=r.useState(null),[$,M]=r.useState(!1),[R,y]=r.useState(""),[j,x]=r.useState(!1),[T,B]=r.useState(!1),[E,F]=r.useState(""),[S,I]=r.useState(!1),[G,w]=r.useState(!1),[J,ae]=r.useState(""),[fe,Q]=r.useState(!1),[Y,xe]=r.useState(void 0),[pe,g]=r.useState(!1),[O,H]=r.useState(null),[oe,ge]=r.useState(null),[Ie,Ae]=r.useState(!1),ne=s?.visibilityEvidence??[],ee=s?.project.name??"",be=s?.project.displayName||s?.project.name||ee,Se=rr(),ke=(s?.recentRuns??[]).some(h=>h.kind===ds["answer-visibility"]&&(h.status===dn.running||h.status===dn.queued)),$e=r.useMemo(()=>(s?.project.locations??[]).map(h=>h.label),[s?.project.locations]),ce=r.useMemo(()=>new Set(ne.map(h=>h.location??"")),[ne]),ye=ce.has(""),We=r.useMemo(()=>[...new Set(ne.map(h=>h.query))].sort((h,K)=>h.localeCompare(K)),[ne]),z=r.useMemo(()=>{const h=[...ce].filter(Boolean);return h.length>1?h:$e},[ce,$e]);r.useEffect(()=>{if(Y===void 0||Y===""||!ee){ge(null),Ae(!1);return}Ae(!0),cr(ee,Y).then(h=>{ge(h),Ae(!1)}).catch(()=>{ge(null),Ae(!1)})},[Y,ee]);const P=r.useMemo(()=>{if(!oe)return null;const h=new Map;for(const K of oe){for(const[le,Re]of Object.entries(K.providerRuns??{}))h.set(`${K.query}::${le}`,Re.map(te=>({runId:te.runId,citationState:te.citationState,createdAt:te.createdAt,answerMentioned:te.answerMentioned,visibilityState:te.visibilityState,visibilityTransition:te.visibilityTransition,mentionState:te.mentionState,mentionTransition:te.mentionTransition})));(!K.providerRuns||Object.keys(K.providerRuns).length===0)&&h.set(`${K.query}::`,K.runs.map(le=>({runId:le.runId,citationState:le.citationState,createdAt:le.createdAt,answerMentioned:le.answerMentioned,visibilityState:le.visibilityState,visibilityTransition:le.visibilityTransition,mentionState:le.mentionState,mentionTransition:le.mentionTransition})))}return h},[oe]),qe=r.useMemo(()=>{let h=Y!==void 0?ne.filter(K=>Y===""?!K.location:K.location===Y):ne;if(O){const K=O.toLowerCase();h=h.filter(le=>le.competitorDomains.some(Re=>Re.toLowerCase()===K))}return P?h.map(K=>{const le=P.get(`${K.query}::${K.provider}`)??P.get(`${K.query}::`);return le?{...K,runHistory:le}:K}):h},[ne,Y,O,P]);async function Me(){try{await Se.mutateAsync({projectName:ee,projectLabel:be,sourceAction:"project-run"}),n()}catch{}}async function Pe(){m(!0);try{await dr(ee),se({title:"Project deleted",detail:`${be} was removed.`,tone:"positive",dedupeKey:`project:delete:${ee}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(h){console.error("Failed to delete project:",h)}finally{m(!1)}}async function ut(){try{const h=await xr(ee),K=typeof h=="string"?h:JSON.stringify(h,null,2),le=new Blob([K],{type:"text/yaml"}),Re=URL.createObjectURL(le),te=document.createElement("a");te.href=Re,te.download=`${ee}.yaml`,te.click()}catch(h){se({title:"Export failed",detail:h instanceof Error?h.message:"Could not export project YAML.",tone:"negative"})}}async function bt(){const h=d.split(`
5
- `).map(K=>K.trim()).filter(Boolean);if(h.length!==0){D(!0);try{await gr(ee,h),n(),A("")}finally{D(!1)}}}async function nt(h){k(h);try{await pr(ee,[h]),n()}catch(K){se({title:"Could not remove query",detail:K instanceof Error?K.message:`Failed to remove "${h}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{k(null)}}async function ht(){const h=R.trim();if(h){x(!0);try{const le=(await mr(ee)).map(te=>te.domain),Re=[...new Set([...le,h])];await ur(ee,Re),n(),y(""),M(!1)}finally{x(!1)}}}async function _e(h){try{await hr(ee,[h]),n()}catch(K){se({title:"Could not remove competitor",detail:K instanceof Error?K.message:`Failed to remove ${h}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function Ze(){const h=E.trim();if(h){I(!0);try{const K=s?.project.ownedDomains??[];await xn(ee,[...K,h]),n(),F(""),B(!1)}finally{I(!1)}}}async function it(h){I(!0);try{const K=s?.project.ownedDomains??[];await xn(ee,K.filter(le=>le!==h)),n()}finally{I(!1)}}async function Xe(){const h=J.trim();if(h){Q(!0);try{const K=s?.project.aliases??[],le=h.toLowerCase();if(K.some(Re=>Re.toLowerCase()===le)){ae(""),w(!1);return}await mn(ee,[...K,h]),n(),ae(""),w(!1)}finally{Q(!1)}}}async function yt(h){Q(!0);try{const K=s?.project.aliases??[];await mn(ee,K.filter(le=>le!==h)),n()}finally{Q(!1)}}async function Ft(h,K){await fr(h,K),await a.invalidateQueries({queryKey:Bn({client:_})})}const we=h=>!Number.isNaN(Number.parseInt(h,10)),Oe=`/projects/${s.project.id}`,Fe=[{key:"overview",label:"AI Visibility",href:Oe},{key:"search-console",label:"Search Engines",href:`${Oe}/search-console`},{key:"activity",label:"Activity",href:`${Oe}/activity`},{key:"technical-aeo",label:"Technical AEO",href:`${Oe}/technical-aeo`},{key:"local",label:"Local Presence",href:`${Oe}/local`},{key:"discovery",label:"Query Discovery",href:`${Oe}/discovery`},{key:"backlinks",label:"Backlinks",href:`${Oe}/backlinks`}],Gt=[{key:"report",label:"Report",href:`${Oe}/report`}],Ue={key:"settings",label:"Settings",href:`${Oe}/settings`};return e.jsxs("div",{className:"page-container",children:[l?e.jsxs(U,{className:"surface-card p-6 mb-6 border-rose-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-rose-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-zinc-400 mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-zinc-200",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(C,{type:"button",variant:"destructive",disabled:u,onClick:Z(Pe),children:u?"Deleting...":"Yes, delete project"}),e.jsx(C,{type:"button",variant:"outline",disabled:u,onClick:()=>o(!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,(s.project.ownedDomains??[]).length===0&&!T&&e.jsx("button",{type:"button",className:"ml-2 rounded px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/60 transition-colors",onClick:()=>B(!0),children:"+ add domain"})," "," · ",s.contextLabel]}),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(h=>e.jsx("span",{className:"tag",children:h},h))]}),((s.project.ownedDomains??[]).length>0||T)&&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-zinc-500 mr-1",children:"Also tracking"}),(s.project.ownedDomains??[]).map(h=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[h,e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-zinc-500 hover:bg-zinc-700/40 hover:text-zinc-200 transition-colors",disabled:S,onClick:()=>{it(h)},"aria-label":`Remove ${h}`,children:"×"})]},h)),T?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-1.5 py-0.5 text-xs text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none w-40",type:"text",placeholder:"docs.example.com",value:E,onChange:h=>F(h.target.value),onKeyDown:h=>{h.key==="Enter"&&Ze()},autoFocus:!0}),e.jsx(C,{type:"button",size:"sm",disabled:!E.trim()||S,onClick:Z(Ze),children:S?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{B(!1),F("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-zinc-700 px-2 py-0.5 text-[10px] uppercase tracking-wide text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors",onClick:()=>B(!0),children:"+ domain"})]}),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-zinc-500 mr-1",children:["Also known as",e.jsx(Ne,{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(h=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[h,e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-zinc-500 hover:bg-zinc-700/40 hover:text-zinc-200 transition-colors",disabled:fe,onClick:()=>{yt(h)},"aria-label":`Remove ${h}`,children:"×"})]},h)),G?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-1.5 py-0.5 text-xs text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none w-40",type:"text",placeholder:"LlamaParse",value:J,onChange:h=>ae(h.target.value),onKeyDown:h=>{h.key==="Enter"&&Xe()},autoFocus:!0}),e.jsx(C,{type:"button",size:"sm",disabled:!J.trim()||fe,onClick:Z(Xe),children:fe?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{w(!1),ae("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-zinc-700 px-2 py-0.5 text-[10px] uppercase tracking-wide text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors",onClick:()=>w(!0),children:"+ alias"})]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-zinc-500",children:s.dateRangeLabel}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"icon",onClick:Z(ut),"aria-label":"Export project as YAML",children:e.jsx(Qs,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(C,{type:"button",variant:"outline",size:"icon",onClick:()=>o(!0),"aria-label":"Delete project",children:e.jsx(Rr,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(C,{type:"button",disabled:Se.isPending||ke,onClick:Z(Me),children:Se.isPending?"Starting…":ke?"Sweep running…":"Run now"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[Fe.map(h=>e.jsx(dt,{to:h.href,className:`project-subnav-link ${h.key===t?"project-subnav-link-active":""}`,"aria-current":h.key===t?"page":void 0,children:h.label},h.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(Sl,{items:Gt,activeTab:t}),e.jsx(dt,{to:Ue.href,className:`project-subnav-link ${t==="settings"?"project-subnav-link-active":""}`,"aria-current":t==="settings"?"page":void 0,children:Ue.label},Ue.key)]})]}),t==="overview"?e.jsxs(e.Fragment,{children:[e.jsx(Gc,{projectName:s.project.name}),e.jsx(yl,{summary:s.movementSummary,onJumpToEvidence:()=>document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})}),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:"Competitive landscape"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>M(!$),children:$?"Cancel":"+ Add competitor"})]})]}),e.jsxs("section",{className:"metric-grid",children:[e.jsx("h2",{className:"sr-only",children:"Mention share and competitive gaps"}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Mention share",e.jsx(Ne,{text:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the % that were you. Head-to-head AI prominence, not market share. Measured from your most recent run."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.mentionShareSummary.value}),we(s.mentionShareSummary.value)?e.jsx("span",{className:"text-zinc-600",children:"%"}):null]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.mentionShareSummary.tone}`,style:{width:s.mentionShareSummary.progress!==void 0?`${Math.min(Math.max(s.mentionShareSummary.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.mentionShareSummary.delta})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Mention Gaps",e.jsx(Ne,{text:"Queries where a competitor was mentioned in the answer but your brand wasn't."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-zinc-600",children:[" / ",s.queryCounts.total]})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.mentionGaps.tone}`,style:{width:s.mentionGaps.progress!==void 0?`${Math.min(Math.max(s.mentionGaps.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.mentionGaps.delta})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Citation Gaps",e.jsx(Ne,{text:"Queries where a competitor was cited as a source but you weren't."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.gapQueries.value}),e.jsxs("span",{className:"text-zinc-600",children:[" / ",s.queryCounts.total]})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.gapQueries.tone}`,style:{width:s.gapQueries.progress!==void 0?`${Math.min(Math.max(s.gapQueries.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.gapQueries.delta})]})]}),e.jsx(vl,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name}),$&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"competitor.com",value:R,onChange:h=>y(h.target.value),onKeyDown:h=>{h.key==="Enter"&&ht()}}),e.jsx(C,{type:"button",size:"sm",disabled:!R.trim()||j,onClick:Z(ht),children:j?"Adding...":"Add"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(tc,{competitors:s.competitors,onSelectCompetitor:h=>{H(h),document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})},onRemoveCompetitor:h=>{_e(h)},activeFilter:O})})]}),e.jsxs("section",{id:"evidence-section",className:"page-section-divider scroll-mt-24",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Answer evidence"}),e.jsx("h2",{children:"What the LLMs said"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[We.length," queries tracked"]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>f(!p),children:p?"Done":"Manage queries"})]})]}),p&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",children:[We.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-zinc-800/60 overflow-y-auto rounded border border-zinc-800/60",children:We.map(h=>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-zinc-200",title:h,children:h}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-500 transition-colors hover:text-rose-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-rose-500 disabled:opacity-50","aria-label":`Remove query ${h}`,title:`Stop tracking "${h}"`,disabled:b!==null,onClick:()=>{nt(h)},children:b===h?"Removing…":"Remove"})]},h))}):e.jsx("p",{className:"mb-3 text-xs text-zinc-500",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:d,onChange:h=>A(h.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-zinc-500",children:[d.split(`
6
- `).filter(h=>h.trim()).length," to add"]}),e.jsx(C,{type:"button",size:"sm",disabled:!d.trim()||L,onClick:Z(bt),children:L?"Adding...":"Add queries"})]})]}),s.project.locations&&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 ${Y===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":Y===void 0,onClick:()=>{xe(void 0)},children:"All locations"}),s.project.locations.map(h=>e.jsx("button",{className:`filter-chip ${Y===h.label?"filter-chip-active":""}`,type:"button","aria-pressed":Y===h.label,onClick:()=>{xe(h.label),g(!1)},children:h.label},h.label)),ye&&e.jsx("button",{className:`filter-chip ${Y===""?"filter-chip-active":""}`,type:"button","aria-pressed":Y==="",onClick:()=>{xe(""),g(!1)},children:"No location"}),z.length>1&&Y===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${pe?"filter-chip-active":""}`,type:"button","aria-pressed":pe,onClick:()=>g(h=>!h),title:"Side-by-side location comparison",children:"Compare"})]}),O&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-rose-900/40 bg-rose-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-rose-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-zinc-200",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:O})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-zinc-400 hover:text-zinc-200",onClick:()=>H(null),children:"Clear filter ×"})]}),e.jsx(Jr,{evidence:qe,compareLocations:pe})]}),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:"Opportunities"}),e.jsx("h2",{children:"What to act on next"})]})}),e.jsx(wl,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:ee})]}),e.jsx(wc,{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:["Visibility by model ",e.jsx(Ne,{text:"Per-model citation rate today. Same query set, different LLMs — gaps between providers point at content / source issues, not the metric. The trend over time is in the chart above (the By engine view)."})]})]})}),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:"Score"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(h=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx($t,{provider:h.provider}),h.model&&e.jsx("span",{className:"text-[11px] font-mono text-zinc-500",children:h.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:`font-semibold ${lr[or(h.score)]}`,children:[h.score,"%"]})}),e.jsxs("td",{className:"text-zinc-500",children:[h.cited," of ",h.total]})]},`${h.provider}::${h.model??"unknown"}`))})]})})]}),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:"Run timeline"}),e.jsx("h2",{children:"Recent execution history"})]})}),e.jsx("div",{className:"run-list",children:s.recentRuns.map(h=>e.jsx(Cr,{run:h},h.id))})]})]}):t==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(ul,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:Ft,onRefresh:()=>{n()}}),e.jsx(pl,{projectName:s.project.name}),e.jsx(fl,{projectName:s.project.name})]}):t==="report"?e.jsx(Jc,{projectName:s.project.name}):t==="discovery"?e.jsx(Bc,{projectName:ee}):t==="technical-aeo"?e.jsx(Vc,{projectName:s.project.name}):t==="activity"?e.jsx(rc,{projectName:s.project.name}):t==="backlinks"?e.jsx(Nc,{projectName:s.project.name}):t==="local"?e.jsx(gc,{projectName:s.project.name,projectId:s.project.id}):e.jsx(bl,{projectName:s.project.name})]})}export{El as ProjectPage};
1
+ import{j as e,r,L as pt,n as ft,u as $e,o as Jt,A as Ni,h as wi}from"./vendor-tanstack-Dq7p98wZ.js";import{c as ys,T as se,t as zi,a as Si,u as Gn,C as ki,b as vs,P as Et,B as C,h as Ci,d as Ai,e as Li,f as Xe,g as Q,i as Z,I as Ne,j as Wt,k as Di,l as U,m as $i,n as Pi,o as Ii,p as Ri,q as Bn,r as Ti,s as Ei,S as Nt,v as Mi,w as Oi,x as Fi,y as Gi,z as xn,A as Bi,G as Le,D as Ks,E as qi,F as _i,H as Ui,J as Qi,K as Ki,L as ee,M as mn,N as qn,O as Vi,Q as Hi,R as Wi,U as Yi,V as Ji,W as Xi,X as Zi,Y as ea,Z as ta,_ as sa,$ as na,a0 as ia,a1 as aa,a2 as ra,a3 as ps,a4 as ca,a5 as la,a6 as un,a7 as oa,a8 as da,a9 as xa,aa as ma,ab as gs,ac as ua,ad as ha,ae as pa,af as qs,ag as ga,ah as fa,ai as ja,aj as ba,ak as ya,al as Xt,am as _n,an as Un,ao as va,ap as Qn,aq as Na,ar as wa,as as za,at as Sa,au as ka,av as Ca,aw as Kn,ax as Aa,ay as Vn,az as La,aA as Da,aB as $a,aC as Pa,aD as Hn,aE as Ia,aF as Ra,aG as Ta,aH as Ea,aI as Ma,aJ as Oa,aK as Fa,aL as Ga,aM as Ba,aN as qa,aO as _a,aP as Ua,aQ as Qa,aR as Ka,aS as Va,aT as Ha,aU as Wa,aV as Cs,aW as Ya,aX as Ja,aY as hn,aZ as Xa,a_ as Za,a$ as er,b0 as tr,b1 as sr,b2 as nr,b3 as ir,b4 as ar,b5 as rr,b6 as cr,b7 as pn,b8 as lr,b9 as or,ba as dr,bb as xr,bc as gn,bd as fn,be as mr,bf as ur,bg as hr,bh as pr,bi as gr,bj as fr,bk as jr,bl as br,bm as yr,bn as Wn,bo as Yn,bp as vr,bq as Jn,br as Nr,bs as Xn,bt as wr,bu as zr,bv as cs,bw as Sr,bx as kr,by as Cr,bz as jn}from"./index-CKbfZ6rA.js";import{R as Ar}from"./RunRow-CgojRiy8.js";import{f as Mt,C as rt,a as He,b as wt,c as gt,d as Be,e as Ge,g as fs,h as Lr,i as Vs,p as Dr}from"./ChartPrimitives-DbjEIcrG.js";import{u as $r,t as Pr,R as js}from"./server-traffic-Dskh-6z1.js";import{R as Ot,C as Ft,X as Gt,Y as Bt,T as qt,L as Zn,A as $t,a as Hs,b as Ir,d as Ws}from"./vendor-recharts-ClRVR6aX.js";import{C as ei,D as Ys,a as Rr,T as Tr}from"./trash-2-b62WCytM.js";import"./vendor-radix-B57xfQbP.js";import"./vendor-markdown-DK7fbRNb.js";const Er=[["path",{d:"M5 12h14",key:"1ays0h"}]],Mr=ys("minus",Er);const Or=[["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"}]],Fr=ys("scan-search",Or);const Gr=[["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"}]],Br=ys("unplug",Gr);const qr=[["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"}]],_r=ys("upload",qr),Ur=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function ti(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function si(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 ni(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(ti).map(si).filter(Boolean)):new Set}function ii(t,s){const n=ti(t).map(si).filter(Boolean).filter(i=>!Ur.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function Qr(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function Kr(t,s){const n=ni(t);if(s.length<=1||n.size===0)return[...s];const i=new Set,a=[];for(const l of s){if(l.category!=="content"){a.push(l);continue}const o=ii(Qr(l),n);!o||i.has(o)||(i.add(o),a.push(l))}return a}function Vr(t){const s=ni(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const l=ii(a.query,s);return!l||i.has(l)?!1:(i.add(l),!0)})}function As(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 Hr(t,s){return s<=0?null:Math.round((t-s)/s*100)}function Ls(t,s,n="vs prior 7 days"){return t.deltaPct===null?t.prior===0?"First baseline week":"":t.deltaPct>0?`Up ${t.deltaPct}% ${n} (${As(t.prior)} ${s})`:t.deltaPct<0?`Down ${Math.abs(t.deltaPct)}% ${n} (${As(t.prior)} ${s})`:`Flat ${n} (${As(t.prior)} ${s})`}function _s({state:t,label:s}){return e.jsx(se,{tone:Si(t),children:s??zi(t)})}function bn({history:t,maxDots:s=12}){const n=t.slice(-s);if(n.length===0)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"No data"});const i={cited:"bg-emerald-400","not-cited":"bg-zinc-600",lost:"bg-rose-400",emerging:"bg-amber-400 ring-1 ring-amber-300/60"},a=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"});return e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:a}),e.jsx("div",{className:"flex items-center gap-[3px]",title:`${n.length} runs`,children:n.map((o,u)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[o.citationState]??"bg-zinc-700"} ${o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"ring-1 ring-amber-300/80 ring-offset-1 ring-offset-zinc-950":""}`,title:[o.citationState,new Date(o.createdAt).toLocaleDateString(),o.model?`model ${o.model}`:null,o.model&&u>0&&n[u-1]?.model&&n[u-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},u))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:l})]})}function Wr(t){const s=new Map;for(const i of t)for(const a of i.runHistory){const l=s.get(a.createdAt);l?l.states.push(a.citationState):s.set(a.createdAt,{states:[a.citationState],runId:a.runId})}return[...s.entries()].sort(([i],[a])=>i.localeCompare(a)).map(([i,{states:a,runId:l}])=>({runId:l,createdAt:i,citationState:a.includes("cited")?"cited":a.includes("emerging")?"emerging":"not-cited"}))}const Yr=320;function yn(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 vn(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 Nn(t,s){const n=s==="mentions"?"mentioned":"cited",i=s==="mentions"?"Mentioned":"Cited";if(t.length===0)return"Awaiting first run";if(t.length===1)return"First observation";const a=t[t.length-1].citationState,l=t[t.length-2].citationState;if(l!=="cited"&&a==="cited")return`Newly ${n}`;if(l==="cited"&&a!=="cited")return"Lost since last run";let o=0;for(let u=t.length-1;u>=0&&t[u].citationState===a;u--)o++;return a==="cited"?o<=1?`${i} in latest run`:`${i} for ${o} runs`:o<=1?`Not ${n} in latest run`:`Not ${n} across ${o} runs`}function Jr(t,s){return s==="citations"?t:t.map(n=>({...n,citationState:yn(n,s),runHistory:n.runHistory.map(i=>({...i,citationState:yn(i,s)}))}))}function Xr({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=Gn(),[a,l]=r.useState(new Set),[o,u]=r.useState("mentions"),[m,p]=r.useState(n),f=r.useMemo(()=>{const b=Jr(t,o),k=new Map;for(const $ of b){const M=$.query,R=s?$.location??null:null,y=s?JSON.stringify([M,R]):M,j=k.get(y)??{key:y,phrase:M,location:R,items:[]};j.items.push($),k.set(y,j)}return[...k.values()]},[t,o,s]),d=b=>{l(k=>{const $=new Set(k);return $.has(b)?$.delete(b):$.add(b),$})},A=o==="mentions"?"mentioned":"cited",L=o==="mentions"?"Mention History":"Citation History",D=o==="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-zinc-500",children:"View by"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Citation tracking view",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":o==="mentions",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="mentions"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("mentions"),children:"Mentions"}),e.jsx("button",{type:"button",role:"tab","aria-selected":o==="citations",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${o==="citations"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>u("citations"),children:"Citations"})]}),e.jsx("span",{className:"text-[11px] text-zinc-500",children:o==="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-zinc-400 hover:text-zinc-200",onClick:()=>{l(b=>b.size===f.length?new Set:new Set(f.map(k=>k.key)))},children:a.size===f.length&&f.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-zinc-500",children:"Density"}),e.jsxs("div",{className:"inline-flex gap-0.5 p-0.5 rounded-md bg-zinc-900/60 border border-zinc-800/40",role:"tablist","aria-label":"Evidence row density",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":m==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":m==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${m==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>p("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:L}),e.jsx("th",{scope:"col",children:"Change"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:f.map(({key:b,phrase:k,location:$,items:M})=>{const R=a.has(b),y=M.map(E=>E.citationState),j=y.includes("cited")?"cited":y.includes("emerging")?"emerging":y.includes("lost")?"lost":y.every(E=>E==="pending")?"pending":"not-cited",x=Wr(M),T=M.filter(E=>E.citationState===ki.cited||E.citationState==="emerging").length,q=Nn(x,o);return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"evidence-phrase-row cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>d(b),onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),d(b))},tabIndex:0,role:"button","aria-expanded":R,children:[e.jsx("td",{children:e.jsx(vs,{size:14,className:`transition-transform duration-150 text-zinc-500 ${R?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:k}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:$??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:M.map(E=>e.jsx(Et,{provider:E.provider},E.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_s,{state:j,label:vn(j,o)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${T} of ${M.length} engines ${D}`,children:[T,"/",M.length]})]})}),e.jsx("td",{children:e.jsx(bn,{history:x})}),e.jsx("td",{className:"evidence-change-cell",children:q}),e.jsx("td",{})]}),R&&M.map(E=>e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:"bg-zinc-900/30",children:[e.jsx("td",{}),e.jsx("td",{className:"evidence-query-cell pl-5",children:e.jsx(Et,{provider:E.provider})}),e.jsx("td",{children:e.jsx(_s,{state:E.citationState,label:vn(E.citationState,o)})}),e.jsx("td",{children:e.jsx(bn,{history:E.runHistory})}),e.jsx("td",{className:"evidence-change-cell",children:Nn(E.runHistory,o)}),e.jsx("td",{children:e.jsx(C,{variant:"ghost",size:"sm",type:"button",onClick:G=>{G.stopPropagation(),i(E.id)},children:"View"})})]}),m==="detailed"&&e.jsxs("tr",{className:"bg-zinc-900/20",children:[e.jsx("td",{}),e.jsx("td",{colSpan:5,className:"px-5 pb-4",children:e.jsx(tc,{item:E,onViewFull:()=>i(E.id)})})]})]},E.id))]},b)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",A==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function Zr(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const l=Ai(a);return l.length>=4?[l]:[]}),...t.recommendedCompetitors??[]].filter(a=>a.trim().length>2),i=[];return s.length>0&&i.push({terms:s,className:"answer-highlight-brand"}),n.length>0&&i.push({terms:n,className:"answer-highlight-competitor"}),i}function ec(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 tc({item:t,onViewFull:s}){if(!(t.answerSnippet.trim().length>0))return e.jsx("p",{className:"text-[11px] text-zinc-500 italic",children:"No answer text captured for this run."});const{body:i,truncated:a}=ec(t.answerSnippet,Yr),l=Zr(t);return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Answer text"}),e.jsx("p",{className:"text-sm leading-relaxed text-zinc-300",children:Ci(i,l)}),(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-zinc-500",children:"Cited:"}),t.citedDomains.slice(0,6).map(o=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-900/60 px-2 py-0.5 text-[11px] text-zinc-300",children:o},`c-${o}`)),t.citedDomains.length>6&&e.jsxs("span",{className:"text-[10px] text-zinc-500",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-rose-500/80",children:"Competitors:"}),t.competitorDomains.slice(0,4).map(o=>e.jsx("span",{className:"rounded-full border border-rose-900/40 bg-rose-950/30 px-2 py-0.5 text-[11px] text-rose-300",children:o},`co-${o}`)),t.competitorDomains.length>4&&e.jsxs("span",{className:"text-[10px] text-zinc-500",children:["+",t.competitorDomains.length-4," more"]})]})]}),a&&e.jsx("button",{type:"button",className:"text-[11px] font-medium text-emerald-400 hover:text-emerald-300",onClick:o=>{o.stopPropagation(),s()},children:"View full answer →"})]})}function sc({competitors:t,onSelectCompetitor:s,onRemoveCompetitor:n,activeFilter:i}){if(t.length===0)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No competitors configured. Add competitors to track overlap."});const a=s!=null,l=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"}),l&&e.jsx("th",{children:e.jsx("span",{className:"sr-only",children:"Actions"})})]})}),e.jsx("tbody",{children:t.map(o=>{const u=i!=null&&i.toLowerCase()===o.domain.toLowerCase(),m=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",u?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:m,onClick:a?()=>s(o.domain):void 0,title:a?`Filter answers to queries where ${o.domain} surfaced`:void 0,children:[e.jsx("td",{className:"font-medium text-zinc-100",children:o.domain}),e.jsx("td",{children:e.jsx(se,{tone:Li(o.pressureLabel),children:o.pressureLabel})}),e.jsx("td",{className:"text-zinc-300 tabular-nums",children:o.totalQueries>0?`${o.citationCount} / ${o.totalQueries}`:"—"}),e.jsx("td",{className:"text-zinc-500 text-xs",children:o.citedQueries.length>0?o.citedQueries.join(", "):"Not cited"}),l&&e.jsx("td",{className:"text-right",children:e.jsx("button",{type:"button",className:"rounded px-1.5 py-0.5 text-xs text-zinc-500 transition-colors hover:text-rose-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-rose-500","aria-label":`Remove competitor ${o.domain}`,title:`Remove ${o.domain}`,onClick:p=>{p.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function wn({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:l,coverageValue:o,note:u,updatedAt:m,active:p,onClick:f}){return e.jsxs("button",{type:"button",onClick:f,className:`surface-card w-full text-left transition-colors ${p?"border-zinc-200 bg-zinc-900/50":"hover:border-zinc-700 hover:bg-zinc-900/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(se,{tone:i,children:n})]}),e.jsxs("div",{className:"mt-4 grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:a}),e.jsx("p",{className:"mt-1 truncate text-sm text-zinc-200",children:l})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Coverage"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:o})]})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1 text-xs text-zinc-500 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("span",{children:u}),e.jsx("span",{children:m?`Updated ${Xe(m)}`:"No recent sync yet"})]})]})}function ls({label:t,value:s,tone:n}){const i=n==="positive"?"text-emerald-400":n==="negative"?"text-rose-400":"text-zinc-200";return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-2 text-2xl font-semibold ${i}`,children:s})]})}const nc=6,_t="__other__",Rt="_socialTotal";function ic(t,s=nc){const n=new Map;for(const f of t)n.set(f.source,(n.get(f.source)??0)+f.sessions);const i=[...n.entries()].sort((f,d)=>d[1]!==f[1]?d[1]-f[1]:f[0].localeCompare(d[0])),a=i.slice(0,s),l=new Set(a.map(([f])=>f)),o=Math.max(0,i.length-s),u=new Map;for(const f of t){let d=u.get(f.date);d||(d={date:f.date,[Rt]:0},u.set(f.date,d));const A=l.has(f.source)?f.source:_t;d[A]=(d[A]??0)+f.sessions,d[Rt]=(d[Rt]??0)+f.sessions}const m=[...u.values()].sort((f,d)=>String(f.date).localeCompare(String(d.date))),p=a.map(([f])=>f);return o>0&&p.push(_t),{data:m,sources:p,otherCount:o}}function Tt(t){return t.replace(/\+/g," ")}function ai(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const ac=["7d","30d","90d","all"],ht=Ge,Us=Be.textDim,ri=Be.textFaint,Yt=25,os=50;function ds(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function ci(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function rc({projectName:t}){const{data:s,isLoading:n,isError:i}=$r(t);if(n)return e.jsx(Q,{className:"p-5",children:e.jsx("div",{className:"text-sm text-zinc-500",children:"Loading server activity…"})});if(i)return e.jsx(Q,{className:"p-5",children:e.jsx("div",{className:"text-sm text-rose-400",children:"Failed to load server activity."})});const a=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-zinc-50",children:"Crawler hits, AI fetches & AI referral sessions"}),e.jsxs("p",{className:"text-xs text-zinc-500 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."," ",e.jsx(pt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Manage sources →"})]})]})}),a.length===0?e.jsx(Q,{className:"p-5",children:e.jsxs("div",{className:"text-sm text-zinc-400",children:["No server traffic source connected yet."," ",e.jsx(pt,{to:"/traffic",className:"text-blue-400 hover:underline",children:"Connect a traffic source"})," ","to surface bot crawls and AI referrals straight from server logs."]})}):e.jsx(Q,{className:"overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-zinc-900/50 text-[10px] uppercase tracking-wide text-zinc-500",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:a.map(l=>e.jsxs("tr",{className:"border-t border-zinc-800/60",children:[e.jsx("td",{className:"px-4 py-3 text-zinc-100",children:l.displayName}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(se,{tone:Pr(l.status),children:l.status})}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.crawlerHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiUserFetchHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right tabular-nums text-zinc-100",children:l.totals24h.aiReferralHits.toLocaleString("en-US")}),e.jsx("td",{className:"px-4 py-3 text-right text-zinc-400 text-xs",children:l.lastSyncedAt?ci(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(pt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function cc({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(rc,{projectName:t}),e.jsx(lc,{projectName:t})]})}function lc({projectName:t}){const s=ft(),[n,i]=r.useState(null),[a,l]=r.useState(null),[o,u]=r.useState(!0),[m,p]=r.useState(!1),[f,d]=r.useState(!1),[A,L]=r.useState(null),[D,b]=r.useState(null),[k,$]=r.useState("sessions"),[M,R]=r.useState("desc"),[y,j]=r.useState("sessions"),[x,T]=r.useState("desc"),[q,E]=r.useState("sessions"),[G,S]=r.useState("desc"),[P,B]=r.useState("sessions"),[w,Y]=r.useState("desc"),[ae,pe]=r.useState(1),[K,W]=r.useState([]),[de,he]=r.useState([]),[g,O]=r.useState([]),[H,le]=r.useState(!1),[ue,Me]=r.useState("30d");async function we(N){u(!0),L(null);try{const F=await s.fetchQuery({...Di({client:U,path:{name:t}}),staleTime:Wt});if(N.current)return;if(i(F),!F.connected){l(null),W([]),he([]),O([]),u(!1);return}const _=ue==="all"?void 0:ue,[J,Ze,Kt,ge]=await Promise.all([s.fetchQuery({...$i({client:U,path:{name:t},query:_?{window:_}:void 0}),staleTime:Wt}).then(Ue=>Ue),s.fetchQuery({...Pi({client:U,path:{name:t},query:_?{window:_}:void 0}),staleTime:Wt}).catch(()=>[]),s.fetchQuery({...Ii({client:U,path:{name:t},query:_?{window:_}:void 0}),staleTime:Wt}).catch(()=>[]),s.fetchQuery({...Ri({client:U,path:{name:t},query:_?{window:_}:void 0}),staleTime:Wt}).catch(()=>[])]);if(N.current)return;l(J),W(Ze),he(Kt),O(ge),u(!1)}catch(F){if(N.current)return;L(F instanceof Error?F.message:"Failed to load GA4 data"),u(!1)}}r.useEffect(()=>{const N={current:!1};return we(N),()=>{N.current=!0}},[t,ue,s]);async function ne(){p(!0),L(null),b(null);try{const N=await Bn(t);b(`Synced ${N.rowCount.toLocaleString()} page rows, ${N.aiReferralCount.toLocaleString()} AI and ${N.socialReferralCount.toLocaleString()} social referral rows (${N.days} days)`),await s.invalidateQueries({predicate:F=>{const _=F.queryKey[0];return typeof _?._id=="string"&&_._id.startsWith("getApiV1ProjectsByNameGa")}}),await we({current:!1})}catch(N){L(N instanceof Error?N.message:"Sync failed")}finally{p(!1)}}async function te(){d(!0),L(null),b(null);try{await Ti(t),await s.invalidateQueries({predicate:N=>{const F=N.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),b("GA4 disconnected")}catch(N){L(N instanceof Error?N.message:"Disconnect failed")}finally{d(!1)}}function je(N){k===N?R(F=>F==="desc"?"asc":"desc"):($(N),R("desc"))}function ke(N){y===N?T(F=>F==="desc"?"asc":"desc"):(j(N),T("desc"))}function be(N){q===N?S(F=>F==="desc"?"asc":"desc"):(E(N),S("desc"))}function Ce(N){pe(1),P===N?Y(F=>F==="desc"?"asc":"desc"):(B(N),Y("desc"))}const xe=r.useMemo(()=>a?.topPages?[...a.topPages].sort((N,F)=>{const _=N[k],J=F[k];return typeof _=="string"&&typeof J=="string"?M==="asc"?_.localeCompare(J):J.localeCompare(_):M==="asc"?_-J:J-_}):[],[a?.topPages,k,M]),Re=r.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((N,F)=>{const _=N[y],J=F[y];return typeof _=="string"&&typeof J=="string"?x==="asc"?_.localeCompare(J):J.localeCompare(_):x==="asc"?_-J:J-_}):[],[a?.aiReferrals,y,x]),Ae=r.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((N,F)=>{const _=N[P],J=F[P];return typeof _=="string"&&typeof J=="string"?w==="asc"?_.localeCompare(J):J.localeCompare(_):w==="asc"?_-J:J-_}):[],[a?.aiReferralLandingPages,P,w]),z=Math.max(1,Math.ceil(Ae.length/os)),I=Math.min(Math.max(1,ae),z),Pe=(I-1)*os,We=r.useMemo(()=>Ae.slice(Pe,Pe+os),[Ae,Pe]),ye=r.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((N,F)=>{const _=N[q],J=F[q];return typeof _=="string"&&typeof J=="string"?G==="asc"?_.localeCompare(J):J.localeCompare(_):G==="asc"?_-J:J-_}):[],[a?.socialReferrals,q,G]),{socialChartData:jt,socialChartSources:ct,socialOtherCount:qe}=r.useMemo(()=>{const N=ic(g);return{socialChartData:N.data,socialChartSources:N.sources,socialOtherCount:N.otherCount}},[g]),{chartData:lt,chartSources:Ie,dateRange:Ye}=r.useMemo(()=>{const N=[...new Set(K.map(ge=>ge.source))],F=new Map;for(const ge of de)F.set(ge.date,{_totalSessions:ge.sessions,_organicSessions:ge.organicSessions});const _=new Map;for(const ge of K){const Ue=`${ge.date}::${ge.source}`,kt=_.get(Ue)??0;_.set(Ue,Math.max(kt,ge.sessions))}for(const[ge,Ue]of _){const[kt,dt]=ge.split("::");let et=F.get(kt);et||(et={_totalSessions:0,_organicSessions:0},F.set(kt,et)),et[dt]=(et[dt]??0)+Ue}const J=[...F.entries()].sort(([ge],[Ue])=>ge.localeCompare(Ue)).map(([ge,Ue])=>({date:ge,...Ue})),Ze=J.map(ge=>ge.date),Kt=Ze.length>0?{start:Ze[0],end:Ze[Ze.length-1]}:null;return{chartData:J,chartSources:N,dateRange:Kt}},[K,de]);if(o&&!n)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading traffic data…"});if(!n?.connected)return e.jsx(oc,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:N=>{const F=N.queryKey[0];return typeof F?._id=="string"&&F._id.startsWith("getApiV1ProjectsByNameGa")}}),await we({current:!1})))()}});const tt=a?.organicSharePctDisplay??"0%",bt=a?.channelBreakdown?.organic.sharePctDisplay??tt,zt=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,Ut=a?.aiSessionsDeduped??0,ze=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Oe=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",Fe=a?new Set(a.aiReferrals.map(N=>N.source.toLowerCase())).size:0,ot=Re[0]??null,st=a?.totalDirectSessions??0,h=a?.directSharePctDisplay??"0%",V=a?.channelBreakdown?.direct.sessions??st,re=a?.channelBreakdown?.direct.sharePctDisplay??h,Te=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,ce=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",nt=a?.socialSessions??0,es=a?.socialSharePctDisplay??"0%",Qt=a?.channelBreakdown?.social.sessions??nt,St=a?.channelBreakdown?.social.sharePctDisplay??es,yt=a?new Set(a.socialReferrals.map(N=>N.source.toLowerCase())).size:0,_e=ye[0]??null;return e.jsxs(e.Fragment,{children:[A&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:A}),D&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-emerald-900/20 border border-emerald-800/60 text-sm text-emerald-300",children:D}),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-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Property ",e.jsx("span",{className:"text-zinc-300",children:n.propertyId}),n.clientEmail&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"text-zinc-500",children:n.clientEmail})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{variant:"outline",size:"sm",disabled:m,onClick:Z(ne),children:[e.jsx(js,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),m?"Syncing…":"Sync"]}),e.jsxs(C,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:f,onClick:Z(te),children:[e.jsx(Br,{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-zinc-500 mb-1",children:"Traffic Overview"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Site Traffic",e.jsx(Ne,{text:`Aggregated traffic metrics from Google Analytics 4. Sessions and users are summed across the selected period.${a?.periodStart&&a?.periodEnd?` Data available: ${new Date(a.periodStart+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})} – ${new Date(a.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:ac.map(N=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${ue===N?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>Me(N),children:N==="all"?"All":N},N))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Ds,{value:ds(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(Ds,{value:ds(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${tt} of total`,tone:"positive"}),e.jsx(Ds,{value:ds(a.totalUsers),label:"Total Users",subtitle:a.totalUsers.toLocaleString(),tone:"neutral"})]}):e.jsxs("div",{className:"surface-card rounded-lg p-6 text-center border border-zinc-800/60",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-3",children:"No traffic data yet."}),e.jsxs(C,{variant:"outline",size:"sm",disabled:m,onClick:Z(ne),children:[e.jsx(js,{className:`w-3.5 h-3.5 mr-1.5 ${m?"animate-spin":""}`}),"Sync from GA4"]})]})]}),a&&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-zinc-500 mb-1",children:"Traffic Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Traffic by channel",e.jsx(Ne,{text:"Decomposes GA4 sessions into five disjoint channels — known AI referrers first, then organic search, social, direct, and other channels. Known AI referrers are removed from their native GA4 channel before the residual Other bucket is computed. Other channels are the remaining GA4 session default channel groups, such as Referral, Email, Paid Search, Display, Cross-network, Shopping, Video, Affiliates, SMS, and Paid Other."})]})]}),Ye&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(Ye.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Ye.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),lt.length>0&&e.jsxs(Q,{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-zinc-100",children:Ie.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Ie.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Ie.length===0&&e.jsx("p",{className:"text-xs text-zinc-500",children:"No AI referrals detected yet"})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ot,{width:"100%",height:"100%",children:e.jsxs(Ft,{data:lt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Gt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:rt},tickFormatter:Mt}),e.jsx(Bt,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(qt,{...gt,labelFormatter:wt,formatter:(N,F)=>{const _=typeof N=="number"?N.toLocaleString():String(N??0),J=String(F??"");return J==="_totalSessions"?[_,"Total Sessions"]:J==="_organicSessions"?[_,"Organic Sessions"]:[_,J]}}),e.jsx(Zn,{wrapperStyle:{fontSize:11,color:Be.text},formatter:N=>N==="_totalSessions"?"Total Sessions":N==="_organicSessions"?"Organic Sessions":N}),e.jsx($t,{type:"monotone",dataKey:"_totalSessions",stroke:Be.textFaint,fill:Be.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Ie.map((N,F)=>e.jsx($t,{type:"monotone",dataKey:N,stackId:"ai",stroke:ht[F%ht.length],fill:ht[F%ht.length],fillOpacity:.4,strokeWidth:1.5},N))]})})})]}),e.jsxs(Q,{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-zinc-100",children:"Channel breakdown"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Je,{label:"Organic",value:bt,hint:`${zt.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(Je,{label:"Social",value:St,hint:`${Qt.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(Je,{label:"Direct",value:re,hint:`${V.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(Je,{label:"Known AI referrers (lower bound)",value:Oe,hint:`${ze.toLocaleString()} sessions`,tone:"positive",tooltip:"Sessions whose current sessionSource matched a known AI engine (e.g. chatgpt.com, claude.ai, gemini.google.com). These sessions are removed from their native GA4 channel in this card grid so the five buckets stay disjoint. This is a strict lower bound: most AI traffic strips the referrer and falls into Direct, so the true AI share is typically higher than what's shown here. The detail table below also surfaces firstUserSource and UTM-tagged AI signals."}),e.jsx(Je,{label:"Other channels",value:ce,hint:`${Te.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."})]}),ot&&e.jsxs("div",{className:"mt-4 rounded-lg border border-emerald-800/40 bg-emerald-500/6 px-4 py-3 text-sm text-emerald-100",children:["Top AI referrer: ",e.jsx("span",{className:"font-medium",children:ot.source})," via ",ot.medium,", accounting for ",ot.sessions.toLocaleString()," sessions."]})]}),e.jsxs(Q,{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-zinc-100",children:"Known AI referrers by source"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.aiReferrals.length>0?`${Fe} unique sources, ${a.aiReferrals.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(De,{label:"Source",sortKey:"source",current:y,dir:x,onSort:ke,align:"left"}),e.jsx(De,{label:"Medium",sortKey:"medium",current:y,dir:x,onSort:ke,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(De,{label:"Sessions",sortKey:"sessions",current:y,dir:x,onSort:ke,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(De,{label:"Users",sortKey:"users",current:y,dir:x,onSort:ke,align:"right"})]})}),e.jsx("tbody",{children:Re.map(N=>e.jsx(xc,{referral:N,totalSessions:Ut},`${N.source}:${N.medium}:${N.sourceDimension}`))})]})}):e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("p",{className:"text-sm text-zinc-400 mb-2",children:"No AI referrer sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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(Q,{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-zinc-100",children:"Known AI referrers by landing page"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:Ae.length>os?`${Pe+1}–${Pe+We.length} of ${Ae.length} rows`:Ae.length>0?`${Ae.length} rows`:"No landing-page rows"})]}),Ae.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-zinc-500",children:[e.jsx(De,{label:"Landing Page",sortKey:"landingPage",current:P,dir:w,onSort:Ce,align:"left"}),e.jsx(De,{label:"Source",sortKey:"source",current:P,dir:w,onSort:Ce,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(De,{label:"Sessions",sortKey:"sessions",current:P,dir:w,onSort:Ce,align:"right"}),e.jsx(De,{label:"Users",sortKey:"users",current:P,dir:w,onSort:Ce,align:"right"})]})}),e.jsx("tbody",{children:We.map(N=>e.jsx(mc,{row:N},`${N.landingPage}:${N.source}:${N.medium}:${N.sourceDimension}`))})]})}),z>1&&e.jsxs("div",{className:"mt-3 flex items-center justify-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>pe(I-1),disabled:I<=1,className:"text-xs text-zinc-400 hover:text-zinc-200 disabled:opacity-40 disabled:hover:text-zinc-400 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 disabled:hover:border-zinc-800 transition-colors",children:"Previous"}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:["Page ",I," of ",z]}),e.jsx("button",{type:"button",onClick:()=>pe(I+1),disabled:I>=z,className:"text-xs text-zinc-400 hover:text-zinc-200 disabled:opacity-40 disabled:hover:text-zinc-400 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 disabled:hover:border-zinc-800 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-zinc-400 mb-2",children:"No AI landing pages detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 max-w-sm",children:"Known-AI landing pages appear after a GA4 sync records visits from AI referrers."})]})]})]})]}),a&&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-zinc-500 mb-1",children:"Social Attribution"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Social Media Traffic",e.jsx(Ne,{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."})]})]}),jt.length>0&&e.jsxs(Q,{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-zinc-100",children:"Social sessions over time"})]}),qe>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",ct.length-1," sources · ",qe," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(Ot,{width:"100%",height:"100%",children:e.jsxs(Ft,{data:jt,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(Gt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:rt},tickFormatter:Mt}),e.jsx(Bt,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(qt,{...gt,labelFormatter:wt,formatter:(N,F)=>{const _=typeof N=="number"?N.toLocaleString():String(N??0),J=String(F??"");if(J===Rt)return[_,"Total Social"];if(J===_t){const Ze=`Other (${qe} source${qe===1?"":"s"})`;return[_,Ze]}return[_,Tt(J)]}}),e.jsx($t,{type:"monotone",dataKey:Rt,stroke:ri,fill:Be.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),ct.map((N,F)=>{const J=N===_t?Us:ht[F%ht.length];return e.jsx($t,{type:"monotone",dataKey:N,stackId:"social",stroke:J,fill:J,fillOpacity:.4,strokeWidth:1.5},N)})]})})}),e.jsx(hc,{sources:ct,otherCount:qe})]}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,0.9fr)_minmax(0,1.5fr)]",children:[e.jsxs(Q,{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-zinc-100",children:"Social media visits"})]}),a.socialReferrals.length>0?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Je,{label:"Social Sessions",value:ds(nt),hint:`${nt.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(Je,{label:"Share of Traffic",value:es,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(Je,{label:"Platforms",value:String(yt),hint:`${a.socialReferrals.length} source rows`,tone:"neutral",tooltip:"Number of distinct social media platforms detected. Each unique source/medium combination counts as one source row."})]}),_e&&e.jsxs("div",{className:"mt-4 rounded-lg border border-sky-800/40 bg-sky-500/6 px-4 py-3 text-sm text-sky-100",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-sky-300/70 mb-1",children:"Top social source"}),e.jsx("p",{className:"font-medium truncate",title:`${_e.source} via ${_e.medium}`,children:ai(Tt(_e.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:_e.medium,children:["via ",Tt(_e.medium)," · ",_e.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(Je,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(Je,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(Je,{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-zinc-800/60 bg-zinc-900/30 px-4 py-3 text-sm text-zinc-400",children:[e.jsx("p",{className:"mb-1.5 text-zinc-300",children:"Monitoring social media traffic via GA4 channel grouping"}),e.jsx("p",{className:"text-xs text-zinc-500",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(Q,{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-zinc-100",children:"Source / medium"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.socialReferrals.length>0?ye.length>Yt&&!H?`Top ${Yt} of ${ye.length}`:`${ye.length} rows`:"No source rows"})]}),a.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-zinc-500",children:[e.jsx(De,{label:"Source",sortKey:"source",current:q,dir:G,onSort:be,align:"left"}),e.jsx(De,{label:"Medium",sortKey:"medium",current:q,dir:G,onSort:be,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(De,{label:"Sessions",sortKey:"sessions",current:q,dir:G,onSort:be,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(De,{label:"Users",sortKey:"users",current:q,dir:G,onSort:be,align:"right"})]})}),e.jsx("tbody",{children:(H?ye:ye.slice(0,Yt)).map(N=>e.jsx(uc,{referral:N,totalSessions:nt},`${N.source}:${N.medium}:${N.channelGroup}`))})]})}),ye.length>Yt&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>le(N=>!N),className:"text-xs text-zinc-400 hover:text-zinc-200 px-3 py-1 rounded-full border border-zinc-800 hover:border-zinc-700 transition-colors",children:H?`Show top ${Yt}`:`Show all ${ye.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-zinc-400 mb-2",children:"No social media sessions detected yet"}),e.jsx("p",{className:"text-xs text-zinc-500 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."})]})]})]})]})]}),a&&a.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-zinc-500 mb-1",children:"Page Performance"}),e.jsxs("h2",{className:"text-base font-semibold text-zinc-50 flex items-center gap-1.5",children:["Top Landing Pages",e.jsx(Ne,{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-zinc-500",children:[e.jsx(De,{label:"Landing Page",sortKey:"landingPage",current:k,dir:M,onSort:je,align:"left"}),e.jsx(De,{label:"Sessions",sortKey:"sessions",current:k,dir:M,onSort:je,align:"right"}),e.jsx(De,{label:"Organic",sortKey:"organicSessions",current:k,dir:M,onSort:je,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(De,{label:"Users",sortKey:"users",current:k,dir:M,onSort:je,align:"right"})]})}),e.jsx("tbody",{children:xe.map(N=>e.jsx(dc,{page:N},N.landingPage))})]})})]})]}),e.jsxs("div",{className:"mt-6 flex items-center justify-between text-xs text-zinc-500",children:[e.jsx("span",{children:a?.lastSyncedAt?`Last synced ${ci(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function oc({projectName:t,onConnected:s}){const[n,i]=r.useState(""),[a,l]=r.useState(null),[o,u]=r.useState(null),[m,p]=r.useState(!1),[f,d]=r.useState(null),A=r.useRef(null),L=r.useCallback(b=>{const k=b.target.files?.[0];if(!k)return;d(null),l(k.name);const $=new FileReader;$.onload=()=>{const M=$.result;try{const R=JSON.parse(M);if(!R.client_email||!R.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)."),u(null);return}u(M)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),u(null)}},$.onerror=()=>{d("Failed to read file."),u(null)},$.readAsText(k)},[]);async function D(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!o){d("Please upload a service account key file.");return}p(!0);try{await Ei(t,{propertyId:n.trim(),keyJson:o});try{await Bn(t)}catch{}s()}catch(b){d(b instanceof Error?b.message:"Failed to connect GA4")}finally{p(!1)}}return e.jsxs(Q,{className:"surface-card p-6",children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-50 mb-1",children:"Connect Google Analytics 4"}),e.jsx("p",{className:"text-sm text-zinc-400 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."}),f&&e.jsx("div",{className:"mb-4 px-4 py-2 rounded-lg bg-rose-900/20 border border-rose-800/60 text-sm text-rose-300",children:f}),e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{htmlFor:"ga4-property-id",className:"block text-xs font-medium text-zinc-400 mb-1.5",children:"GA4 Property ID"}),e.jsx("input",{id:"ga4-property-id",type:"text",placeholder:"e.g. 123456789",value:n,onChange:b=>i(b.target.value),className:"w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 px-3 py-2 text-sm text-zinc-200 placeholder:text-zinc-600 focus:outline-none focus:ring-1 focus:ring-zinc-600"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",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-zinc-400 mb-1.5",children:"Service Account Key File"}),e.jsx("input",{ref:A,type:"file",accept:".json,application/json",onChange:L,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>A.current?.click(),className:"flex items-center gap-2 w-full rounded-lg bg-zinc-900/60 border border-zinc-800/60 border-dashed px-4 py-3 text-sm text-zinc-400 hover:border-zinc-600 hover:text-zinc-300 transition-colors cursor-pointer",children:[e.jsx(_r,{className:"w-4 h-4 shrink-0"}),a?e.jsx("span",{className:"text-zinc-200 truncate",children:a}):e.jsx("span",{children:"Upload .json key file"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Download from Google Cloud Console → IAM & Admin → Service Accounts → Keys → Add Key → JSON. The service account must have ",e.jsx("span",{className:"text-zinc-400",children:"Viewer"})," access on the GA4 property."]})]}),e.jsx(C,{variant:"default",size:"sm",disabled:m||!n.trim()||!o,onClick:Z(D),children:m?"Connecting & syncing…":"Connect GA4"})]})}function De({label:t,sortKey:s,current:n,dir:i,onSort:a,align:l}){const o=n===s;return e.jsx("th",{className:`py-1 ${l==="right"?"text-right":"text-left"}`,children:e.jsxs("button",{type:"button",className:"font-medium cursor-pointer select-none hover:text-zinc-300 transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded",onClick:()=>a(s),"aria-label":`Sort by ${t}${o?` (currently ${i==="asc"?"ascending":"descending"})`:""}`,children:[t,o&&e.jsx("span",{className:"ml-0.5",children:i==="asc"?"↑":"↓"})]})})}const li={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function Ds({value:t,label:s,subtitle:n,tone:i}){return e.jsxs("div",{className:"rounded-lg bg-zinc-900/30 border border-zinc-800/60 px-5 py-4",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1",children:s}),e.jsx("p",{className:`text-2xl font-bold tabular-nums ${li[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function Je({value:t,label:s,hint:n,tone:i,tooltip:a}){return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 flex flex-col",children:[e.jsxs("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-zinc-500 mb-1 flex items-center gap-1",children:[s,a&&e.jsx(Ne,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${li[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function dc({page:t}){const s=t.sessions>0?(t.organicSessions/t.sessions*100).toFixed(1):"0.0";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[400px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.organicSessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[s,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}const oi={session:"Session",first_user:"First Visit",manual_utm:"UTM"},di={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 xc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=oi[t.sourceDimension]??t.sourceDimension,a=di[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-200 max-w-[220px] truncate",title:t.source,children:t.source}),e.jsx("td",{className:"py-1.5 text-zinc-500 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 border-zinc-700 text-zinc-400",title:a,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function mc({row:t}){const s=oi[t.sourceDimension]??t.sourceDimension,n=di[t.sourceDimension]??"";return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 text-zinc-300 max-w-[360px] truncate",title:t.landingPage,children:t.landingPage}),e.jsx("td",{className:"py-1.5 text-zinc-200 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-zinc-700 text-zinc-400",title:n,children:s})}),e.jsx("td",{className:"py-1.5 text-right text-emerald-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function uc({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Tt(t.source),l=Tt(t.medium);return e.jsxs("tr",{className:"border-t border-zinc-800/40",children:[e.jsx("td",{className:"py-1.5 pr-3 text-zinc-200 truncate",title:t.source,children:a}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500 truncate",title:t.medium,children:l}),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-zinc-700 text-zinc-400",title:`GA4 channel group: ${t.channelGroup}`,children:i})}),e.jsx("td",{className:"py-1.5 text-right text-sky-400 tabular-nums",children:t.sessions.toLocaleString()}),e.jsxs("td",{className:"py-1.5 text-right text-zinc-400 tabular-nums",children:[n,"%"]}),e.jsx("td",{className:"py-1.5 text-right text-zinc-200 tabular-nums",children:t.users.toLocaleString()})]})}function hc({sources:t,otherCount:s}){const n=[{key:Rt,color:ri,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===_t)n.push({key:_t,color:Us,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Tt(a);n.push({key:a,color:ht[i%ht.length]??Us,label:ai(l,32),tooltip:l})}}return e.jsx("div",{className:"mt-3 flex flex-wrap gap-x-4 gap-y-1.5 text-[11px] text-zinc-400",children:n.map(i=>e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0 max-w-[260px]",title:i.tooltip,children:[e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm shrink-0",style:{backgroundColor:i.color},"aria-hidden":"true"}),e.jsx("span",{className:"truncate",children:i.label})]},i.key))})}const pc=["7d","30d","90d","all"],xs=500,mt=25;function gc({projectName:t,refreshNonce:s}){const n=ft(),[i,a]=r.useState(!1),[l,o]=r.useState([]),[u,m]=r.useState([]),[p,f]=r.useState([]),[d,A]=r.useState(null),[L,D]=r.useState([]),[b,k]=r.useState([]),[$,M]=r.useState(null),[R,y]=r.useState(""),[j,x]=r.useState(""),[T,q]=r.useState("30"),[E,G]=r.useState(!1),[S,P]=r.useState("30d"),[B,w]=r.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[Y,ae]=r.useState(0),[pe,K]=r.useState(!1),[W,de]=r.useState(0),[he,g]=r.useState(!1),[O,H]=r.useState(""),[le,ue]=r.useState(!0),[Me,we]=r.useState(!1),[ne,te]=r.useState(!1),[je,ke]=r.useState(!1),[be,Ce]=r.useState(!1),[xe,Re]=r.useState(!1),[Ae,z]=r.useState(!1),[I,Pe]=r.useState(null),[We,ye]=r.useState(!1),[jt,ct]=r.useState(!1),[qe,lt]=r.useState(null),[Ie,Ye]=r.useState(""),[tt,bt]=r.useState(!1),[zt,Ut]=r.useState(!1),[ze,Oe]=r.useState("indexed"),[Fe,ot]=r.useState(null),st=!!(B.query.trim()||B.page.trim()||Fe),h=Fe!==null,V=r.useMemo(()=>{if(!Fe)return p;const{key:c,dir:v}=Fe;return[...p].sort((X,ie)=>{const Se=c===Nt.CTR?Number.isFinite(X.ctr)?X.ctr:0:X[c],Ee=c===Nt.CTR?Number.isFinite(ie.ctr)?ie.ctr:0:ie[c];return v==="asc"?Se-Ee:Ee-Se})},[p,Fe]),[re,Te]=r.useState([]),[ce,nt]=r.useState(null),[es,Qt]=r.useState(1);r.useEffect(()=>{Qt(1)},[I,ze,ce]);const St=r.useMemo(()=>ce?(I?.reasonGroups??[]).find(c=>c.reason===ce):void 0,[I,ce]),yt=r.useMemo(()=>I?ze==="indexed"?I.indexed:ze==="deindexed"?I.deindexed:ze==="notIndexed"?ce?St?.urls??[]:(I.reasonGroups??[]).length===0?I.notIndexed:[]:[]:[],[I,ze,ce,St]),_e=Math.max(1,Math.ceil(yt.length/mt)),N=Math.min(Math.max(1,es),_e),F=(N-1)*mt,_=yt.length>mt,J=yt.length===0?0:F+1,Ze=Math.min(F+mt,yt.length),Kt=r.useMemo(()=>I?.indexed.slice(F,F+mt)??[],[I,F]),ge=r.useMemo(()=>I?.notIndexed.slice(F,F+mt)??[],[I,F]),Ue=r.useMemo(()=>I?.deindexed.slice(F,F+mt)??[],[I,F]),kt=r.useMemo(()=>(St?.urls??[]).slice(F,F+mt),[St,F]),[dt,et]=r.useState(!1),[en,oe]=r.useState(null),[tn,it]=r.useState(null),fe=l.find(c=>c.connectionType==="gsc"),xi=p.length>0||L.length>0||b.length>0,zs=Mi(),Vt=Oi(),Ss=Fi();async function sn(c){if(!c){m([]),y("");return}te(!0);try{const{sites:v}=await n.fetchQuery({...Ji({client:U,path:{name:t}}),staleTime:Le});m(v),y(c.propertyId??v[0]?.siteUrl??"")}catch(v){m([]),oe(v instanceof Error?v.message:"Failed to load Search Console properties")}finally{te(!1)}}async function Ct(c){Ce(!0);const v=c??Y;try{const X=parseInt(B.limit,10)||20,ie=st?xs:X+1,Se=st?0:v,Ee={limit:String(ie)};B.startDate&&(Ee.startDate=B.startDate),B.endDate&&(Ee.endDate=B.endDate),B.query&&(Ee.query=B.query),B.page&&(Ee.page=B.page),Se>0&&(Ee.offset=String(Se)),S&&S!=="all"&&!B.startDate&&(Ee.window=S);const Qe=await n.fetchQuery({...qi({client:U,path:{name:t},query:Ee}),staleTime:Le});st?(K(!1),f(Qe),de(Qe.length),g(!0)):(K(Qe.length>X),f(Qe.slice(0,X)),de(0),g(!1))}catch(X){f([]),K(!1),de(0),oe(X instanceof Error?X.message:"Failed to load GSC performance data")}finally{Ce(!1)}}async function ks(){try{const c={};B.startDate&&(c.startDate=B.startDate),B.endDate&&(c.endDate=B.endDate),S&&S!=="all"&&!B.startDate&&(c.window=S);const v=await n.fetchQuery({..._i({client:U,path:{name:t},query:c}),staleTime:Le});A(v)}catch{A(null)}}async function ts(){Re(!0);try{const c=O.trim()||void 0,v={limit:"20"};c&&(v.url=c);const[X,ie]=await Promise.all([n.fetchQuery({...Wi({client:U,path:{name:t},query:v}),staleTime:Le}),n.fetchQuery({...Yi({client:U,path:{name:t}}),staleTime:Le})]);D(X),k(ie)}catch(c){D([]),k([]),oe(c instanceof Error?c.message:"Failed to load GSC inspection history")}finally{Re(!1)}}async function nn(){ye(!0);try{const[c,v]=await Promise.all([n.fetchQuery({...qn({client:U,path:{name:t}}),staleTime:Le}),n.fetchQuery({...Vi({client:U,path:{name:t}}),staleTime:Le}).catch(()=>[])]);Pe(c),Te(v)}catch(c){Pe(null),Te([]),oe(c instanceof Error?c.message:"Failed to load coverage data")}finally{ye(!1)}}async function an(c){et(!0),oe(null);try{const v=await mn(t,{urls:c}),{succeeded:X,failed:ie,total:Se}=v.summary;ee({title:"Indexing requested",detail:ie===0?`${X} URL${X!==1?"s":""} submitted for indexing.`:`${X}/${Se} submitted successfully, ${ie} failed.`,tone:ie===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(v){oe(v instanceof Error?v.message:"Failed to request indexing")}finally{et(!1)}}async function mi(){et(!0),oe(null);try{const c=await mn(t,{urls:[],allUnindexed:!0}),{succeeded:v,failed:X,total:ie}=c.summary;ee({title:"Indexing requested",detail:X===0?`${v} unindexed URL${v!==1?"s":""} submitted for indexing.`:`${v}/${ie} submitted successfully, ${X} failed.`,tone:X===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(c){oe(c instanceof Error?c.message:"Failed to request indexing")}finally{et(!1)}}async function ss(){if(Ie.trim()){bt(!0),oe(null);try{await Ki(t,"gsc",Ie.trim()),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(v=>v.connectionType==="gsc"?{...v,sitemapUrl:Ie.trim()}:v)),ee({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),Ye("")}catch(c){oe(c instanceof Error?c.message:"Failed to save sitemap URL")}finally{bt(!1)}}}async function rn(){oe(null);try{const c=await Vt.mutateAsync({projectName:t,projectLabel:t});lt(c.sitemaps),o(v=>v.map(X=>X.connectionType==="gsc"?{...X,sitemapUrl:c.primarySitemapUrl}:X))}catch{}}async function ui(){ct(!0),oe(null);try{const c=await Zi(t);n.setQueryData(ea({client:U,path:{name:t}}),c),lt(c.sitemaps),c.sitemaps.length===0&&it("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(c){oe(c instanceof Error?c.message:"Failed to list sitemaps")}finally{ct(!1)}}async function cn(){ue(!0),oe(null);try{const[c,v]=await Promise.all([Bi().catch(()=>null),n.fetchQuery({...Ks({client:U,path:{name:t}}),staleTime:Le}).catch(()=>[])]);a(!!c?.google?.configured),o(v);const X=v.find(ie=>ie.connectionType==="gsc");await Promise.all([sn(X),Ct(),ks(),ts(),nn()])}finally{ue(!1)}}r.useEffect(()=>{cn()},[t,s]),r.useEffect(()=>{ae(0),Ct(0),ks()},[S]);const ln=r.useRef(!1);r.useEffect(()=>{if(!ln.current){ln.current=!0;return}ae(0),Ct(0)},[h]);async function hi(){if(!i){oe("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}we(!0),oe(null),it(null);try{const{authUrl:c}=await Qi(t,"gsc");if(!c.startsWith("https://accounts.google.com/")){oe("Unexpected OAuth redirect URL. Please try again.");return}const v=window.open(c,"_blank","width=600,height=700");if(!v){window.location.assign(c);return}it("Finish the Google consent flow in the popup, then close it to refresh this project.");const X=window.setInterval(()=>{v.closed&&(window.clearInterval(X),it(null),n.invalidateQueries({predicate:ie=>{const Se=ie.queryKey[0];return typeof Se?._id=="string"&&Se._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),cn())},1e3)}catch(c){oe(c instanceof Error?c.message:"Failed to start OAuth flow")}finally{we(!1)}}async function pi(){oe(null),it(null);try{await Ui(t,"gsc"),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.filter(v=>v.connectionType!=="gsc")),m([]),y("")}catch(c){oe(c instanceof Error?c.message:"Failed to disconnect")}}async function gi(){if(R){ke(!0),oe(null);try{await Xi(t,"gsc",R),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(c=>c.map(v=>v.connectionType==="gsc"?{...v,propertyId:R}:v)),ee({title:"GSC property updated",detail:`${t} is now linked to ${R}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(c){oe(c instanceof Error?c.message:"Failed to save GSC property")}finally{ke(!1)}}}async function fi(){oe(null),it(null);try{await zs.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(T,10)||void 0,full:E||void 0}}),await n.invalidateQueries({predicate:c=>{const v=c.queryKey[0];return typeof v?._id=="string"&&v._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function on(){if(j.trim()){z(!0),oe(null),it(null);try{const c=await Hi(t,j.trim());await n.invalidateQueries({predicate:v=>{const X=v.queryKey[0];return typeof X?._id=="string"&&X._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),M(c),x(""),await ts()}catch(c){oe(c instanceof Error?c.message:"Failed to inspect URL")}finally{z(!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"})]})}),en&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[en,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>oe(null),children:"×"})]}),tn&&e.jsxs("div",{className:"mb-3 rounded-lg border border-emerald-800/40 bg-emerald-950/20 px-3 py-2 text-sm text-emerald-300",children:[tn,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>it(null),children:"×"})]}),le?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[fe?e.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 px-1 text-xs text-zinc-500",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-emerald-500"}),e.jsx("span",{className:"text-zinc-300",children:"Authorized"})]}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsx("code",{className:"text-zinc-400",children:fe.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Xe(fe.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:Z(pi),children:"Disconnect"})]}):e.jsxs(Q,{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(se,{tone:i?"caution":"negative",children:i?"Ready to connect":"App credentials missing"})]}),e.jsxs("div",{className:"mt-3 rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-4 py-5",children:[e.jsx("p",{className:"text-sm text-zinc-300",children:i?"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."}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[i?e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:Me,onClick:Z(hi),children:Me?"Opening…":"Connect Google Search Console"}):e.jsx(C,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(pt,{to:"/settings",children:"Open Settings"})}),!i&&e.jsx("p",{className:"text-xs text-zinc-500",children:"The same Google OAuth app credentials are shared across all projects."})]})]})]}),fe&&!fe.sitemapUrl&&e.jsx("div",{className:"rounded-lg border border-amber-800/40 bg-amber-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-amber-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-amber-300",children:"Set your sitemap URL"}),e.jsx("p",{className:"mt-1 text-xs text-amber-400/70",children:"Canonry uses your sitemap to discover URLs for index coverage inspection. Auto-discover from GSC or enter it manually."}),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(C,{type:"button",size:"sm",disabled:Vt.isPending||!fe.propertyId,onClick:Z(rn),children:Vt.isPending?"Discovering…":"Auto-discover from GSC"}),e.jsx("span",{className:"self-center text-xs text-amber-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-amber-800/40 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-500 focus:border-amber-600 focus:outline-none",type:"url",placeholder:"https://example.com/sitemap.xml",value:Ie,onChange:c=>Ye(c.target.value),onKeyDown:c=>c.key==="Enter"&&void ss()}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:tt||!Ie.trim(),onClick:Z(ss),children:tt?"Saving…":"Save sitemap URL"})]})]})]})]})}),(fe||xi)&&e.jsxs(e.Fragment,{children:[e.jsxs(Q,{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:[I&&I.notIndexed.length>0&&e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:dt,onClick:()=>{mi()},children:dt?"Requesting…":`Request indexing (${I.notIndexed.length})`}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:We,onClick:()=>{nn()},children:We?"Loading…":"Refresh coverage"})]})]}),I&&I.summary.total>0?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-6 flex flex-col items-center",children:(()=>{const c=I.summary.indexed+I.summary.notIndexed,v=c>0?I.summary.indexed/c:0,X=c>0?I.summary.notIndexed/c:0,ie=54,Se=2*Math.PI*ie,Ee=Se*(1-v),Qe=Se*X,At=Se*v;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:ie,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ie,fill:"none",stroke:fs.positiveDeep,strokeWidth:"14",strokeDasharray:Se,strokeDashoffset:Ee,strokeLinecap:"round",transform:"rotate(-90 64 64)",style:{transition:"stroke-dashoffset 0.6s ease"}}),I.summary.notIndexed>0&&e.jsx("circle",{cx:"64",cy:"64",r:ie,fill:"none",stroke:Be.textFaint,strokeWidth:"14",strokeDasharray:`${Qe} ${Se-Qe}`,strokeDashoffset:-At,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-zinc-50",children:[(v*100).toFixed(0),"%"]}),e.jsx("span",{className:"text-xs uppercase tracking-widest text-zinc-500 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-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:I.summary.indexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Indexed"})]})]}),e.jsx("div",{className:"h-8 w-px bg-zinc-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-zinc-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:I.summary.notIndexed.toLocaleString()}),e.jsxs("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:["Not indexed",(I.reasonGroups??[]).length>0&&e.jsxs("span",{className:"ml-1 text-zinc-600",children:["· ",(I.reasonGroups??[]).length," ",(I.reasonGroups??[]).length===1?"reason":"reasons"]})]})]})]}),I.summary.deindexed>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-px bg-zinc-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-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold tabular-nums text-zinc-50",children:I.summary.deindexed.toLocaleString()}),e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Deindexed"})]})]})]})]})]})})()}),e.jsx("div",{className:"mt-3 flex gap-1",children:["indexed","notIndexed","deindexed"].map(c=>{const v=c==="indexed"?I.indexed.length:c==="notIndexed"?I.notIndexed.length:I.deindexed.length,X=c==="indexed"?"Indexed":c==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${ze===c?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Oe(c),nt(null)},children:[X," (",v,")"]},c)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[ze==="indexed"&&I.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:Kt.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.crawlTime?c.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:c.isMobileFriendly===!0?"Yes":c.isMobileFriendly===!1?"No":"—"})]},c.id))})]}),ze==="notIndexed"&&!ce&&(I.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:(I.reasonGroups??[]).map(c=>e.jsxs("tr",{className:"cursor-pointer hover:bg-zinc-800/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400",onClick:()=>nt(c.reason),onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),nt(c.reason))},tabIndex:0,role:"button","aria-label":`View ${c.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:c.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.count})]},c.reason))})]}),ze==="notIndexed"&&!ce&&(I.reasonGroups??[]).length===0&&I.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:ge.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"})]},c.id))})]}),ze==="notIndexed"&&ce&&(()=>{const c=(I.reasonGroups??[]).find(v=>v.reason===ce);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-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>nt(null),children:["←"," Back to reasons"]})}),e.jsxs("div",{className:"mb-3 flex items-center justify-between rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:c.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[c.count," affected page",c.count!==1?"s":""]})]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:dt,onClick:()=>{an(c.urls.map(v=>v.url))},children:dt?"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"}),e.jsx("th",{className:"w-8"})]})}),e.jsx("tbody",{children:kt.map(v=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:v.url}),e.jsx("td",{className:"text-zinc-400",children:v.crawlTime?v.crawlTime.split("T")[0]:"—"}),e.jsx("td",{children:e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-200 transition-colors",disabled:dt,onClick:()=>{an([v.url])},title:"Request indexing",children:"Index"})})]},v.id))})]})]}):null})(),ze==="deindexed"&&I.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:Ue.map((c,v)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState}),e.jsx("td",{className:"text-zinc-400",children:c.currentState}),e.jsx("td",{className:"text-zinc-400",children:c.transitionDate.split("T")[0]})]},`${c.url}-${v}`))})]}),(ze==="indexed"&&I.indexed.length===0||ze==="notIndexed"&&!ce&&I.notIndexed.length===0||ze==="deindexed"&&I.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-zinc-500",children:"No URLs in this category."}),_&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 text-xs text-zinc-400",children:[e.jsxs("p",{className:"tabular-nums",children:["Showing ",e.jsx("span",{className:"text-zinc-300",children:J.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:Ze.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:yt.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>Qt(c=>Math.max(1,c-1)),disabled:N<=1,"aria-label":"Previous page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:[e.jsx(Lr,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:N})," of"," ",e.jsx("span",{className:"text-zinc-200",children:_e})]}),e.jsxs("button",{type:"button",onClick:()=>Qt(c=>Math.min(_e,c+1)),disabled:N>=_e,"aria-label":"Next page",className:"inline-flex items-center gap-1 rounded-md border border-zinc-800 bg-zinc-950 px-2.5 py-1.5 text-zinc-200 transition hover:border-zinc-700 hover:text-zinc-50 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-zinc-800 disabled:hover:text-zinc-200",children:["Next",e.jsx(vs,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:We?"Loading coverage data…":"No coverage data yet. Inspect your sitemap to populate this view."})]}),e.jsxs(Q,{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:pc.map(c=>e.jsx("button",{type:"button",role:"tab","aria-selected":S===c,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${S===c?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>P(c),children:c==="all"?"All":c},c))}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:be,onClick:()=>{ae(0),Ct(0),ks()},children:be?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const c=d.daily,v=Math.max(...c.map(me=>me.impressions),1),{clicks:X,impressions:ie,ctr:Se}=d.totals,Ee=(Se*100).toFixed(1),Qe=700,At=220,Ke={top:12,bottom:36,left:48,right:12},ji=Qe-Ke.left-Ke.right,Lt=At-Ke.top-Ke.bottom,Ht=ji/c.length,ns=Math.max(Math.min(Ht*.35,24),4),dn=Math.max(ns*.15,1),bi=me=>{if(me<=0)return 1;const at=Math.pow(10,Math.floor(Math.log10(me))),Ve=me/at,xt=Ve<=1.5?1.5:Ve<=3?3:Ve<=5?5:10;return Math.ceil(xt*at)},is=4,as=Math.ceil(bi(v)/is)*is,yi=Array.from({length:is+1},(me,at)=>as/is*at),vi=me=>me>=1e3?`${(me/1e3).toFixed(me>=1e4?0:1)}k`:String(me);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-emerald-500"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Clicks ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:X.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-blue-400"}),e.jsxs("span",{className:"text-xs text-zinc-400",children:["Impressions ",e.jsx("span",{className:"text-zinc-200 tabular-nums font-medium",children:ie.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[Ee,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Qe} / ${At}`},children:e.jsxs("svg",{viewBox:`0 0 ${Qe} ${At}`,className:"h-full w-full",children:[yi.map((me,at)=>{const Ve=Ke.top+Lt-me/as*Lt;return e.jsxs("g",{children:[e.jsx("line",{x1:Ke.left,y1:Ve,x2:Qe-Ke.right,y2:Ve,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:Ke.left-6,y:Ve+3.5,textAnchor:"end",fill:Be.text,fontSize:"10",fontFamily:"inherit",children:vi(me)})]},`t-${at}`)}),c.map((me,at)=>{const Ve=Ke.left+Ht*at+Ht/2,xt=me.impressions/as*Lt,rs=me.clicks/as*Lt;return e.jsxs("g",{children:[e.jsx("title",{children:`${me.date}
2
+ Clicks: ${me.clicks}
3
+ Impressions: ${me.impressions}
4
+ CTR: ${(me.ctr*100).toFixed(1)}%`}),e.jsx("rect",{x:Ve-ns-dn/2,y:Ke.top+Lt-xt,width:ns,height:Math.max(xt,1),rx:2,fill:Ge[1],opacity:.85}),e.jsx("rect",{x:Ve+dn/2,y:Ke.top+Lt-rs,width:ns,height:Math.max(rs,1),rx:2,fill:fs.positiveDeep,opacity:.85})]},me.date)}),(()=>{const me=Math.min(c.length,7);return Array.from({length:me},(at,Ve)=>{const xt=c.length===1?0:Math.round(Ve/(me-1)*(c.length-1)),rs=Ke.left+Ht*xt+Ht/2;return e.jsx("text",{x:rs,y:At-8,textAnchor:"middle",fill:Be.textDim,fontSize:"10",fontFamily:"inherit",children:c[xt].date.slice(5)},`xl-${xt}`)})})()]})})]})})(),e.jsxs("div",{className:"mt-3 grid gap-2 lg:grid-cols-5",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"date","aria-label":"Start date",title:"Start date (inclusive). Leave blank to use the window above.",value:B.startDate,onChange:c=>w(v=>({...v,startDate:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"date","aria-label":"End date",title:"End date (inclusive).",value:B.endDate,onChange:c=>w(v=>({...v,endDate:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:B.query,onChange:c=>w(v=>({...v,query:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:B.page,onChange:c=>w(v=>({...v,page:c.target.value}))}),e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-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:B.limit,onChange:c=>w(v=>({...v,limit:c.target.value}))})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Query and page filters match case-insensitive substrings. Click Apply filters to run. When a filter or column sort is active, up to ",xs.toLocaleString()," matching rows load so sorting covers the full set."]}),p.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(Nt).map(c=>e.jsx("th",{className:"text-right","aria-sort":Fe?.key===c?Fe.dir==="asc"?"ascending":"descending":"none",children:e.jsxs("button",{type:"button",className:"w-full cursor-pointer select-none text-right hover:text-zinc-200 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-400 rounded px-1 -mx-1",onClick:()=>ot(v=>v?.key===c?v.dir==="desc"?{key:c,dir:"asc"}:null:{key:c,dir:"desc"}),children:[Gi[c],Fe?.key===c?Fe.dir==="desc"?" ↓":" ↑":""]})},c))]})}),e.jsx("tbody",{children:V.map((c,v)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-400",children:c.date}),e.jsx("td",{className:"max-w-xs truncate text-zinc-200",children:c.query}),e.jsx("td",{className:"max-w-xs truncate text-zinc-400",children:c.page}),e.jsx("td",{className:"text-right tabular-nums text-zinc-300",children:c.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-400",children:[(Number.isFinite(c.ctr)?c.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:c.position.toFixed(1)})]},`${c.date}:${c.query}:${c.page}:${v}`))})]})}),he?e.jsx("div",{className:"mt-3 text-xs text-zinc-500",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",W.toLocaleString()," matching row",W===1?"":"s",W>=xs?` (capped at ${xs.toLocaleString()} — narrow the filter to see more)`:""]})}):(Y>0||pe)&&(()=>{const c=parseInt(B.limit,10)||20,v=Y+1,X=Y+p.length;return e.jsxs("div",{className:"mt-3 flex items-center justify-between text-xs text-zinc-500",children:[e.jsxs("span",{className:"tabular-nums",children:["Showing ",v.toLocaleString()," – ",X.toLocaleString(),pe?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:be||Y===0,onClick:()=>{const ie=Math.max(0,Y-c);ae(ie),Ct(ie)},children:"Previous"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:be||!pe,onClick:()=>{const ie=Y+c;ae(ie),Ct(ie)},children:"Next"})]})]})})()]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No performance rows match the current filters yet."})]}),e.jsxs(Q,{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"})]})}),e.jsxs("div",{className:"mt-3 flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://example.com/page",value:j,onChange:c=>x(c.target.value),onKeyDown:c=>c.key==="Enter"&&void on()}),e.jsx(C,{type:"button",size:"sm",disabled:Ae||!fe?.propertyId||!j.trim(),onClick:Z(on),children:Ae?"Inspecting…":"Inspect URL"})]}),$&&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-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Indexing state"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:$.indexingState??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Verdict"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:$.verdict??"Unknown"})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Mobile friendly"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:xn($.isMobileFriendly??null)})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last crawl"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:Xe($.crawlTime)})]})]})]}),e.jsxs(Q,{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.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:xe,onClick:()=>{ts()},children:xe?"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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"Filter exact URL",value:O,onChange:c=>H(c.target.value)}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:xe,onClick:()=>{ts()},children:"Apply filter"})]}),L.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:L.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-300",children:c.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:c.coverageState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:xn(c.isMobileFriendly??null)}),e.jsx("td",{className:"text-zinc-400",children:Xe(c.inspectedAt)})]},c.id))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No inspection history yet."})]}),e.jsxs(Q,{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"})]})}),b.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:b.map(c=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:c.url}),e.jsx("td",{className:"text-zinc-400",children:c.previousState??"Unknown"}),e.jsx("td",{className:"text-zinc-300",children:c.currentState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Xe(c.transitionDate)})]},`${c.url}:${c.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No deindexed transitions recorded."})]})]}),fe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-zinc-800/60 pt-3",children:e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 text-left",onClick:()=>Ut(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-zinc-500 transition-transform ${zt?"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-zinc-500",children:"Setup & Configuration"})]})}),zt&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid gap-3 xl:grid-cols-2",children:[e.jsxs(Q,{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-zinc-500",htmlFor:`gsc-property-${t}`,children:"Property URL"}),e.jsx("select",{id:`gsc-property-${t}`,className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:R,disabled:ne||u.length===0,onChange:c=>y(c.target.value),children:u.length===0?e.jsx("option",{value:"",children:ne?"Loading properties…":"No properties available"}):u.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.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:ne,onClick:()=>{sn(fe)},children:ne?"Refreshing…":"Refresh properties"}),e.jsx(C,{type:"button",size:"sm",disabled:!R||je,onClick:Z(gi),children:je?"Saving…":"Save property"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"The selected property is used for future syncs and URL inspections for this project."})]})]}),e.jsxs(Q,{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-zinc-500",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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",value:T,onChange:c=>q(c.target.value)})]}),e.jsxs("label",{className:"flex items-center gap-2 rounded border border-zinc-800/60 bg-zinc-900/20 px-3 py-2 text-sm text-zinc-300",children:[e.jsx("input",{type:"checkbox",checked:E,onChange:c=>G(c.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(C,{type:"button",size:"sm",disabled:zs.isPending||!fe.propertyId,onClick:Z(fi),children:zs.isPending?"Queueing…":"Queue sync"}),!fe.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property before queueing a sync."})]})]})]}),e.jsxs(Q,{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:[fe.sitemapUrl&&e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Current sitemap URL"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200 break-all",children:fe.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:jt||!fe.propertyId,onClick:()=>{ui()},children:jt?"Loading…":"Browse sitemaps from GSC"}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:Vt.isPending||!fe.propertyId,onClick:Z(rn),children:Vt.isPending?"Discovering…":"Auto-discover and queue inspection"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:"Browse lists available sitemaps without queueing a run. Auto-discover saves the primary sitemap and queues an inspection."}),qe&&qe.length>0&&e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3 space-y-2",children:[e.jsxs("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:["Sitemaps (",qe.length,")"]}),qe.map(c=>{const v=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-zinc-200 break-all",children:c.path}),c.lastSubmitted&&e.jsxs("p",{className:"text-zinc-500",children:["Submitted: ",c.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[v&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-zinc-300",children:[v.indexed," / ",v.submitted]}),e.jsx("p",{className:"text-zinc-500",children:"indexed"})]}),e.jsx("button",{type:"button",className:"text-xs text-zinc-400 hover:text-zinc-200 transition-colors",onClick:()=>Ye(c.path),children:"Use"})]})]},c.path)})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:fe.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Ie,onChange:c=>Ye(c.target.value),onKeyDown:c=>c.key==="Enter"&&Ie.trim()&&void ss()}),e.jsx(C,{type:"button",size:"sm",disabled:tt||!Ie.trim(),onClick:Z(ss),children:tt?"Saving…":fe.sitemapUrl?"Update":"Save"})]}),e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"Sitemap URL for inspection (leave empty for saved default)",id:`gsc-sitemap-inspect-${t}`}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:Ss.isPending||!fe.propertyId,onClick:Z(async()=>{const v=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||fe.sitemapUrl||void 0;oe(null),it(null);try{await Ss.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:v}})}catch{}}),children:Ss.isPending?"Queueing…":"Inspect sitemap"})]}),!fe.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}function fc({projectName:t,projectId:s}){const n=ft(),[i,a]=r.useState(null),[l,o]=r.useState(!1),u=$e(Ks({client:U,path:{name:t}})),m=u.data?.find(w=>w.connectionType==="gbp"),p=!!m,f=i?{locationName:i}:void 0,d=$e({...ta({client:U,path:{name:t}}),enabled:p}),A=$e({...sa({client:U,path:{name:t},query:f}),enabled:p}),L=$e({...na({client:U,path:{name:t},query:f}),enabled:p}),D=$e({...ia({client:U,path:{name:t},query:f}),enabled:p}),b=$e({queryKey:["gbp-section-insights",t],queryFn:()=>aa(t),enabled:p});function k(){n.invalidateQueries({predicate:w=>{const Y=w.queryKey[0];return typeof Y?._id=="string"&&Y._id.startsWith("getApiV1ProjectsByNameGbp")}})}const $=Jt({...ca(),onSuccess:w=>{ra({id:w.runId,projectId:s,kind:ps["gbp-sync"],projectLabel:t,sourceAction:"gbp-sync"}),ee({title:"Business Profile sync started",detail:`${t} will refresh when the sync completes.`,tone:"neutral",dedupeKey:`gbp-sync:${t}`,dedupeMode:"replace"})}}),M=r.useSyncExternalStore(la,un,un),R=Object.values(M.runs).some(w=>w.kind===ps["gbp-sync"]&&w.projectId===s),y=$.isPending||R,j=Jt({...oa(),onSuccess:()=>k()});if(r.useEffect(()=>{if(!i||!d.data)return;const w=d.data.locations.filter(Y=>Y.selected);(w.length<=1||!w.some(Y=>Y.locationName===i))&&a(null)},[i,d.data]),u.isLoading)return null;if(!m){const w=[{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-zinc-900/80 px-1 py-0.5 font-mono text-[11px] text-zinc-400",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-zinc-900/80 px-1 py-0.5 font-mono text-[11px] text-zinc-400",children:["canonry schedule set ",t," --kind gbp-sync --preset daily"]})]})}];return e.jsx("section",{className:"page-section-divider",children:e.jsxs(Q,{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-zinc-500",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:w.map((Y,ae)=>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-zinc-800 text-xs font-medium tabular-nums text-zinc-300","aria-hidden":"true",children:ae+1}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-200",children:Y.title}),e.jsx("code",{className:"mt-1.5 inline-block w-fit max-w-full overflow-x-auto rounded bg-zinc-900/80 px-2 py-1 font-mono text-xs text-zinc-300",children:Y.command}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-zinc-500",children:Y.note})]})]},Y.title))})]})})}const x=A.data,T=d.data?.locations??[],q=T.filter(w=>w.selected),E=L.data?.keywords??[],G=D.data?.places??[],S=T.length>0?T[0].accountName:m.domain,P=i?T.find(w=>w.locationName===i)?.displayName??null:null,B=(b.data??[]).filter(w=>!w.dismissed&&(w.type==="gbp-listing-discrepancy"||w.type==="gbp-lodging-gap")&&(!P||w.query===i||w.title.startsWith(P)));return e.jsx("section",{className:"page-section-divider",children:e.jsxs(Q,{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(Ne,{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(se,{tone:"positive",children:"Connected"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:y,onClick:()=>$.mutate({client:U,path:{name:t},body:{}}),children:y?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-zinc-500",children:[S?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-zinc-400",children:S})," · "]}):null,d.data?`${d.data.totalSelected} of ${d.data.totalDiscovered} locations tracked`:"Loading locations…"]}),q.length>1&&e.jsxs("div",{className:"mb-5 flex flex-wrap gap-1.5",role:"tablist","aria-label":"Location",children:[e.jsx(zn,{label:"All locations",active:i===null,onClick:()=>a(null)}),q.map(w=>e.jsx(zn,{label:w.displayName,active:i===w.locationName,onClick:()=>a(w.locationName)},w.id))]}),q.length===0?e.jsxs("p",{className:"text-sm text-zinc-500",children:["No locations are tracked yet. Open ",e.jsx("span",{className:"font-medium text-zinc-300",children:"Manage locations"})," below to track the one(s) for this business."]}):e.jsxs(e.Fragment,{children:[B.length>0&&e.jsx("div",{className:"mb-6 grid gap-2",children:B.map(w=>e.jsx("div",{className:"insight-card insight-card-negative rounded-r-lg border border-zinc-800/60 bg-zinc-900/30 p-3 pl-4",children:e.jsxs("p",{className:"flex items-center gap-2 text-sm font-medium text-zinc-200",children:[w.title,w.recommendation?.reason&&e.jsx(Ne,{text:w.recommendation.reason})]})},w.id))}),x&&e.jsx(jc,{performance:x.performance,freshness:x.freshness,timeseries:x.timeseries}),G.length>0&&e.jsxs("div",{className:"mb-6",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Public listing · Google Maps"}),e.jsx("div",{className:"grid gap-2",children:G.map(w=>{const Y=T.find(ae=>ae.locationName===w.locationName);return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:Y?.displayName??w.locationName}),e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[w.amenities.length," amenit",w.amenities.length===1?"y":"ies"," advertised"]})]}),w.amenities.length>0?e.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:w.amenities.map(ae=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 px-2 py-0.5 text-[11px] text-zinc-400",children:ae},ae))}):e.jsx("p",{className:"mt-1 text-sm text-zinc-500",children:"Public listing advertises no structured amenities."}),Y?.mapsUri&&e.jsx("a",{href:Y.mapsUri,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-block text-[11px] text-zinc-500 hover:text-zinc-300",children:"View on Google Maps →"})]},w.locationName)})})]}),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"}),L.data&&L.data.total>0&&e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[L.data.thresholdedPct,"% privacy-thresholded"]})]}),E.length===0?e.jsx("p",{className:"text-sm text-zinc-500",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"}),e.jsx("th",{className:"text-right",children:"Impressions"}),e.jsx("th",{className:"text-right",children:"Window"})]})}),e.jsx("tbody",{children:E.slice(0,25).map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-300",children:w.keyword}),e.jsx("td",{className:"text-right font-mono text-zinc-200",children:w.valueCount!==null?w.valueCount.toLocaleString():e.jsxs("span",{className:"text-zinc-500",title:"Privacy floor — Google withheld the exact count",children:["<",w.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-zinc-600",children:[w.periodStart,"–",w.periodEnd]})]},`${w.locationName}:${w.keyword}`))})]})]})]}),e.jsxs("div",{className:"mt-6 border-t border-zinc-800/60 pt-4",children:[e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-xs font-medium text-zinc-400 hover:text-zinc-200",onClick:()=>o(w=>!w),"aria-expanded":l,children:[e.jsx("span",{"aria-hidden":"true",children:l?"▾":"▸"})," Manage locations (",T.length,")"]}),l&&e.jsx("div",{className:"mt-3",children:T.length===0?e.jsxs("p",{className:"text-sm text-zinc-500",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"}),e.jsx("th",{className:"text-right",children:"Action"})]})}),e.jsx("tbody",{children:T.map(w=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-200",children:w.displayName}),e.jsx("td",{className:"text-zinc-500",children:w.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(se,{tone:w.selected?"positive":"neutral",children:w.selected?"Tracked":"Not tracked"})}),e.jsx("td",{className:"text-right",children:e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:j.isPending,onClick:()=>j.mutate({client:U,path:{name:t,locationName:w.locationName},body:{selected:!w.selected}}),children:w.selected?"Untrack":"Track"})})]},w.id))})]})})]})]})})}function zn({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-zinc-500 bg-zinc-800 text-zinc-100":"border-zinc-700/60 text-zinc-400 hover:border-zinc-600 hover:text-zinc-200"}`,children:t})}function jc({performance:t,freshness:s,timeseries:n}){const i=t.totals,a=da.filter(D=>(i[D]??0)>0),l=xa.filter(D=>(i[D]??0)>0),o=Object.keys(i).filter(D=>(i[D]??0)>0&&ma(D)==="other").sort((D,b)=>(i[b]??0)-(i[D]??0)),u=Object.keys(i).filter(D=>(i[D]??0)===0).sort(),m=n.map(D=>{const b={date:D.date};for(const[k,$]of Object.entries(D.metrics))b[k]=$;return b}),p=n.find(D=>D.pending)?.date,f=n.length>0?n[n.length-1].date:void 0,d=m.length>0,A=s.dataThroughDate?`Data through ${wt(s.dataThroughDate)}${s.pendingDays>0?` · ${s.pendingDays}d pending`:""}`:null,L=[...a,...o];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:"Conversions · daily"}),A&&e.jsx("span",{className:"text-[11px] text-zinc-500",children:A})]}),!d||a.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No conversion activity yet — run a sync."}):e.jsxs(e.Fragment,{children:[e.jsx(Sn,{data:m,metrics:a,kind:"line",firstPending:p,lastDate:f}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-x-5 gap-y-1",children:L.map(D=>e.jsxs("span",{className:"text-sm text-zinc-400",children:[gs(D)," ",e.jsx("span",{className:"font-mono text-zinc-100",children:(i[D]??0).toLocaleString()})]},D))})]})]}),d&&l.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Reach · impressions, daily"}),e.jsx(Sn,{data:m,metrics:l,kind:"area",firstPending:p,lastDate:f})]}),u.length>0&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Not active: ",u.map(D=>gs(D)).join(", ")]})]})}function Sn({data:t,metrics:s,kind:n,firstPending:i,lastDate:a}){return e.jsx("div",{className:"h-48 w-full",children:e.jsx(Ot,{width:"100%",height:"100%",children:e.jsxs(Ft,{data:t,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Hs,{stroke:Vs,vertical:!1}),e.jsx(Gt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:rt},tickFormatter:Mt,minTickGap:24}),e.jsx(Bt,{tick:He,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(qt,{...gt,labelFormatter:wt,formatter:(l,o)=>[typeof l=="number"?l.toLocaleString():String(l??0),gs(String(o??""))]}),e.jsx(Zn,{wrapperStyle:{fontSize:11,color:Be.text},formatter:l=>gs(l)}),i&&a&&e.jsx(Ir,{x1:i,x2:a,fill:Be.surface,fillOpacity:.55,stroke:"none",label:{value:"pending",position:"insideTopRight",fill:Be.textDim,fontSize:10}}),s.map((l,o)=>n==="line"?e.jsx(Ws,{type:"monotone",dataKey:l,stroke:Ge[o%Ge.length],strokeWidth:2,dot:!1,isAnimationActive:!1},l):e.jsx($t,{type:"monotone",dataKey:l,stackId:"reach",stroke:Ge[o%Ge.length],fill:Ge[o%Ge.length],fillOpacity:.25,strokeWidth:1.5,isAnimationActive:!1},l))]})})})}function $s({children:t,label:s="More info",placement:n="top",className:i}){const a=r.useId(),[l,o]=r.useState(!1);return e.jsxs("span",{className:`relative inline-flex ${i??""}`,children:[e.jsx("button",{type:"button","aria-label":s,"aria-describedby":l?a:void 0,className:"inline-flex h-4 w-4 items-center justify-center rounded-full text-zinc-500 hover:text-zinc-200 focus:text-zinc-200 focus:outline-none focus-visible:ring-1 focus-visible:ring-zinc-500",onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onFocus:()=>o(!0),onBlur:()=>o(!1),children:e.jsx(Rr,{className:"h-3.5 w-3.5","aria-hidden":!0})}),l&&e.jsx("span",{id:a,role:"tooltip",className:`absolute z-50 w-64 rounded border border-zinc-700 bg-zinc-900 px-3 py-2 text-xs font-normal leading-relaxed text-zinc-200 shadow-lg ${n==="top"?"bottom-full mb-2":"top-full mt-2"} left-1/2 -translate-x-1/2 whitespace-normal`,children:t})]})}const vt=50;function Dt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function ms(t){return t.toLocaleString()}function bc(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function yc(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 i=Math.floor(n/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function vc(t){const s=t.filter(n=>n.kind===ps["backlink-extract"]&&!_n(n.status));return s.length===0?null:s.reduce((n,i)=>n.createdAt>i.createdAt?n:i)}function Nc(t,s){const n=new Date(t??s).getTime(),i=Math.max(0,Math.floor((Date.now()-n)/1e3));if(i<60)return`${i}s`;const a=Math.floor(i/60),l=i%60;return l===0?`${a}m`:`${a}m ${l}s`}function wc({projectName:t}){const[s,n]=r.useState(null),[i,a]=r.useState(null),[l,o]=r.useState([]),[u,m]=r.useState(null),[p,f]=r.useState(null),[d,A]=r.useState(null),[L,D]=r.useState(Date.now()),[b,k]=r.useState(0),[$,M]=r.useState(!0),[R,y]=r.useState(!1),[j,x]=r.useState(null),T=r.useRef(null),q=r.useCallback(async()=>{M(!0),x(null);try{const[K,W,de,he,g]=await Promise.all([ua().catch(()=>null),ha(t,{excludeCrawlers:!0}).catch(()=>null),pa(t,{limit:vt,offset:b,excludeCrawlers:!0}).catch(H=>{if(H instanceof qs&&H.code==="NOT_FOUND")return null;throw H}),ga(t).catch(()=>[]),fa(t).catch(()=>[])]);m(K),n(W),a(de),o(he);const O=vc(g);f(O),T.current=O?.id??null}catch(K){x(K instanceof Error?K.message:"Failed to load backlinks")}finally{M(!1)}},[t,b]);r.useEffect(()=>{q()},[q]),r.useEffect(()=>{if(!p)return;const K=p.id;let W=!1;const de=async()=>{try{const g=await Un(K);if(W)return;_n(g.status)?(f(null),A(g),await q()):f(O=>O?.id===g.id?{...O,...g}:O)}catch{}},he=window.setInterval(()=>{de()},3e3);return()=>{W=!0,window.clearInterval(he)}},[p,q]),r.useEffect(()=>{if(!p)return;const K=window.setInterval(()=>D(Date.now()),1e3);return()=>window.clearInterval(K)},[p]),r.useEffect(()=>{if(!d||d.status==="failed")return;const K=window.setTimeout(()=>A(null),1e4);return()=>window.clearTimeout(K)},[d]);async function E(){y(!0),x(null);try{const K=await va(t);f(K),T.current=K.id}catch(K){K instanceof qs&&K.code==="MISSING_DEPENDENCY"?x("DuckDB is not installed. Visit the Backlinks admin page to install it."):x(K instanceof Error?K.message:"Failed to trigger extract")}finally{y(!1)}}const G=r.useMemo(()=>l.slice().sort((K,W)=>K.queriedAt.localeCompare(W.queriedAt)).map(K=>({date:K.queriedAt,linkingDomains:K.totalLinkingDomains})),[l]),S=i?.rows??[],P=i?.total??0,B=s?.excludedLinkingDomains??0,w=P>vt,Y=Math.floor(b/vt)+1,ae=Math.max(1,Math.ceil(P/vt));return r.useEffect(()=>{b>0&&b>=P&&k(0)},[b,P]),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-zinc-500 mt-1 max-w-2xl",children:["Domains linking to "," ",e.jsx("span",{className:"text-zinc-300",children:t}),", extracted from the Common Crawl hyperlink graph. Updates when a release sync completes — no live scraping, no paid API."]})]})}),j&&e.jsx(Q,{className:"surface-card p-4 mb-4 border-rose-800/60",children:e.jsx("p",{className:"text-sm text-rose-300",children:j})}),p&&e.jsx(Q,{className:"surface-card p-4 mb-4 border-sky-800/60",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ja,{className:"h-5 w-5 text-sky-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-zinc-100",children:"Extract running"}),e.jsx(se,{tone:"neutral",children:p.status}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:[Nc(p.startedAt??null,p.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",L]})]}),e.jsxs("p",{className:"text-xs text-zinc-500 mt-1",children:["Re-querying the cached Common Crawl release for"," ",e.jsx("span",{className:"text-zinc-300",children:t}),". No re-download — the ~16 GB dump already lives at"," ",e.jsx("code",{className:"text-zinc-400",children:"~/.canonry/cache/commoncrawl/"}),". Typically takes ~5 minutes."]})]})]})}),d&&!p&&e.jsx(Q,{className:`surface-card p-4 mb-4 ${d.status==="failed"?"border-rose-800/60":"border-emerald-800/60"}`,children:e.jsxs("div",{className:"flex items-start gap-3",children:[d.status==="failed"?e.jsx("span",{className:"h-5 w-5 shrink-0 mt-0.5 text-rose-400 text-lg leading-none","aria-hidden":!0,children:"!"}):e.jsx(ei,{className:"h-5 w-5 text-emerald-400 shrink-0 mt-0.5","aria-hidden":!0}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:`text-sm font-medium ${d.status==="failed"?"text-rose-300":"text-emerald-300"}`,children:d.status==="failed"?"Extract failed":"Extract complete"}),d.error?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:ba(d.error)}):d.status!=="failed"?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),pe()]});function pe(){if($)return e.jsx(Q,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading backlinks…"})});const K=s!==null&&s.totalLinkingDomains>0,W=d?.status==="failed",de=s!==null&&s.totalLinkingDomains===0&&!W,he=u?.status==="ready",g=u?.status==="failed",O=u&&(u.status==="downloading"||u.status==="querying"||u.status==="queued");return K?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-zinc-50",children:ms(s.totalLinkingDomains)})}),e.jsxs("p",{className:"metric-card-sub",children:["unique domains linking to ",s.targetDomain]})]}),e.jsxs("div",{className:"metric-card",children:[e.jsx("p",{className:"metric-card-eyebrow",children:"Total linking hosts"}),e.jsx("p",{className:"metric-card-big-value",children:e.jsx("span",{className:"text-zinc-50",children:ms(s.totalHosts)})}),e.jsx("p",{className:"metric-card-sub",children:"aggregate host count 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-zinc-50",children:bc(s.top10HostsShare)})}),e.jsx("p",{className:"metric-card-sub",children:"share of hosts from the 10 largest linking domains"})]})]}),e.jsxs("p",{className:"text-xs text-zinc-600 mt-2",children:["Release ",e.jsx("code",{className:"text-zinc-400",children:s.release})," · queried ",yc(s.queriedAt),B>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-zinc-500",children:[B," crawler/proxy domain",B===1?"":"s"," hidden"]})]})]}),G.length>=2&&e.jsxs(Q,{className:"surface-card p-4 mt-4",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Referring domains over releases"}),e.jsx("div",{className:"h-40 mt-2",children:e.jsx(Ot,{width:"100%",height:"100%",children:e.jsxs(Ft,{data:G,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:Ge[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:Ge[0],stopOpacity:0})]})}),e.jsx(Gt,{dataKey:"date",tick:He,stroke:rt,tickFormatter:Mt}),e.jsx(Bt,{tick:He,stroke:rt,allowDecimals:!1}),e.jsx(qt,{contentStyle:gt.contentStyle,labelStyle:gt.labelStyle,itemStyle:gt.itemStyle,labelFormatter:wt}),e.jsx($t,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:Ge[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"}),w&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Page ",Y," of ",ae," · ",ms(P)," total"]})]}),e.jsx(Q,{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-zinc-800 text-left text-xs uppercase tracking-wide text-zinc-600",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:"Linking hosts"})]})}),e.jsxs("tbody",{children:[S.map(H=>e.jsxs("tr",{className:"border-b border-zinc-900 last:border-0",children:[e.jsx("td",{className:"px-4 py-2 text-zinc-200",children:H.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-zinc-400 tabular-nums",children:ms(H.numHosts)})]},H.linkingDomain)),S.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-zinc-500",colSpan:2,children:B>0&&P===0?`Every referring domain in this release was a crawler/proxy host (${B} hidden).`:"No referring domains in this release."})})]})]})}),w&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:b===0,onClick:()=>k(H=>Math.max(0,H-vt)),children:"Previous"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:b+vt>=P,onClick:()=>k(H=>H+vt),children:"Next"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(C,{type:"button",variant:"outline",size:"sm",disabled:R||p!==null,onClick:Z(E),children:[e.jsx(Ys,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),p?"Extract running…":R?"Queuing…":"Re-run extract"]}),e.jsxs($s,{label:"What does Re-run extract do?",children:[e.jsxs("span",{className:"block",children:["Re-queries the ",e.jsx("span",{className:"text-zinc-200",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-zinc-300",children:"~/.canonry/cache/commoncrawl/"})," for ",e.jsx("span",{className:"text-zinc-200",children:t}),". Replaces existing backlink rows for this project under the current release."]}),e.jsxs("span",{className:"mt-2 block text-zinc-400",children:[e.jsx("span",{className:"text-zinc-200",children:"No re-download"})," of the ~16 GB dump. Typically ",e.jsx("span",{className:"text-zinc-200",children:"~5 min"}),"."]})]}),e.jsx(C,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Dt("/backlinks"),children:"Open admin"})})]})]}):e.jsx(Q,{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-zinc-900 text-zinc-400",children:e.jsx(ya,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!u&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No release sync yet"}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:"Run a workspace release sync to populate backlinks for every project in this workspace."}),e.jsx("div",{className:"mt-4",children:e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dt("/backlinks"),children:"Set up backlinks"})})})]}),O&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Sync in progress"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["A workspace release sync is running (",u.status,u.phaseDetail?` — ${u.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),e.jsx("div",{className:"mt-4",children:e.jsx(C,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:Dt("/backlinks"),children:"View sync status"})})})]}),g&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Last sync failed"}),e.jsx("p",{className:"text-sm text-zinc-500 mt-1",children:u.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),e.jsx("div",{className:"mt-4",children:e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dt("/backlinks"),children:"Go to Backlinks admin"})})})]}),he&&!O&&!de&&!W&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No backlinks yet for this project"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["Release ",e.jsx("code",{className:"text-zinc-300",children:u.release})," is ready but no backlinks have been extracted for"," ",e.jsx("code",{className:"text-zinc-300",children:t}),". Run an extract to populate data using the cached release."]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(C,{type:"button",size:"sm",disabled:R||p!==null,onClick:Z(E),children:[e.jsx(Xt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),p?"Extract running…":R?"Queuing…":"Run extract"]}),e.jsxs($s,{label:"What does Run extract do?",children:[e.jsxs("span",{className:"block",children:["Runs a DuckDB query against the ",e.jsx("span",{className:"text-zinc-200",children:"cached release files"})," at"," ",e.jsx("code",{className:"text-zinc-300",children:"~/.canonry/cache/commoncrawl/"})," to find referring domains for ",e.jsx("span",{className:"text-zinc-200",children:t}),"."]}),e.jsxs("span",{className:"mt-2 block text-zinc-400",children:["No re-download. Typically takes ",e.jsx("span",{className:"text-zinc-200",children:"~5 min"}),"."]})]})]})]}),W&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"Last extract failed"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["See the error above for details. If the cache files for release"," ",e.jsx("code",{className:"text-zinc-300",children:u?.release})," are missing, re-sync the release from the Backlinks admin to restore the ~16 GB dump, then re-run the extract."]}),e.jsx("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dt("/backlinks"),children:"Go to Backlinks admin"})})})]}),de&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"text-base font-semibold text-zinc-100",children:"No referring domains found"}),e.jsxs("p",{className:"text-sm text-zinc-500 mt-1",children:["The last extract against release ",e.jsx("code",{className:"text-zinc-300",children:s.release})," found"," ",e.jsx("span",{className:"text-zinc-300",children:"0 referring domains"})," for"," ",e.jsx("code",{className:"text-zinc-300",children:s.targetDomain}),". This can happen when:"]}),e.jsxs("ul",{className:"mt-2 space-y-1 text-xs text-zinc-500 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-zinc-500 mt-3",children:"Try syncing a newer release — each Common Crawl dump is a different snapshot of the web graph."}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsx(C,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:Dt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(C,{type:"button",variant:"outline",size:"sm",disabled:R||p!==null,onClick:Z(E),children:[e.jsx(Xt,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),p?"Extract running…":R?"Queuing…":"Re-run extract"]}),e.jsxs($s,{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-zinc-200",children:s.targetDomain}),". Only useful if the cache files were incomplete last time."]}),e.jsx("span",{className:"mt-2 block text-zinc-400",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 zc({projectName:t}){const s=$e({...Na({client:U,path:{name:t}}),staleTime:Qn}),n=s.data??null,i=s.error;if(s.isLoading&&!n)return null;if(i)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-rose-400",children:i instanceof Error?i.message:String(i)})]});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-zinc-500",children:n.reason==="no-queries"?"Add queries to start tracking AI citations.":"Run a sweep to see which engines cite this project."})]});const{providersCiting:a,providersMentioning:l,providersConfigured:o}=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 ",a," of ",o," engines",e.jsx(Ne,{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-zinc-300 flex items-center gap-2",children:["Mentioned in ",l," of ",o," engine answers",e.jsx(Ne,{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(Sc,{data:n}),e.jsx(kc,{data:n}),n.competitorGaps.length>0&&e.jsx(Dc,{data:n})]})}function Sc({data:t}){const{totalQueries:s,queriesCitedAndMentioned:n,queriesCitedOnly:i,queriesMentionedOnly:a,queriesInvisible:l}=t.summary;return e.jsxs("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4 mb-4",children:[e.jsx(us,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(us,{label:"Cited only",value:`${i} / ${s}`,helper:"In sources, not named in answer",tone:i>0?"positive-dim":"neutral"}),e.jsx(us,{label:"Mentioned only",value:`${a} / ${s}`,helper:"Named in answer, no source link",tone:a>0?"caution":"neutral"}),e.jsx(us,{label:"Invisible",value:`${l} / ${s}`,helper:"No engine cites or mentions",tone:l>0?"negative":"neutral"})]})}function us({label:t,value:s,helper:n,tone:i}){const a=i==="positive"?"text-emerald-300":i==="positive-dim"?"text-emerald-400/70":i==="caution"?"text-amber-300":i==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${a}`,children:s}),e.jsx("p",{className:"text-[11px] text-zinc-500",children:n})]})}function kc({data:t}){const s=r.useMemo(()=>{const n=new Set;for(const i of t.byQuery)for(const a of i.providers)n.add(a.provider);return Array.from(n).sort()},[t.byQuery]);return t.byQuery.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No query coverage rows."}):e.jsxs("div",{children:[e.jsx(Cc,{}),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(Et,{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-zinc-100",children:n.query}),s.map(i=>{const a=n.providers.find(l=>l.provider===i);return e.jsx("td",{className:"text-center",children:a==null?e.jsx(Mr,{className:"inline h-3.5 w-3.5 text-zinc-700","aria-label":"no data"}):e.jsx(Ac,{provider:a})},i)}),e.jsx("td",{className:"text-right tabular-nums",children:e.jsxs("span",{className:n.totalProviders>0&&n.citedCount===n.totalProviders?"text-emerald-300":n.citedCount>0?"text-emerald-400/70":"text-zinc-500",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-sky-300":n.mentionedCount>0?"text-sky-400/70":"text-zinc-500",children:[n.mentionedCount,"/",n.totalProviders]})})]},n.queryId))})]})})]})}function Cc(){return e.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-3 text-[11px] text-zinc-500",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Pt,{active:!1,tone:"cited"}),e.jsx(Pt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Ac({provider:t}){const s=Lc(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(Pt,{active:t.cited,tone:"cited"}),e.jsx(Pt,{active:t.mentioned,tone:"mentioned"})]})}function Lc(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 Pt({active:t,tone:s}){if(!t)return e.jsx("span",{className:"inline-block h-2 w-2 rounded-full border border-zinc-700/80 bg-transparent","aria-hidden":"true"});const n=s==="cited"?"inline-block h-2 w-2 rounded-full bg-emerald-400 shadow-[0_0_0_1px_rgba(16,185,129,0.25)]":"inline-block h-2 w-2 rounded-full bg-sky-400 shadow-[0_0_0_1px_rgba(56,189,248,0.25)]";return e.jsx("span",{className:n,"aria-hidden":"true"})}function Dc({data:t}){return e.jsxs("div",{className:"mt-4",children:[e.jsxs("h3",{className:"text-sm font-semibold text-zinc-200 mb-2 flex items-center gap-2",children:["Competitor gaps",e.jsx(Ne,{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-zinc-500",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-zinc-100",children:s.query}),e.jsx("td",{children:e.jsx(Et,{provider:s.provider})}),e.jsx("td",{className:"text-zinc-300",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const Ns="__cited__",ws="__mentioned__";function kn(t){return Math.round(t*1e3)/10}function $c(t,s,n){const i=t.buckets.length>0,a=t.buckets.length===1;if(n==="overall"){const m=s==="cited"?Ns:ws,p=s==="cited"?"citationRate":"mentionRate";return{rows:t.buckets.map(d=>({date:d.startDate,[m]:kn(d[p])})),series:[m],hasData:i,singleBucket:a}}const l=s==="mentioned"?"mentionRate":"citationRate",o=[...new Set(t.buckets.flatMap(m=>Object.keys(m.byProvider??{})))].sort();return{rows:t.buckets.map(m=>{const p={date:m.startDate};for(const f of o){const d=m.byProvider?.[f];p[f]=d?kn(d[l]):null}return p}),series:o,hasData:i,singleBucket:a}}function Pc(t,s){for(let n=t.length-1;n>=0;n--){const i=t[n][s];if(typeof i=="number"&&Number.isFinite(i))return i}return null}function Cn(t){const[,s,n]=t.slice(0,10).split("-");return!s||!n?t:`${s}/${n}`}function An(t){return t>0?`+${t}`:`${t}`}function Ic(t){if(t.length===0)return null;if(t.length<=2)return`Query set changed: ${t.map(n=>`${An(n.delta)} on ${Cn(n.date)}`).join(", ")}`;const s=[...t].sort((n,i)=>i.date.localeCompare(n.date))[0];return`Query set changed ${t.length} times (latest ${An(s.delta)} on ${Cn(s.date)})`}const Rc=[{value:"7d",label:"7d"},{value:"30d",label:"30d"},{value:"90d",label:"90d"},{value:"all",label:"All"}],Tc=[{value:"byProvider",label:"By engine"},{value:"overall",label:"All engines"}],Ec=[{value:"mentioned",label:"Mentioned"},{value:"cited",label:"Cited"}],Mc="#18181b",Oc={claude:"Claude",openai:"OpenAI",gemini:"Gemini",perplexity:"Perplexity",local:"Local"};function Fc(t){return Oc[t]??t.charAt(0).toUpperCase()+t.slice(1)}function Ps(t){return Math.round(t*10)/10}function Gc(t){return t===Ns||t===ws}function Ln(t){return t===Ns?"Cited":t===ws?"Mentioned":Fc(t)}function Is(t,s){return t===Ns?fs.positive:t===ws?Ge[1]:Dr(t,s)}function Rs({options:t,value:s,onChange:n,ariaLabel:i,className:a}){return e.jsx("div",{role:"group","aria-label":i,className:`segmented ${a??""}`,children:t.map(l=>{const o=s===l.value;return e.jsx("button",{type:"button","aria-pressed":o,className:`segmented-option ${o?"segmented-option-active":""}`,onClick:()=>n(l.value),children:l.label},l.value)})})}function Bc({projectName:t}){const[s,n]=r.useState("all"),[i,a]=r.useState("mentioned"),[l,o]=r.useState("byProvider"),u=$e({queryKey:["analytics-metrics",t,s],queryFn:()=>wa(t,s),staleTime:Qn}),m=u.data??null,p=u.error,f=r.useMemo(()=>m?$c(m,i,l):null,[m,i,l]),d=l==="byProvider",A=i==="cited"?"citationRate":"mentionRate",L=i==="cited"?"Cited":"Mentioned",D=i==="cited"?fs.positive:Ge[1],b=d?Be.textDim:D,k=m?.buckets??[],$=k.length>0?Ps(k[k.length-1][A]*100):null,M=k.length>0?Ps(k[0][A]*100):null,R=$!==null&&M!==null&&k.length>1?Ps($-M):null,y=e.jsxs(e.Fragment,{children:[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:["Citations & mentions over time",e.jsx(Ne,{text:"How often AI engines cited your domain as a source (Cited) and named your brand in the answer text (Mentioned), across all tracked queries, over time. Each point is a sweep bucket; rates are the share of (query × provider) snapshots in that bucket."})]})]}),$!==null&&e.jsxs("div",{className:"visibility-trend-current",children:[e.jsx("span",{className:"visibility-trend-current-dot",style:{backgroundColor:b},"aria-hidden":"true"}),e.jsx("span",{className:"visibility-trend-current-label",children:L}),d&&e.jsx("span",{className:"visibility-trend-current-qualifier",children:"avg"}),e.jsxs("span",{className:"visibility-trend-current-value",children:[$,"%"]}),R!==null&&e.jsxs("span",{className:`visibility-trend-current-delta ${R>0?"text-emerald-400":R<0?"text-rose-400":"text-zinc-500"}`,children:[R>0?"+":"",R.toFixed(1)," pts"]})]})]}),e.jsxs("div",{className:"visibility-trend-controls",children:[e.jsx(Rs,{options:Ec,value:i,onChange:a,ariaLabel:"Metric"}),e.jsx(Rs,{options:Tc,value:l,onChange:o,ariaLabel:"Series"}),e.jsx(Rs,{options:Rc,value:s,onChange:n,ariaLabel:"Time window",className:"sm:ml-auto"})]})]});let j;if(p)j=e.jsx("p",{className:"text-sm text-rose-400",children:p instanceof Error?p.message:String(p)});else if(u.isLoading&&!m)j=e.jsx("div",{className:"visibility-trend-chart animate-pulse rounded-lg bg-zinc-900/40","aria-hidden":"true"});else if(!m||!f)j=null;else{const{rows:x,series:T,hasData:q,singleBucket:E}=f,G=Ic(m.queryChanges);if(!q)j=e.jsx("p",{className:"text-sm text-zinc-400",children:"Run a sweep to start tracking citations and mentions over time."});else if(l==="byProvider"&&T.length===0)j=e.jsxs("p",{className:"text-sm text-zinc-400",children:["No per-engine breakdown for this data yet. Switch to ",e.jsx("span",{className:"text-zinc-200",children:"All engines"})," to see the trend."]});else{const S=`${L} rate across ${x.length} ${x.length===1?"sweep":"sweeps"}. Latest ${$}%${R!==null?`, ${R>=0?"up":"down"} ${Math.abs(R).toFixed(1)} points over the period`:""}.`;j=e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"sr-only",children:S}),l==="byProvider"&&T.length>0&&e.jsx("ul",{className:"trend-legend","aria-label":"Engines",children:T.map((P,B)=>{const w=Pc(x,P);return e.jsxs("li",{className:"trend-legend-item",children:[e.jsx("span",{className:"trend-legend-swatch",style:{backgroundColor:Is(P,B)},"aria-hidden":"true"}),e.jsx("span",{className:"trend-legend-name",children:Ln(P)}),w!==null&&e.jsxs("span",{className:"trend-legend-value",children:[w,"%"]})]},P)})}),e.jsx("div",{className:"visibility-trend-chart",children:e.jsx(Ot,{width:"100%",height:"100%",children:e.jsxs(Ft,{data:x,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Hs,{stroke:Vs,vertical:!1}),e.jsx(Gt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:rt},tickFormatter:Mt,minTickGap:24}),e.jsx(Bt,{domain:[0,100],ticks:[0,25,50,75,100],tickFormatter:P=>`${P}%`,tick:He,tickLine:!1,axisLine:!1,width:40}),e.jsx(qt,{...gt,cursor:{stroke:rt,strokeWidth:1},labelFormatter:wt,formatter:(P,B)=>[P==null?"no data":`${P}%`,Ln(String(B))]}),T.map((P,B)=>e.jsx(Ws,{type:"monotone",dataKey:P,name:P,stroke:Is(P,B),strokeWidth:Gc(P)?2.5:2,dot:{r:2.5,fill:Is(P,B),strokeWidth:0},activeDot:{r:4,strokeWidth:2,stroke:Mc},connectNulls:!0,isAnimationActive:!1},P))]})})}),E&&e.jsx("p",{className:"visibility-trend-note",children:"Only one sweep so far. The trend line fills in after the next run."}),G&&e.jsx("p",{className:"visibility-trend-note",children:G})]})}}return e.jsxs("section",{className:"visibility-trend",children:[y,j]})}const Qs=new Set(["queued","seeding","probing"]);function qc({projectName:t}){const s=ft(),[n,i]=r.useState(null),[a,l]=r.useState(""),[o,u]=r.useState("100"),m=$e({...za({client:U,path:{name:t},query:{limit:"10"}}),refetchInterval:y=>y.state.data?.some(x=>Qs.has(x.status))?3e3:!1}),p=m.data??[];r.useEffect(()=>{!n&&p[0]&&i(p[0].id)},[n,p]);const f=p.find(y=>y.id===n)??null,d=$e({...Sa({client:U,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:f&&Qs.has(f.status)?3e3:!1}),A=d.data??null,L=$e({...ka({client:U,path:{name:t,id:n??""}}),enabled:!!(n&&f?.status==="completed")}),D=Jt({mutationFn:()=>{const y={},j=a.trim();j&&(y.icpDescription=j);const x=Number.parseInt(o,10);return Number.isFinite(x)&&x>0&&(y.maxProbes=x),Ca(t,y)},onSuccess:async y=>{i(y.sessionId),l(""),await $n(s,t,y.sessionId),ee({title:"Discovery started",detail:`Run ${Ts(y.sessionId)} is testing questions your customers might ask.`,tone:"neutral",dedupeKey:`discovery:start:${y.sessionId}`,dedupeMode:"replace"})},onError:y=>{ee({title:"Discovery failed to start",detail:y instanceof Error?y.message:"Could not start discovery.",tone:"negative"})}}),b=Jt({mutationFn:y=>{if(!n)throw new Error("Select a completed discovery session first.");return Aa(t,n,y)},onSuccess:async y=>{await $n(s,t,y.sessionId),s.invalidateQueries({queryKey:Kn({client:U})}),s.invalidateQueries({predicate:j=>Array.isArray(j.queryKey)&&j.queryKey[0]==="projects"&&j.queryKey.length>1}),ee({title:"Queries added",detail:Kc(y),tone:"positive",dedupeKey:`discovery:promote:${y.sessionId}`,dedupeMode:"replace"})},onError:y=>{ee({title:"Could not add queries",detail:y instanceof Error?y.message:"Could not add queries from this run.",tone:"negative"})}}),k=A??f,$=L.data??null,M=($?.queriesByBucket.cited.length??0)+($?.queriesByBucket.aspirational.length??0),R=r.useMemo(()=>(A?.probes??[]).slice(0,30),[A?.probes]);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:"Discovery"}),e.jsx("h2",{children:"Find new queries to track"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"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(C,{type:"button",variant:"outline",size:"sm",disabled:m.isFetching,onClick:()=>{m.refetch()},children:[e.jsx(js,{size:14}),"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(Q,{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(se,{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-zinc-500",children:"Who is your ideal customer?"}),e.jsx("textarea",{className:"mt-1 min-h-24 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"e.g. Small e-commerce stores that want AI-powered customer support. Leave blank to use the customer profile saved on this project.",value:a,onChange:y=>l(y.target.value)})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-xs text-zinc-500",children:"How many questions to test"}),e.jsx("input",{className:"mt-1 w-full rounded border border-zinc-700 bg-transparent px-3 py-2 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",inputMode:"numeric",value:o,onChange:y=>u(y.target.value)}),e.jsx("span",{className:"mt-1 block text-[11px] text-zinc-600",children:"More questions means broader coverage but a longer run. 100 is a good default."})]}),e.jsxs(C,{type:"button",size:"sm",disabled:D.isPending,onClick:()=>D.mutate(),children:[e.jsx(Xt,{size:14}),D.isPending?"Starting…":"Find queries"]})]})]}),e.jsxs(Q,{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"})]}),m.isFetching&&e.jsx(se,{tone:"neutral",children:"Loading"})]}),p.length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No discovery runs yet. Describe your customer above to start your first one."}):e.jsx("div",{className:"space-y-2",children:p.map(y=>e.jsxs("button",{type:"button",className:`w-full rounded-md border px-3 py-2 text-left transition-colors ${n===y.id?"border-zinc-600 bg-zinc-900/70":"border-zinc-800/60 bg-zinc-950/40 hover:border-zinc-700 hover:bg-zinc-900/40"}`,onClick:()=>i(y.id),children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-zinc-100",children:Ts(y.id)}),e.jsx(se,{tone:Dn(y.status),children:y.status})]}),e.jsxs("div",{className:"mt-2 grid grid-cols-3 gap-2 text-[11px] text-zinc-500",children:[e.jsxs("span",{children:["Cited ",y.citedCount??0]}),e.jsxs("span",{children:["Opportunity ",y.aspirationalCount??0]}),e.jsxs("span",{children:["Low value ",y.wastedCount??0]})]})]},y.id))})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Q,{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:k?Ts(k.id):"No run selected"})]}),k&&e.jsx(se,{tone:Dn(k.status),children:k.status})]}),k?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ut,{label:"Questions tested",value:k.probeCount??0}),e.jsx(ut,{label:"Already cited",value:k.citedCount??0,tone:"positive"}),e.jsx(ut,{label:"Opportunities",value:k.aspirationalCount??0,tone:"caution"}),e.jsx(ut,{label:"Low value",value:k.wastedCount??0,tone:"negative"})]}),k.error&&e.jsx("div",{className:"rounded-md border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:k.error}),k.icpDescription&&e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:"Customer profile"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-300",children:k.icpDescription})]}),k.competitorMap.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Sites that keep getting cited"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:k.competitorMap.slice(0,8).map(y=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[y.domain," ",e.jsx("span",{className:"text-zinc-500",children:y.hits})]},y.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"Start a run above, or pick one from Recent runs to see its progress."})]}),k?.status==="completed"&&e.jsxs(Q,{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"})]}),e.jsxs(C,{type:"button",size:"sm",disabled:b.isPending||M===0,onClick:()=>b.mutate(void 0),children:[e.jsx(ei,{size:14}),b.isPending?"Adding…":"Add recommended queries"]})]}),L.isLoading?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading recommendations…"}):$?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ut,{label:"Queries to add",value:M,tone:"positive"}),e.jsx(ut,{label:"Already cited",value:$.queriesByBucket.cited.length,tone:"positive"}),e.jsx(ut,{label:"Opportunities",value:$.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(ut,{label:"Low value (skipped)",value:$.queriesByBucket["wasted-surface"].length,tone:"negative"})]}),e.jsx("p",{className:"text-xs leading-5 text-zinc-500",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."}),$.suggestedCompetitors.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-zinc-400",children:"Competitor sites that will be added"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:$.suggestedCompetitors.map(y=>e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-950 px-2 py-1 text-xs text-zinc-300",children:[y.domain," ",e.jsx("span",{className:"text-zinc-500",children:y.hits})]},y.domain))})]})]}):e.jsx("p",{className:"text-sm text-zinc-500",children:"No recommendations available for this run."})]}),e.jsxs(Q,{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(se,{tone:"neutral",children:"Loading"})]}),R.length===0?e.jsx("p",{className:"text-sm text-zinc-500",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:R.map(y=>e.jsxs("tr",{children:[e.jsx("td",{className:"font-medium text-zinc-100",children:y.query}),e.jsx("td",{children:e.jsx(se,{tone:_c(y.bucket),children:Qc(y.bucket)})}),e.jsx("td",{className:"text-zinc-400",children:y.citedDomains.length>0?y.citedDomains.slice(0,3).join(", "):"-"})]},y.id))})]})})]})]})]})]})}function ut({label:t,value:s,tone:n="neutral"}){const i=n==="positive"?"text-emerald-300":n==="caution"?"text-amber-300":n==="negative"?"text-rose-300":"text-zinc-100";return e.jsxs("div",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("p",{className:`mt-1 text-2xl font-semibold tabular-nums ${i}`,children:s})]})}function Dn(t){return t==="completed"?"positive":t==="failed"?"negative":Qs.has(t)?"caution":"neutral"}function _c(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Uc={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function Qc(t){return t?Uc[t]:"Not classified"}function Ts(t){return t.length>8?t.slice(0,8):t}function Kc(t){const s=t.promoted.queries.length,n=t.promoted.competitors.length,i=t.skipped.queries.length+t.skipped.competitors.length;return`${s} quer${s===1?"y":"ies"} and ${n} competitor${n===1?"":"s"} added${i>0?`; ${i} already tracked`:""}.`}async function $n(t,s,n){await Promise.all([t.invalidateQueries({predicate:i=>{const a=i.queryKey[0];return typeof a?._id=="string"&&a._id.startsWith("getApiV1ProjectsByNameDiscover")}}),t.invalidateQueries({queryKey:Vn({client:U})})])}const Pn=100,Es=12;function Ms(t){return t>=70?"positive":t>=40?"caution":"negative"}function Os(t){return t>=70?"text-emerald-400":t>=40?"text-amber-400":"text-rose-400"}function Vc(t){return t==="pass"?"positive":t==="partial"?"caution":"negative"}function hs(t){return t>=70?"Pass":t>=40?"Partial":"Fail"}function Hc({projectName:t}){const s=ft(),[n,i]=r.useState(!1),[a,l]=r.useState(null),o=$e(La({client:U,path:{name:t}})),u=$e(Da({client:U,path:{name:t},query:{limit:30}})),m=$e($a({client:U,path:{name:t},query:{limit:Pn,sort:"score-asc"}})),p=Jt({mutationFn:()=>Pa(t),onSuccess:()=>{ee({title:"Technical audit started",detail:"The audit re-reads your sitemap in the background. Refresh in a minute to see the score.",tone:"positive"}),s.invalidateQueries({queryKey:Vn({client:U})})},onError:x=>{ee({title:"Could not start technical audit",detail:x instanceof Error?x.message:"Failed to start technical audit.",tone:"negative"})}}),f=()=>{s.invalidateQueries({queryKey:Ra({client:U,path:{name:t}})}),s.invalidateQueries({queryKey:Ta({client:U,path:{name:t},query:{limit:30}})}),s.invalidateQueries({queryKey:Ea({client:U,path:{name:t},query:{limit:Pn,sort:"score-asc"}})})},d=o.data;if(o.isLoading)return e.jsx("p",{className:"supporting-copy mt-6",children:"Loading technical audit…"});if(!d||!d.hasData)return e.jsxs(Q,{className:"surface-card mt-6 p-8 text-center",children:[e.jsx(Fr,{className:"mx-auto mb-3 h-8 w-8 text-zinc-500","aria-hidden":"true"}),e.jsx("h2",{className:"text-base font-semibold text-zinc-100",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."}),e.jsx("div",{className:"mt-5 flex items-center justify-center gap-3",children:e.jsxs(C,{type:"button",onClick:()=>p.mutate(),disabled:p.isPending,children:[e.jsx(Xt,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),p.isPending?"Starting…":"Run first audit"]})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-600",children:["Or from the CLI: ",e.jsxs("code",{className:"text-zinc-400",children:["canonry technical-aeo run ",t," --wait"]})]})]});const A=d.deltaScore==null?null:`${d.deltaScore>=0?"+":""}${d.deltaScore} vs previous`,L=d.trend==="up"?"positive":d.trend==="down"?"negative":"neutral",D=u.data?.points.map(x=>({date:x.auditedAt,score:x.aggregateScore}))??[],b=m.data?.pages??[],k=b.filter(x=>x.status==="success"),$=d.pagesErrored>0,M=n&&$,R=M?b.filter(x=>x.status==="error"):b,y=d.pagesAudited>b.length;function j(x){const T=[];for(const q of k){const E=q.factors.find(G=>G.id===x);E&&E.score<70&&T.push({url:q.url,score:E.score})}return T.sort((q,E)=>q.score-E.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-zinc-800/60 bg-zinc-900/30 p-6",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Technical AEO"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-3",children:[e.jsx("span",{className:`text-4xl font-semibold tabular-nums ${Os(d.aggregateScore)}`,children:d.aggregateScore}),e.jsx("span",{className:"text-lg text-zinc-500",children:"/ 100"}),e.jsx(se,{tone:Ms(d.aggregateScore),children:hs(d.aggregateScore)}),A?e.jsx(se,{tone:L,children:A}):null]}),e.jsxs("p",{className:"supporting-copy mt-2 tabular-nums",children:[d.pagesDiscovered," URL",d.pagesDiscovered===1?"":"s"," in sitemap · ",d.pagesAudited," audited · ",d.pagesSkipped," skipped · ",d.pagesErrored," errored"]}),e.jsxs("p",{className:"mt-1 flex flex-wrap items-center gap-x-1.5 text-xs text-zinc-500",children:[e.jsx("span",{className:"text-zinc-600",children:"Sitemap:"}),e.jsx("a",{href:d.sitemapUrl??"#",target:"_blank",rel:"noreferrer",className:"max-w-[22rem] truncate text-zinc-400 underline decoration-zinc-700 underline-offset-2 hover:text-zinc-200",children:d.sitemapUrl}),e.jsx(Ne,{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>`."})]}),d.auditedAt?e.jsxs("p",{className:"mt-0.5 text-xs text-zinc-600",children:["Audited ",new Date(d.auditedAt).toLocaleString()]}):null]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(C,{type:"button",variant:"outline",size:"sm",onClick:f,children:[e.jsx(js,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),"Refresh"]}),e.jsxs(C,{type:"button",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,children:[e.jsx(Xt,{className:"mr-1.5 h-4 w-4","aria-hidden":"true"}),p.isPending?"Starting…":"Re-run audit"]})]})]}),D.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.jsx("div",{className:"mt-3 h-56",children:e.jsx(Ot,{width:"100%",height:"100%",children:e.jsxs(Ft,{data:D,margin:{top:8,right:8,bottom:0,left:0},children:[e.jsx(Hs,{stroke:Vs,vertical:!1}),e.jsx(Gt,{dataKey:"date",tick:He,tickLine:!1,axisLine:{stroke:rt},tickFormatter:Mt,minTickGap:24}),e.jsx(Bt,{domain:[0,100],ticks:[0,25,50,75,100],tick:He,tickLine:!1,axisLine:!1,width:32}),e.jsx(qt,{...gt,cursor:{stroke:rt,strokeWidth:1},labelFormatter:wt,formatter:x=>[`${x}/100`,"Site score"]}),e.jsx(Ws,{type:"monotone",dataKey:"score",name:"score",stroke:"#34d399",strokeWidth:2.5,dot:{r:2.5,fill:"#34d399",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(Ne,{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:d.factors.map(x=>{const T=a===x.id,q=d.crossCuttingIssues.find(S=>S.factorId===x.id),E=T?j(x.id):[],G=x.pagesPartial+x.pagesFailing;return e.jsxs(r.Fragment,{children:[e.jsxs("tr",{className:T?"bg-zinc-900/30":void 0,children:[e.jsx("td",{children:e.jsxs("button",{type:"button",className:"flex items-center gap-1.5 text-left font-medium text-zinc-200 hover:text-zinc-50","aria-expanded":T,onClick:()=>l(T?null:x.id),children:[T?e.jsx(Hn,{className:"h-3.5 w-3.5 shrink-0 text-zinc-500","aria-hidden":"true"}):e.jsx(vs,{className:"h-3.5 w-3.5 shrink-0 text-zinc-500","aria-hidden":"true"}),x.name]})}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-500",children:[x.weight,"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-200",children:x.avgScore}),e.jsx("td",{children:e.jsx(se,{tone:Vc(x.status),children:hs(x.avgScore)})}),e.jsxs("td",{className:"tabular-nums text-zinc-400",children:[e.jsx("span",{className:"text-emerald-400",children:x.pagesPassing})," / ",e.jsx("span",{className:"text-amber-400",children:x.pagesPartial})," / ",e.jsx("span",{className:"text-rose-400",children:x.pagesFailing})]})]}),T?e.jsx("tr",{className:"bg-zinc-900/30",children:e.jsx("td",{colSpan:5,className:"px-4 pb-4 pt-0",children:e.jsxs("div",{className:"space-y-4 border-l border-zinc-800 pl-4",children:[q&&q.topRecommendations.length>0?e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-1.5 text-zinc-500",children:"How to fix"}),e.jsx("ul",{className:"space-y-1",children:q.topRecommendations.map((S,P)=>e.jsxs("li",{className:"flex gap-2 text-sm text-zinc-300",children:[e.jsx("span",{className:"select-none text-zinc-600",children:"→"}),e.jsx("span",{children:S})]},P))})]}):G===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"Every audited page passes this factor."}):null,G>0?e.jsxs("div",{children:[e.jsxs("p",{className:"eyebrow eyebrow-soft mb-1.5 text-zinc-500",children:["Pages below pass (",G,")"]}),e.jsx("ul",{className:"space-y-1",children:E.slice(0,Es).map(S=>e.jsxs("li",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:`w-8 shrink-0 text-right tabular-nums ${Os(S.score)}`,children:S.score}),e.jsx("a",{href:S.url,target:"_blank",rel:"noreferrer",className:"truncate text-zinc-300 hover:text-zinc-100",title:S.url,children:S.url})]},S.url))}),E.length>Es?e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["+ ",E.length-Es," more below pass"]}):null,y?e.jsxs("p",{className:"mt-1 text-xs text-zinc-600",children:["Showing the worst ",b.length," audited pages."]}):null]}):null]})})}):null]},x.id)})})]})})]}),d.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(Ne,{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-zinc-800/60 overflow-hidden rounded-lg border border-zinc-800/60",children:d.crossCuttingIssues.map(x=>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-zinc-100",children:x.factorName}),e.jsx(se,{tone:Ms(x.avgScore),children:hs(x.avgScore)}),e.jsxs("span",{className:"text-xs tabular-nums text-zinc-500",children:["avg ",x.avgScore," · affects ",x.affectedPages," of ",x.totalPages," pages (",x.affectedPct,"%)"]})]}),x.topRecommendations.length>0?e.jsx("ul",{className:"mt-2 space-y-1",children:x.topRecommendations.map((T,q)=>e.jsxs("li",{className:"flex gap-2 text-sm text-zinc-400",children:[e.jsx("span",{className:"select-none text-zinc-600",children:"→"}),e.jsx("span",{children:T})]},q))}):null]},x.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"})]}),$?e.jsxs("div",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-800/60 p-0.5",role:"group","aria-label":"Filter pages",children:[e.jsxs("button",{type:"button",onClick:()=>i(!1),"aria-pressed":!M,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${M?"text-zinc-500 hover:text-zinc-300":"bg-zinc-800 text-zinc-100"}`,children:["All ",d.pagesAudited]}),e.jsxs("button",{type:"button",onClick:()=>i(!0),"aria-pressed":M,className:`rounded-full px-3 py-1 text-xs font-medium tabular-nums transition-colors ${M?"bg-rose-500/15 text-rose-300":"text-zinc-500 hover:text-zinc-300"}`,children:["Errors ",d.pagesErrored]})]}):null]}),R.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",{children:"URL"})]})}),e.jsx("tbody",{children:R.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-right tabular-nums",children:x.status==="error"?e.jsxs("span",{className:"inline-flex items-center gap-1 text-rose-400",children:[e.jsx(Ia,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"err"]}):e.jsx("span",{className:Os(x.overallScore),children:x.overallScore})}),e.jsx("td",{children:x.status==="error"?e.jsx(se,{tone:"negative",children:"Error"}):e.jsx(se,{tone:Ms(x.overallScore),children:hs(x.overallScore)})}),e.jsx("td",{className:"max-w-0",children:e.jsx("a",{href:x.url,target:"_blank",rel:"noreferrer",className:"block truncate text-zinc-300 hover:text-zinc-100",title:x.status==="error"?x.error??x.url:x.url,children:x.url})})]},x.url))})]})}),y?e.jsxs("p",{className:"mt-2 text-xs text-zinc-600",children:["Showing the worst ",b.length," of ",d.pagesAudited," audited pages."]}):null]})]})]})}const Wc={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ve(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 Yc(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 Jc(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function Xc({projectName:t}){const[s,n]=r.useState(!1),[i,a]=r.useState(null),l=$e(Ma({client:U,path:{name:t}}));async function o(){n(!0),a(null);try{await Oa(t,"client")}catch(m){const p=m instanceof qs||m instanceof Error?m.message:"Download failed";a(p)}finally{n(!1)}}if(l.isLoading)return e.jsx("p",{className:"text-sm text-zinc-500 py-8 text-center",children:"Loading report…"});if(l.error){const m=l.error instanceof Error?l.error.message:"Failed to load report";return e.jsx("div",{className:"py-8 text-center",children:e.jsx("p",{className:"text-sm text-rose-400",children:m})})}const u=l.data;return u?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:u.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[u.meta.project.canonicalDomain," · ",u.meta.project.country," / ",u.meta.project.language.toUpperCase(),u.meta.location?` · Location: ${Jc(u.meta.location)}`:" · No location set"," · ","Generated ",Yc(u.meta.generatedAt)]}),i&&e.jsx("p",{className:"mt-2 text-xs text-rose-400",children:i})]}),e.jsx("div",{className:"page-header-right",children:e.jsxs(C,{variant:"secondary",size:"sm",onClick:Z(o),disabled:s,children:[e.jsx(Ys,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})})]}),e.jsx(al,{report:u}),e.jsx(ml,{report:u,audience:"client"}),e.jsx(tl,{report:u}),e.jsx(ll,{report:u,audience:"client",projectName:t}),e.jsx(ol,{report:u})]}):null}const In="AI Visibility — Server-Side",Rn="AI engine attention",Zc="What AI engines actually do in your server logs over the last 7 days — the other half of citations.",el="Live telemetry from your server logs.";function tl({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Zt,{eyebrow:Rn,title:In,subtitle:el}),e.jsx("p",{className:"text-sm text-zinc-500",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:Hr(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},i=Ls(n,"requests"),a=`${ve(s.verifiedCrawlerHits.current)} verified · ${ve(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,l=Ls(s.aiUserFetchHits,"requests"),o=Ls(s.referralArrivals,"sessions"),u=s.byOperator.filter(m=>m.verifiedHits>0||m.unverifiedHits>0||m.userFetchHits>0||m.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Zt,{eyebrow:Rn,title:In,subtitle:Zc}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(Bs,{label:"AI bot requests observed",value:ve(n.current),subtitle:a}),e.jsx(Bs,{label:"AI user-fetch requests",value:ve(s.aiUserFetchHits.current),subtitle:l||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(Bs,{label:"AI referral sessions",value:ve(s.referralArrivals.current),subtitle:o})]}),u.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.jsx("th",{children:"Bot requests (7d)"}),e.jsx("th",{children:"User fetches (7d)"}),e.jsx("th",{children:"Referral sessions"})]})}),e.jsx("tbody",{children:u.map(m=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:m.operator}),e.jsx("td",{children:ve(m.verifiedHits+m.unverifiedHits)}),e.jsx("td",{children:ve(m.userFetchHits)}),e.jsx("td",{children:ve(m.referralArrivals)})]},m.operator))})]})}),e.jsx("p",{className:"mt-2 text-[11px] text-zinc-500",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 sl(t,s){return t.audience==="both"||t.audience===s}const nl={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function bs(t){return nl[t]??t.charAt(0).toUpperCase()+t.slice(1)}function il(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 al({report:t}){const s=t.executiveSummary,n=t.citationScorecard,i=s.totalQueryCount,a=i>0?`${s.citationRate}%`:"—",l=i>0?`When customers asked AI ${i} ${i===1?"question":"questions"} about your industry, AI linked to your website in ${s.citedQueryCount} of ${i===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.",o=il(t.whatsChanged.citationRate),u=n.providers.length>0?n.providers.map(bs).join(", "):`${ve(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-zinc-800/60 bg-zinc-900/40 p-6 sm:p-8",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:"Overview"}),e.jsx("p",{className:"mt-3 text-6xl font-bold tracking-tight text-zinc-50 sm:text-7xl",children:a}),e.jsx("p",{className:"mt-3 max-w-2xl text-base text-zinc-300 sm:text-lg",children:l}),o&&e.jsxs("p",{className:`mt-3 text-sm font-medium ${o.tone==="positive"?"text-emerald-400":o.tone==="negative"?"text-rose-400":"text-zinc-400"}`,children:[e.jsx("span",{className:"mr-1",children:o.arrow}),o.text]})]}),e.jsxs("div",{className:"mt-5 grid gap-4 sm:grid-cols-3",children:[e.jsx(Fs,{label:"AI mentions your name",value:`${s.mentionRate}%`,subtitle:i>0?`Says your name in ${s.mentionedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(Fs,{label:"AI links to your website",value:`${s.citationRate}%`,subtitle:i>0?`Cites your site as a source in ${s.citedQueryCount} of ${i} ${i===1?"answer":"answers"}`:"No data yet"}),e.jsx(Fs,{label:"AI tools tested",value:ve(s.providerCount),subtitle:u})]}),e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-950/40 px-4 py-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-semibold text-zinc-200",children:"Mentions and links are different."})," ","A ",e.jsx("span",{className:"font-medium text-zinc-200",children:"mention"})," is when AI says your name out loud in its answer. A ",e.jsx("span",{className:"font-medium text-zinc-200",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-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Customer questions we tested"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",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((m,p)=>e.jsxs("li",{className:"flex items-start gap-3 rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2 text-sm text-zinc-200",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold tabular-nums text-zinc-500",children:String(p+1).padStart(2,"0")}),e.jsxs("span",{children:['"',m,'"']})]},p))})]}),n.providerRates.length>0&&e.jsxs("div",{className:"mt-5 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"How often each AI tool links to your website"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",children:"Higher is better. Each bar shows the share of customer questions where the AI cited your site."}),e.jsx("div",{className:"mt-4 space-y-3",children:n.providerRates.map(m=>e.jsxs("div",{className:"grid grid-cols-[120px_1fr_120px] items-center gap-3",children:[e.jsx("span",{className:"text-sm text-zinc-300",children:bs(m.provider)}),e.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500/70",style:{width:`${Math.max(m.citationRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-zinc-100",children:[m.citationRate,"% ",e.jsxs("span",{className:"font-normal text-zinc-500",children:["(",m.citedCount,"/",m.totalCount,")"]})]})]},m.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((m,p)=>e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2 text-xs text-zinc-400",children:m},p))})]})}function Fs({label:t,value:s,subtitle:n}){return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-zinc-500",children:t}),e.jsx("p",{className:"mt-3 text-4xl font-bold tracking-tight text-zinc-50 sm:text-5xl",children:s}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",children:n})]})}function rl(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function cl(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function ll({report:t,audience:s,projectName:n}){const i=s==="client"?t.clientSummary.actionItems:t.agencyDiagnostics.priorities.length>0?t.agencyDiagnostics.priorities:t.actionPlan.filter(d=>sl(d,s)),a=Kr(t,i),l=s==="client",o=Fa(),[u,m]=r.useState(new Set),p=u.size>0?a.filter(d=>!d.targetRef||!u.has(d.targetRef)):a,f=d=>{if(!d.targetRef)return;const A=d.targetRef;m(L=>new Set(L).add(A)),o.mutate({projectName:n,body:{targetRef:A}},{onSuccess:()=>{ee({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:L=>{ee({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(L)}),m(D=>{const b=new Set(D);return b.delete(A),b})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Zt,{eyebrow:l?"Action plan":"Agency actions",title:l?"What to do next":"Agency Action Plan",subtitle:l?"Approve these in order. They are sorted by what will move the needle fastest.":"The highest-leverage work, sorted by urgency and evidence strength."}),p.length===0?e.jsx(Zs,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:p.map((d,A)=>{const L=d.evidence.length>0?d.evidence:d.why,D=d.why.length>0||d.evidence.length>0;return e.jsxs("article",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 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-zinc-800/80 text-sm font-semibold text-zinc-100",title:"Priority — 1 will move the needle fastest",children:A+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(se,{tone:Ba(d),children:l?rl(d.horizon):Ga(d.horizon)}),!l&&e.jsx(se,{tone:"neutral",children:qa(d.category)}),e.jsx(se,{tone:"neutral",children:l?cl(d.confidence):`${_a(d.confidence)} confidence`})]}),e.jsx("p",{className:"text-sm font-medium text-zinc-100",children:d.title})]})]}),e.jsx("p",{className:"mt-3 text-sm text-zinc-400",children:d.action}),e.jsx(ul,{items:L,limit:3,className:"mt-3"}),D&&e.jsxs("details",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("summary",{className:"cursor-pointer text-zinc-500 hover:text-zinc-300",children:l?"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:l?"Why this matters":"Why"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.why.map((b,k)=>e.jsx("li",{children:b},k))})]}),d.evidence.length>0&&e.jsxs("div",{className:"mt-2",children:[e.jsx("p",{className:"eyebrow-soft mb-1",children:l?"What we saw":"Evidence"}),e.jsx("ul",{className:"list-disc space-y-1 pl-4",children:d.evidence.map((b,k)=>e.jsx("li",{children:b},k))})]})]}),e.jsxs("p",{className:"mt-3 border-t border-zinc-800/60 pt-3 text-xs text-zinc-300",children:[e.jsx("span",{className:"font-medium",children:l?"What success looks like:":"Win condition:"})," ",d.successMetric]}),d.targetRef&&e.jsx("div",{className:"mt-3 flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>f(d),className:"rounded-md border border-zinc-700/60 bg-zinc-900/50 px-2.5 py-1 text-[11px] font-medium text-zinc-300 hover:border-zinc-600 hover:bg-zinc-800/70 hover:text-zinc-100",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 Tn({label:t,value:s,displayValue:n,max:i,barClass:a}){const l=i>0?Math.max(s/i*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-zinc-300",title:t,children:t}),e.jsx("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${a}`,style:{width:`${l}%`}})})]}),e.jsx("span",{className:"whitespace-nowrap text-sm font-semibold text-zinc-100",children:n})]})}function ol({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,i=t.indexingHealth,a=Vr(t).slice(0,5),l=s.length>0?Math.max(...s.map(m=>m.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(m=>m.impressions),1):0,u=s.length>0||n!==null||i!==null||a.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Zt,{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."}),u?e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[s.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Where AI gets its answers"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",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(m=>e.jsx(Tn,{label:m.domain+(m.isCompetitor?" (competitor)":""),value:m.count,displayValue:`${ve(m.count)}×`,max:l,barClass:"bg-zinc-400/70"},m.domain))})]}),i&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Pages Google can find on your site"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",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 ${i.indexedPct>=90?"text-emerald-400":i.indexedPct>=70?"text-amber-400":"text-rose-400"}`,children:[i.indexedPct,"%"]}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[ve(i.indexed)," of ",ve(i.total)," pages indexed"]}),e.jsx("div",{className:"mt-3 h-3 overflow-hidden rounded-full bg-zinc-800/80",children:e.jsx("div",{className:`h-full rounded-full ${i.indexedPct>=90?"bg-emerald-500/70":i.indexedPct>=70?"bg-amber-500/70":"bg-rose-500/70"}`,style:{width:`${Math.max(i.indexedPct,1.5)}%`}})}),e.jsxs("p",{className:"mt-3 text-xs text-zinc-400",children:[e.jsx("span",{className:"font-medium text-zinc-200",children:ve(i.notIndexed)})," ",i.notIndexed===1?"page is":"pages are"," not indexed yet."]})]}),n&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"What people search Google for"}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:["You appeared in ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ve(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ve(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(m=>e.jsx(Tn,{label:m.query,value:m.impressions,displayValue:`${ve(m.impressions)} ${m.impressions===1?"search":"searches"}`,max:o,barClass:"bg-sky-500/70"},m.query))})]}),a.length>0&&e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-5",children:[e.jsx("p",{className:"text-sm font-semibold text-zinc-100",children:"Topics where you could improve"}),e.jsx("p",{className:"mt-1 text-xs text-zinc-500",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-zinc-300",children:a.map((m,p)=>e.jsxs("li",{className:"rounded-lg border border-zinc-800/60 bg-zinc-950/40 px-3 py-2",children:[e.jsx("p",{className:"font-medium text-zinc-100",children:m.query}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-2 text-xs text-zinc-400",children:[Ua(m.action),m.winnabilityClass==="ceded"&&e.jsx(se,{tone:"caution",children:"Ceded surface"})]})]},p))})]})]}):e.jsx(Zs,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}const dl=14;function Js(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function Xs(t){return t==="up"?"↑":t==="down"?"↓":"→"}function Gs({label:t,delta:s,unit:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"No prior data"})]});const i=n==="%"?"%":"",a=s.deltaAbs>0?"+":"",l=Js(s.direction),o=l==="positive"?"text-emerald-400":l==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${o}`,children:[s.current,i," ",e.jsx("span",{className:"text-sm font-medium",children:Xs(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[a,n==="%"?s.deltaAbs.toFixed(1):s.deltaAbs,i," vs ",s.prior,i]})]})}function En({label:t,delta:s,countLabel:n}){if(!s)return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:"text-2xl font-semibold tracking-tight text-zinc-500",children:"—"}),e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:"Not enough trend data"})]});const i=s.deltaAbs>0?"+":"",a=Js(s.direction),l=a==="positive"?"text-emerald-400":a==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsxs("p",{className:`text-2xl font-semibold tracking-tight ${l}`,children:[ve(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:Xs(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[i,ve(s.deltaAbs)," ",n," vs prior ",dl," days"]})]})}function xl({movements:t,audience:s}){const n=t.filter(a=>a.direction!=="flat");if(n.length===0)return null;const i=s==="client";return e.jsxs("div",{className:"mt-4",children:[e.jsx("p",{className:"eyebrow mb-2",children:i?"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:i?"AI tool":"Engine"}),e.jsx("th",{children:i?"Was":"Prior"}),e.jsx("th",{children:i?"Now":"Current"}),e.jsx("th",{children:"Change"})]})}),e.jsx("tbody",{children:n.map(a=>{const l=a.deltaAbs>0?"+":"",o=Js(a.direction),u=o==="positive"?"text-emerald-400":o==="negative"?"text-rose-400":"text-zinc-300";return e.jsxs("tr",{children:[e.jsx("td",{children:i?bs(a.provider):a.provider}),e.jsxs("td",{children:[a.prior,"%"]}),e.jsxs("td",{children:[a.current,"%"]}),e.jsxs("td",{className:u,children:[l,a.deltaAbs.toFixed(1),"% ",Xs(a.direction)]})]},a.provider)})})]})})]})}function Mn({insights:t,heading:s,emptyMessage:n,audience:i}){if(t.length===0)return e.jsxs("div",{className:"mt-4 rounded-xl border border-zinc-800/60 bg-zinc-900/30 p-4",children:[e.jsx("p",{className:"eyebrow mb-1",children:s}),e.jsx("p",{className:"text-xs text-zinc-500",children:n})]});const a=i==="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:[!a&&e.jsx("th",{children:"Severity"}),e.jsx("th",{children:a?"What changed":"Title"}),e.jsx("th",{children:a?"Customer question":"Query"}),e.jsx("th",{children:a?"AI tool":"Provider"})]})}),e.jsx("tbody",{children:t.map(l=>e.jsxs("tr",{children:[!a&&e.jsxs("td",{children:[e.jsx(se,{tone:Wc[l.severity],children:Qa(l.severity)}),l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsxs("td",{className:"evidence-query-cell",children:[l.title,a&&l.instanceCount>1&&e.jsxs("span",{className:"ml-2 text-[11px] text-zinc-500",children:["×",l.instanceCount]})]}),e.jsx("td",{className:"text-xs text-zinc-400",children:l.query}),e.jsx("td",{className:"text-xs text-zinc-400",children:a?bs(l.provider):l.provider})]},l.id))})]})})]})}function ml({report:t,audience:s}){const n=t.whatsChanged,i=s==="client",a=!n.enoughHistory&&!n.gscClicksDelta&&!n.aiReferralsDelta&&n.wins.length===0&&n.regressions.length===0,l=e.jsx(Zt,{eyebrow:i?"Since last check":"Section 2",title:i?"What's different since last check":"What's Changed",subtitle:i?void 0:n.headline});return a?e.jsxs("section",{className:"page-section-divider",children:[l,e.jsx(Zs,{message:i?"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:[l,e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-5",children:[e.jsx(Gs,{label:i?"AI links to your website":"Citation rate",delta:n.citationRate,unit:"%"}),e.jsx(Gs,{label:i?"AI mentions your name":"Mention rate",delta:n.mentionRate,unit:"%"}),e.jsx(Gs,{label:i?"Questions AI answered with you":"Cited queries",delta:n.citedQueryCount,unit:"count"}),e.jsx(En,{label:i?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:i?"visits":"clicks"}),e.jsx(En,{label:i?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:i?"visits":"sessions"})]}),e.jsx(xl,{movements:n.providerMovements,audience:s}),e.jsx(Mn,{insights:n.wins,heading:i?"What got better":"Wins",emptyMessage:i?"No new wins this period.":"No new gains in the latest check.",audience:s}),e.jsx(Mn,{insights:n.regressions,heading:i?"What got worse":"Regressions",emptyMessage:i?"Nothing got worse this period.":"No new regressions in the latest check.",audience:s})]})}function Bs({label:t,value:s,tone:n,subtitle:i}){const a=n==="positive"?"text-emerald-400":n==="caution"?"text-amber-400":n==="negative"?"text-rose-400":"text-zinc-100";return e.jsxs("div",{className:"rounded-xl border border-zinc-800/60 bg-zinc-900/30 px-4 py-3",children:[e.jsx("p",{className:"eyebrow-soft",children:t}),e.jsx("p",{className:`text-2xl font-semibold tracking-tight ${a}`,children:s}),i&&e.jsx("p",{className:"mt-1 text-[11px] text-zinc-500",children:i})]})}function Zt({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 ul({items:t,limit:s=3,className:n}){if(t.length===0)return null;const i=t.slice(0,s),a=t.length-i.length;return e.jsxs("div",{className:`flex flex-wrap gap-1.5 ${n??""}`,children:[i.map((l,o)=>e.jsx("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-300",children:l},o)),a>0&&e.jsxs("span",{className:"rounded-md border border-zinc-800/60 bg-zinc-900/40 px-2 py-0.5 text-[11px] text-zinc-400",children:["+",a," more"]})]})}function Zs({message:t}){return e.jsx("p",{className:"text-sm text-zinc-500 py-4 text-center",children:t})}function hl({project:t,onUpdateProject:s,onRefresh:n}){const[i,a]=r.useState(!1),[l,o]=r.useState(!1),[u,m]=r.useState(null),[p,f]=r.useState(t.displayName),[d,A]=r.useState(t.canonicalDomain),[L,D]=r.useState(t.country),[b,k]=r.useState(t.language),[$,M]=r.useState(t.ownedDomains??[]),[R,y]=r.useState(""),[j,x]=r.useState(t.aliases??[]),[T,q]=r.useState(""),[E,G]=r.useState(null),[S,P]=r.useState(!1),[B,w]=r.useState(!1),[Y,ae]=r.useState(""),[pe,K]=r.useState(""),[W,de]=r.useState(""),[he,g]=r.useState(""),[O,H]=r.useState("");r.useEffect(()=>{i||(f(t.displayName),A(t.canonicalDomain),D(t.country),k(t.language),M(t.ownedDomains??[]),x(t.aliases??[]))},[t,i]);function le(){a(!1),m(null),f(t.displayName),A(t.canonicalDomain),D(t.country),k(t.language),M(t.ownedDomains??[]),x(t.aliases??[]),y(""),q("")}function ue(){const z=R.trim();z&&($.includes(z)||M([...$,z]),y(""))}function Me(z){M($.filter(I=>I!==z))}function we(){const z=T.trim();if(!z)return;const I=z.toLowerCase();j.some(Pe=>Pe.toLowerCase()===I)||x([...j,z]),q("")}function ne(z){x(j.filter(I=>I!==z))}async function te(){if(!(!p.trim()||!d.trim()||!L.trim()||!b.trim())){o(!0),m(null);try{await s(t.name,{displayName:p.trim(),canonicalDomain:d.trim(),ownedDomains:$,aliases:j,country:L.trim(),language:b.trim()}),a(!1),ee({title:"Project settings saved",detail:`${p.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(z){m(z instanceof Error?z.message:"Failed to save")}finally{o(!1)}}}async function je(){const z=Y.trim(),I=pe.trim(),Pe=W.trim(),We=he.trim();if(!(!z||!I||!Pe||!We)){P(!0),G(null);try{const ye={label:z,city:I,region:Pe,country:We};O.trim()&&(ye.timezone=O.trim()),await Ha(t.name,ye),n(),ae(""),K(""),de(""),g(""),H(""),w(!1),ee({title:"Location added",detail:`${z} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${z}`,dedupeMode:"drop"})}catch(ye){G(ye instanceof Error?ye.message:"Failed to add location")}finally{P(!1)}}}async function ke(z){P(!0),G(null);try{await Va(t.name,z),n(),ee({title:"Location removed",detail:`${z} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${z}`,dedupeMode:"drop"})}catch(I){G(I instanceof Error?I.message:"Failed to remove location")}finally{P(!1)}}async function be(z){P(!0),G(null);try{await Ka(t.name,z),n(),ee({title:"Default location updated",detail:`${z} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(I){G(I instanceof Error?I.message:"Failed to set default location")}finally{P(!1)}}const Ce=p!==t.displayName||d!==t.canonicalDomain||L!==t.country||b!==t.language||JSON.stringify($)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(j)!==JSON.stringify(t.aliases??[]),xe="w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",Re="block text-xs font-medium text-zinc-400 mb-1",Ae=Y.trim()&&pe.trim()&&W.trim()&&he.trim();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:"Configuration"}),e.jsx("h2",{children:"Project settings"})]}),!i&&e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),u&&e.jsxs("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:[u,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>m(null),children:"×"})]}),i?e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/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:Re,children:"Display name"}),e.jsx("input",{className:xe,type:"text",value:p,onChange:z=>f(z.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Re,children:"Canonical domain"}),e.jsx("input",{className:xe,type:"text",value:d,onChange:z=>A(z.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:Re,children:"Country"}),e.jsx("input",{className:xe,type:"text",value:L,onChange:z=>D(z.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:Re,children:"Language"}),e.jsx("input",{className:xe,type:"text",value:b,onChange:z=>k(z.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Re,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:$.map(z=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[z,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>Me(z),"aria-label":`Remove ${z}`,children:"×"})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${xe} flex-1`,type:"text",placeholder:"docs.example.com",value:R,onChange:z=>y(z.target.value),onKeyDown:z=>z.key==="Enter"&&(z.preventDefault(),ue())}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:!R.trim(),onClick:ue,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:Re,children:"Aliases"}),e.jsx("p",{className:"text-[11px] text-zinc-500 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:j.map(z=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[z,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ne(z),"aria-label":`Remove ${z}`,children:"×"})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${xe} flex-1`,type:"text",placeholder:"Facebook",value:T,onChange:z=>q(z.target.value),onKeyDown:z=>z.key==="Enter"&&(z.preventDefault(),we())}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:!T.trim(),onClick:we,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-zinc-800/60",children:[e.jsx(C,{type:"button",disabled:l||!Ce||!p.trim()||!d.trim(),onClick:Z(te),children:l?"Saving...":"Save changes"}),e.jsx(C,{type:"button",variant:"outline",disabled:l,onClick:le,children:"Cancel"})]})]}):e.jsx("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 overflow-hidden",children:e.jsx("table",{className:"w-full text-sm",children:e.jsxs("tbody",{children:[e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium w-40",children:"Display name"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.displayName||"—"})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Canonical domain"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.canonicalDomain})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 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(z=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:z},z))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 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(z=>e.jsx("span",{className:"rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:z},z))}):e.jsx("span",{className:"text-zinc-500",children:"—"})})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Country"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.country})]}),e.jsxs("tr",{className:"border-b border-zinc-800/40",children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium",children:"Language"}),e.jsx("td",{className:"px-4 py-2.5 text-zinc-200",children:t.language})]}),e.jsxs("tr",{children:[e.jsx("td",{className:"px-4 py-2.5 text-zinc-500 font-medium align-top pt-3",children:"Locations"}),e.jsxs("td",{className:"px-4 py-2.5",children:[E&&e.jsxs("div",{className:"mb-2 rounded border border-rose-800/40 bg-rose-950/20 px-2 py-1 text-xs text-rose-300",children:[E,e.jsx("button",{type:"button",className:"ml-1 text-rose-400 hover:text-rose-200",onClick:()=>G(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-zinc-600",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(z=>e.jsxs("tr",{className:"border-t border-zinc-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 ${z.label===t.defaultLocation?"border-emerald-700/60 bg-emerald-950/30 text-emerald-300":"border-zinc-700/60 bg-zinc-800/40 text-zinc-300"}`,children:[z.label,z.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:z.city}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:z.region}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:z.country}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500",children:z.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[z.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:S,onClick:()=>{be(z.label)},className:"text-[10px] text-zinc-500 hover:text-emerald-400 transition-colors disabled:opacity-40","aria-label":`Set ${z.label} as default location`,children:"Set default"}),e.jsx("button",{type:"button",disabled:S,onClick:()=>{ke(z.label)},className:"text-[10px] text-zinc-500 hover:text-rose-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${z.label}`,children:"Remove"})]})})]},z.label))})]}):e.jsx("p",{className:"text-zinc-500 text-xs mb-2",children:"No locations configured"}),B?e.jsxs("div",{className:"mt-2 rounded border border-zinc-800 bg-zinc-900/50 p-3 space-y-2",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-wide text-zinc-500",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-zinc-500 mb-0.5",children:"Label *"}),e.jsx("input",{className:xe,type:"text",value:Y,onChange:z=>ae(z.target.value),placeholder:"nyc"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"City *"}),e.jsx("input",{className:xe,type:"text",value:pe,onChange:z=>K(z.target.value),placeholder:"New York"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Region *"}),e.jsx("input",{className:xe,type:"text",value:W,onChange:z=>de(z.target.value),placeholder:"NY"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Country *"}),e.jsx("input",{className:xe,type:"text",value:he,onChange:z=>g(z.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-[10px] text-zinc-500 mb-0.5",children:"Timezone (optional)"}),e.jsx("input",{className:xe,type:"text",value:O,onChange:z=>H(z.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(C,{type:"button",size:"sm",disabled:S||!Ae,onClick:Z(je),children:S?"Adding...":"Add location"}),e.jsx(C,{type:"button",size:"sm",variant:"outline",disabled:S,onClick:()=>{w(!1),G(null)},children:"Cancel"})]})]}):e.jsx(C,{type:"button",size:"sm",variant:"outline",onClick:()=>w(!0),children:"+ Add location"})]})]})]})})})]})}const pl=[{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"}],On=["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 gl({projectName:t}){const[s,n]=r.useState("loading"),[i,a]=r.useState(!1),[l,o]=r.useState("daily"),[u,m]=r.useState(6),[p,f]=r.useState(""),[d,A]=r.useState("UTC"),[L,D]=r.useState(!1),[b,k]=r.useState(""),[$,M]=r.useState(!1),[R,y]=r.useState(!1),[j,x]=r.useState(null);r.useEffect(()=>{Wa(t).then(n).catch(()=>n(null))},[t]);const T=()=>{if(s&&s!=="loading"){const S=Ja(s.preset??null,s.cronExpr);o(S.freq),m(S.hour),f(S.customCron);const P=On.includes(s.timezone);A(P?s.timezone:"Other"),D(!P),k(P?"":s.timezone)}else o("daily"),m(6),f(""),A("UTC"),D(!1),k("");x(null),a(!0)},q=async()=>{M(!0),x(null);try{const P={timezone:L?b.trim()||"UTC":d};l==="custom"?P.cron=p.trim():P.preset=Za(l,u);const B=await hn(t,P);n(B),a(!1),ee({title:"Schedule saved",detail:Cs(B.preset??null,B.cronExpr,B.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(S){x(S instanceof Error?S.message:"Failed to save schedule")}finally{M(!1)}},E=async()=>{if(!(!s||s==="loading")){M(!0),x(null);try{const S={timezone:s.timezone,enabled:!s.enabled};s.preset?S.preset=s.preset:S.cron=s.cronExpr;const P=await hn(t,S);n(P),ee({title:P.enabled?"Schedule resumed":"Schedule paused",detail:Cs(P.preset??null,P.cronExpr,P.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(S){x(S instanceof Error?S.message:"Failed to update schedule")}finally{M(!1)}}},G=async()=>{y(!0),x(null);try{await Xa(t),n(null),a(!1),ee({title:"Schedule removed",detail:`${t} will no longer run automatically.`,tone:"positive",dedupeKey:`schedule:remove:${t}`,dedupeMode:"drop"})}catch(S){x(S instanceof Error?S.message:"Failed to remove schedule")}finally{y(!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"})]}),s!=="loading"&&!i&&e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:T,children:s?"Edit schedule":"+ Set schedule"})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&!i&&s===null&&e.jsx(Q,{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"&&!i&&s!==null&&e.jsxs(Q,{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-zinc-200",children:Cs(s.preset??null,s.cronExpr,s.timezone)}),e.jsxs("p",{className:"text-xs text-zinc-500",children:["Cron: ",e.jsx("span",{className:"font-mono",children:s.cronExpr})]}),s.nextRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Next run: ",new Date(s.nextRunAt).toLocaleString()]}),s.lastRunAt&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Last run: ",new Date(s.lastRunAt).toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(se,{tone:s.enabled?"positive":"neutral",children:s.enabled?"Active":"Paused"}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:$,onClick:Z(E),children:s.enabled?"Pause":"Resume"}),e.jsx(C,{type:"button",variant:"ghost",size:"sm",disabled:R,onClick:Z(G),children:R?"Removing...":"Remove"})]})]}),j&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:j})]}),i&&e.jsxs("div",{className:"rounded-lg border border-zinc-800 bg-zinc-900/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-zinc-400",children:"Frequency"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:l,onChange:S=>o(S.target.value),children:pl.map(S=>e.jsx("option",{value:S.value,children:S.label},S.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Time"}),e.jsx("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none disabled:opacity-40",value:u,disabled:l==="twice-daily"||l==="custom",onChange:S=>m(parseInt(S.target.value)),children:Array.from({length:24},(S,P)=>e.jsx("option",{value:P,children:Ya(P)},P))})]})]}),l==="custom"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Cron expression"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 font-mono focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"0 9 * * 1-5",value:p,onChange:S=>f(S.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Timezone"}),e.jsxs("select",{className:"w-full rounded border border-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:L?"Other":d,onChange:S=>{S.target.value==="Other"?(D(!0),A("Other")):(D(!1),A(S.target.value))},children:[On.map(S=>e.jsx("option",{value:S,children:S},S)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),L&&e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"e.g. America/New_York",value:b,onChange:S=>k(S.target.value)})]}),j&&e.jsx("p",{className:"text-rose-400 text-sm",children:j}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),x(null)},children:"Cancel"}),e.jsx(C,{type:"button",size:"sm",disabled:$||l==="custom"&&!p.trim(),onClick:Z(q),children:$?"Saving...":"Save schedule"})]})]})]})}const fl=[{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 jl({projectName:t}){const[s,n]=r.useState("loading"),[i,a]=r.useState(!1),[l,o]=r.useState(""),[u,m]=r.useState(["citation.lost","citation.gained"]),[p,f]=r.useState(!1),[d,A]=r.useState(null),[L,D]=r.useState({}),[b,k]=r.useState(new Set);r.useEffect(()=>{er(t).then(n).catch(()=>n([]))},[t]);const $=j=>{m(x=>x.includes(j)?x.filter(T=>T!==j):[...x,j])},M=async()=>{if(!(!l.trim()||u.length===0)){f(!0),A(null);try{const j=await tr(t,{channel:"webhook",url:l.trim(),events:u});n(x=>x==="loading"?[j]:[...x,j]),o(""),m(["citation.lost","citation.gained"]),a(!1),ee({title:"Webhook added",detail:`Notifications will be sent to ${j.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(j){A(j instanceof Error?j.message:"Failed to add webhook")}finally{f(!1)}}},R=async j=>{if(!b.has(j)){k(x=>new Set(x).add(j));try{await nr(t,j),n(x=>x==="loading"?x:x.filter(T=>T.id!==j)),ee({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${j}`,dedupeMode:"drop"})}catch(x){A(x instanceof Error?x.message:"Failed to remove webhook")}finally{k(x=>{const T=new Set(x);return T.delete(j),T})}}},y=async j=>{D(x=>({...x,[j]:{state:"testing"}}));try{const x=await sr(t,j);D(T=>({...T,[j]:{state:x.ok?"ok":"fail",status:x.status}})),x.ok&&ee({title:"Test notification sent",detail:`Webhook returned status ${x.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${j}`,dedupeMode:"replace"})}catch{D(x=>({...x,[j]:{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"})]}),s!=="loading"&&e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!i),A(null)},children:i?"Cancel":"+ Add webhook"})]}),i&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/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-zinc-400",children:"Webhook URL"}),e.jsx("input",{className:"w-full rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"url",placeholder:"https://hooks.example.com/canonry",value:l,onChange:j=>o(j.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("label",{className:"text-xs font-medium text-zinc-400",children:"Trigger on"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:fl.map(j=>e.jsxs("label",{className:"flex items-center gap-1.5 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",className:"rounded border-zinc-600 bg-zinc-800",checked:u.includes(j.value),onChange:()=>$(j.value)}),e.jsx("span",{className:"text-sm text-zinc-300",children:j.label})]},j.value))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm",children:d}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),A(null)},children:"Cancel"}),e.jsx(C,{type:"button",size:"sm",disabled:p||!l.trim()||u.length===0,onClick:Z(M),children:p?"Adding...":"Add webhook"})]})]}),s==="loading"&&e.jsx("p",{className:"supporting-copy",children:"Loading..."}),s!=="loading"&&s.length===0&&!i&&e.jsx(Q,{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(j=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:e.jsx("span",{className:"font-mono text-xs text-zinc-300 break-all",title:j.urlHost,children:j.urlDisplay??j.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:j.events.map(x=>e.jsx("span",{className:"inline-flex items-center rounded-full border border-zinc-700 bg-zinc-800/60 px-2 py-0.5 text-[10px] font-medium text-zinc-400 uppercase tracking-wide",children:x.replace("."," ")},x))})}),e.jsx("td",{children:e.jsx(se,{tone:j.enabled?"positive":"neutral",children:j.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[L[j.id]&&(()=>{const x=L[j.id],T=x.state==="testing"?"Sending…":x.state==="ok"?`Delivered${x.status?` (${x.status})`:""}`:`Failed${x.status?` (${x.status})`:""}`;return e.jsx(se,{tone:x.state==="ok"?"positive":x.state==="fail"?"negative":"neutral",children:T})})(),e.jsx(C,{variant:"ghost",size:"sm",type:"button",disabled:L[j.id]?.state==="testing",onClick:()=>{y(j.id)},children:"Test"}),e.jsx(C,{variant:"ghost",size:"sm",type:"button",disabled:b.has(j.id),onClick:()=>{R(j.id)},children:b.has(j.id)?"Removing…":"Remove"})]})})]},j.id))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:d})]})]})}function It(t,s){return t.invalidateQueries({predicate:n=>{const i=n.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith(s)}})}function bl({projectName:t,refreshNonce:s}){const n=ft(),[i,a]=r.useState(null),[l,o]=r.useState([]),[u,m]=r.useState(null),[p,f]=r.useState([]),[d,A]=r.useState([]),[L,D]=r.useState(null),[b,k]=r.useState(""),[$,M]=r.useState(""),[R,y]=r.useState(""),[j,x]=r.useState(!0),[T,q]=r.useState(!1),[E,G]=r.useState(null),[S,P]=r.useState("performance");r.useEffect(()=>{B()},[t,s]);async function B(){x(!0),G(null);try{const g=await n.fetchQuery({...Wn({client:U,path:{name:t}}),staleTime:Le});if(a(g),g.connected){const[O,H,le,ue]=await Promise.all([n.fetchQuery({...Yn({client:U,path:{name:t}}),staleTime:Le}).catch(()=>null),n.fetchQuery({...Jn({client:U,path:{name:t}}),staleTime:Le}).catch(()=>[]),n.fetchQuery({...wr({client:U,path:{name:t}}),staleTime:Le}).catch(()=>[]),g.siteUrl?Promise.resolve([]):n.fetchQuery({...zr({client:U,path:{name:t}}),staleTime:Le}).then(Me=>Me.sites).catch(()=>[])]);m(O),f(H),A(le),o(ue)}else m(null),f([]),A([]),o([])}catch(g){G(g instanceof Error?g.message:"Failed to load Bing data")}finally{x(!1)}}async function w(){if($.trim()){G(null);try{const g=await Sr(t,$.trim());await It(n,"getApiV1ProjectsByNameBing"),M(""),g.availableSites.length>0&&o(g.availableSites),await B()}catch(g){G(g instanceof Error?g.message:"Failed to connect")}}}async function Y(){try{await kr(t),await It(n,"getApiV1ProjectsByNameBing"),a(null),o([]),m(null),f([]),A([]),D(null),y(""),G(null)}catch(g){G(g instanceof Error?g.message:"Failed to disconnect")}}async function ae(){if(R)try{await Cr(t,R),await It(n,"getApiV1ProjectsByNameBing"),await B()}catch(g){G(g instanceof Error?g.message:"Failed to set site")}}async function pe(){if(b.trim())try{const g=await Xn(t,b.trim());await It(n,"getApiV1ProjectsByNameBing"),D(g),f(O=>[g,...O])}catch(g){G(g instanceof Error?g.message:"Inspection failed")}}async function K(g){q(!0),G(null);try{const O=await jn(t,{urls:[g]}),{succeeded:H,failed:le,total:ue}=O.summary;ee({title:"Bing submission requested",detail:le===0?`${H} URL submitted to Bing.`:`${H}/${ue} submitted successfully, ${le} failed.`,tone:le===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${g}`,dedupeMode:"replace"})}catch(O){const H=O instanceof Error?O.message:"Submission failed";G(H),ee({title:"Bing submission failed",detail:H,tone:"negative",dedupeKey:`bing:indexing:${t}:${g}`,dedupeMode:"replace"})}finally{q(!1)}}async function W(){q(!0),G(null),ee({title:"Submitting URLs to Bing",detail:"Requesting indexing for all currently unindexed URLs.",tone:"neutral",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"});try{const g=await jn(t,{allUnindexed:!0}),{succeeded:O,failed:H,total:le}=g.summary;ee({title:"Bing submissions requested",detail:H===0?`${O}/${le} URL${le!==1?"s":""} submitted to Bing.`:`${O}/${le} submitted successfully, ${H} failed.`,tone:H===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(g){const O=g instanceof Error?g.message:"Batch submission failed";G(O),ee({title:"Bing submissions failed",detail:O,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{q(!1)}}if(j)return e.jsx(Q,{className:"surface-card",children:e.jsx("div",{className:"text-sm text-zinc-400",children:"Loading Bing data..."})});if(!i?.connected)return e.jsxs(Q,{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(se,{tone:"caution",children:"Not connected"})]}),e.jsx("p",{className:"text-sm text-zinc-300",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-zinc-500",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-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"Bing Webmaster Tools API key",value:$,onChange:g=>M(g.target.value),onKeyDown:g=>{g.key==="Enter"&&w()}}),e.jsx(C,{size:"sm",disabled:!$.trim(),onClick:Z(w),children:"Connect"})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:["Get your API key from"," ",e.jsx("a",{href:"https://www.bing.com/webmasters/",target:"_blank",rel:"noopener noreferrer",className:"text-zinc-400 hover:text-zinc-300 underline underline-offset-2",children:"Bing Webmaster Tools"})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:E})]});if(!i.siteUrl)return e.jsxs(Q,{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(se,{tone:"positive",children:"Connected"}),e.jsx(C,{size:"sm",variant:"ghost",onClick:Z(Y),children:"Disconnect"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 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-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsx("p",{className:"mt-2 text-xs text-zinc-500",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-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Registered domain"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.domain})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?Xe(i.updatedAt):"—"})]})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Select site"}),l.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-zinc-700 bg-zinc-900 px-2 py-1.5 text-sm text-zinc-200 focus:border-zinc-500 focus:outline-none",value:R,onChange:g=>y(g.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(g=>e.jsxs("option",{value:g.url,children:[g.url,g.verified?" (verified)":""]},g.url))]}),e.jsx(C,{size:"sm",disabled:!R,onClick:Z(ae),children:"Set Site"})]}):e.jsx("p",{className:"mt-3 text-xs text-zinc-500",children:"No verified Bing sites are available yet. Verify the domain in Bing Webmaster Tools, then use the page-level refresh to reload everything."})]})]}),E&&e.jsx("p",{className:"mt-3 text-xs text-rose-400",children:E})]});const de=[{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"}],he=de.find(g=>g.key===S)??de[0];return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(Q,{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(se,{tone:"positive",children:"Connected"}),e.jsx(C,{size:"sm",variant:"ghost",onClick:Z(Y),children:"Disconnect"})]})]}),E&&e.jsx("p",{className:"mb-3 text-xs text-rose-400",children:E}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 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-emerald-500"}),e.jsx("span",{className:"text-sm text-zinc-200",children:"Authorized for this project domain"}),e.jsx("span",{className:"text-xs text-zinc-500",children:i.domain})]}),e.jsxs("p",{className:"mt-2 text-xs text-zinc-500",children:["Canonry stores Bing connections per canonical domain. This project is currently mapped to ",e.jsx("code",{children:i.siteUrl}),"."]})]}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Selected site"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.siteUrl})]}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/20 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-zinc-500",children:"Last auth update"}),e.jsx("p",{className:"mt-1 text-sm text-zinc-200",children:i.updatedAt?Xe(i.updatedAt):"—"})]})]})]})]}),e.jsxs(Q,{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:he.eyebrow}),e.jsx("h3",{children:he.title})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:u?.lastInspectedAt?`Last inspected ${Xe(u.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-zinc-800",children:de.map(g=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${S===g.key?"border-zinc-200 text-zinc-200":"border-transparent text-zinc-500 hover:text-zinc-300"}`,onClick:()=>P(g.key),children:g.label},g.key))}),S==="coverage"&&u&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(ls,{label:"Indexed",value:u.summary.indexed,tone:"positive"}),e.jsx(ls,{label:"Not in index",value:u.summary.notIndexed+(u.summary.unknown??0),tone:"negative"}),e.jsx(ls,{label:"Status unknown",value:u.summary.unknown??0,tone:"neutral"}),e.jsx(ls,{label:"Coverage",value:`${u.summary.percentage}%`,tone:"neutral"})]}),u.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-zinc-400",children:["Not Indexed (",u.notIndexed.length,")"]}),e.jsx(C,{size:"sm",variant:"ghost",disabled:T,onClick:Z(W),children:T?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"HTTP"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:u.notIndexed.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:T,onClick:()=>{K(g.url)},children:"Submit"})})]},g.id))})]})})]}),(u.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-zinc-400",children:["Unknown — not yet confirmed (",(u.unknown??[]).length,")"]}),e.jsx(C,{size:"sm",variant:"ghost",disabled:T,onClick:Z(W),children:T?"Submitting…":"Submit all to Bing"})]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-20",children:"Action"})]})}),e.jsx("tbody",{children:(u.unknown??[]).map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.lastCrawledDate?Xe(g.lastCrawledDate):"—"}),e.jsx("td",{className:"py-1.5 px-3 text-right",children:e.jsx("button",{className:"text-[10px] text-zinc-400 hover:text-zinc-200 underline underline-offset-2",disabled:T,onClick:()=>{K(g.url)},children:"Submit"})})]},g.id))})]})})]}),u.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-zinc-400",children:["Indexed (",u.indexed.length,")"]}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Last Crawled"})]})}),e.jsx("tbody",{children:u.indexed.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.lastCrawledDate?Xe(g.lastCrawledDate):"—"})]},g.id))})]})})]})]}),S==="coverage"&&!u&&e.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"No coverage data yet. Inspect URLs to build coverage data."}),S==="inspections"&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-col gap-2 lg:flex-row",children:[e.jsx("input",{type:"text",className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",placeholder:"URL to inspect",value:b,onChange:g=>k(g.target.value),onKeyDown:g=>{g.key==="Enter"&&pe()}}),e.jsx(C,{size:"sm",disabled:!b.trim(),onClick:Z(pe),children:"Inspect"})]}),L&&e.jsxs("div",{className:"rounded border border-zinc-800 bg-zinc-900/40 p-3 text-xs space-y-1",children:[e.jsx("div",{className:"font-medium text-zinc-200",children:L.url}),e.jsxs("div",{className:"text-zinc-400",children:["In Index: ",e.jsx("span",{className:L.inIndex?"text-emerald-400":"text-rose-400",children:L.inIndex?"Yes":"No"})," · ","HTTP: ",L.httpCode??"—"," · ","Crawled: ",L.lastCrawledDate??"—"]})]}),p.length>0&&e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"URL"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-16",children:"Index"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-14",children:"HTTP"}),e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium w-32",children:"Inspected"})]})}),e.jsx("tbody",{children:p.map(g=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(se,{tone:g.inIndex?"positive":"negative",children:g.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:g.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:Xe(g.inspectedAt)})]},g.id))})]})})]}),S==="performance"&&e.jsx("div",{className:"mt-4",children:d.length===0?e.jsx("p",{className:"text-xs text-zinc-500",children:"No Bing performance data available."}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-zinc-800/60",children:e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-zinc-800",children:[e.jsx("th",{className:"text-left py-1.5 px-3 text-zinc-500 font-medium",children:"Query"}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:cs[Nt.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:cs[Nt.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:cs[Nt.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:cs[Nt.Position]})]})}),e.jsx("tbody",{children:d.map((g,O)=>e.jsxs("tr",{className:"border-b border-zinc-800/50",children:[e.jsx("td",{className:"py-1.5 px-3 text-zinc-300 truncate max-w-[480px]",children:g.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-200",children:g.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:g.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:[(Number.isFinite(g.ctr)?g.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:g.averagePosition.toFixed(1)})]},O))})]})})})]})]})}function yl({projectName:t}){const s=ft(),[n,i]=r.useState("google"),[a,l]=r.useState(!0),[o,u]=r.useState("idle"),[m,p]=r.useState(null),f=r.useRef(null),[d,A]=r.useState(!1),[L,D]=r.useState(null),[b,k]=r.useState(null),[$,M]=r.useState(!1),[R,y]=r.useState(null),[j,x]=r.useState(null),[T,q]=r.useState(0);async function E(g=!1){g||l(!0),p(null);try{const[O,H,le]=await Promise.all([s.fetchQuery(yr({client:U})).catch(()=>null),s.fetchQuery({...Ks({client:U,path:{name:t}}),staleTime:Le}).catch(()=>[]),s.fetchQuery({...Wn({client:U,path:{name:t}}),staleTime:Le}).catch(()=>null)]),ue=H.find(ne=>ne.connectionType==="gsc")??null;A(!!O?.google?.configured),M(!!O?.bing?.configured),D(ue),y(le);const[Me,we]=await Promise.all([ue?s.fetchQuery({...qn({client:U,path:{name:t}}),staleTime:Le}).catch(()=>null):Promise.resolve(null),le?.connected?s.fetchQuery({...Yn({client:U,path:{name:t}}),staleTime:Le}).catch(()=>null):Promise.resolve(null)]);k(Me),x(we)}catch(O){p(O instanceof Error?O.message:"Failed to load search console overview")}finally{l(!1)}}async function G(){if(o!=="idle")return;f.current?.abort();const g=new AbortController;f.current=g;const O=g.signal;u("syncing"),p(null);const H=[];try{async function le(){if(!L)return;const ne=await vr(t);if(!ne?.id)return;const te=2e3,ke=Date.now()+12e4;for(;Date.now()<ke;){if(O.aborted||(await new Promise(Ce=>setTimeout(Ce,te)),O.aborted))return;const be=await Un(ne.id).catch(()=>null);if(!be)break;if(["completed","failed","cancelled"].includes(be.status)){be.status!=="completed"&&H.push(`Google sync ${be.status}`);break}}}const ue=10;async function Me(){if(!R?.connected)return;const ne=await s.fetchQuery({...Jn({client:U,path:{name:t}}),staleTime:0}).catch(()=>[]),te=[...new Set(ne.map(je=>je.url))];if(te.length===0){await Nr(t).catch(()=>null);return}for(let je=0;je<te.length;je+=ue){if(O.aborted)return;const ke=te.slice(je,je+ue),Ce=(await Promise.allSettled(ke.map(xe=>Xn(t,xe)))).filter(xe=>xe.status==="rejected").length;Ce>0&&H.push(`${Ce} Bing inspection(s) failed`)}}const we=await Promise.allSettled([le(),Me()]);for(const ne of we)ne.status==="rejected"&&H.push(ne.reason instanceof Error?ne.reason.message:"Sync failed");if(O.aborted)return;u("reloading"),await Promise.all([It(s,"getApiV1ProjectsByNameGoogleGsc"),It(s,"getApiV1ProjectsByNameBing")]),await E(!0),q(ne=>ne+1),H.length>0&&p(`Partial refresh: ${H.join("; ")}`)}catch(le){O.aborted||p(le instanceof Error?le.message:"Refresh failed")}finally{O.aborted||u("idle")}}r.useEffect(()=>(E(),()=>{f.current?.abort()}),[t]);const S=L?"positive":d?"caution":"negative",P=L?"Connected":d?"Ready to connect":"Needs setup",B=b?`${b.summary.percentage}% indexed`:L?"Awaiting coverage":"No coverage data",w=b?`${b.summary.notIndexed} not indexed${b.summary.deindexed>0?` · ${b.summary.deindexed} deindexed`:""}`:L?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",Y=b?.lastSyncedAt??b?.lastInspectedAt??L?.updatedAt??null,ae=R?.connected?"positive":$?"caution":"negative",pe=R?.connected?"Connected":$?"Ready to connect":"Needs setup",K=j?`${j.summary.percentage}% indexed`:R?.connected?"Awaiting coverage":"No coverage data",W=j?j.summary.notIndexed+(j.summary.unknown??0):0,de=j?`${W} not in index`:R?.connected?"Inspect URLs to populate coverage":$?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",he=j?.lastInspectedAt??R?.updatedAt??null;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Q,{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-zinc-500",children:"Scan both engines at a glance, then open the Google or Bing workspace when you need to inspect coverage or take action."})]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",disabled:a||o!=="idle",onClick:()=>{G()},children:a?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"})]}),m&&e.jsx("div",{className:"mb-3 rounded-lg border border-rose-800/40 bg-rose-950/20 px-3 py-2 text-sm text-rose-300",children:m}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(wn,{eyebrow:"Google",title:"Google Search Console",status:a?"Loading…":P,tone:a?"neutral":S,targetLabel:"Selected property",targetValue:L?.propertyId??"No property selected",coverageValue:a?"Loading…":B,note:a?"Loading overview…":w,updatedAt:Y,active:n==="google",onClick:()=>i("google")}),e.jsx(wn,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:a?"Loading…":pe,tone:a?"neutral":ae,targetLabel:"Selected site",targetValue:R?.siteUrl??"No site selected",coverageValue:a?"Loading…":K,note:a?"Loading overview…":de,updatedAt:he,active:n==="bing",onClick:()=>i("bing")})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",role:"tablist","aria-label":"Search engine workspaces",children:[["google","Google"],["bing","Bing"]].map(([g,O])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===g,className:`project-subnav-link ${n===g?"project-subnav-link-active":""}`,onClick:()=>i(g),children:O},g))}),n==="google"&&e.jsx(gc,{projectName:t,refreshNonce:T}),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(bl,{projectName:t,refreshNonce:T})]})]})}function vl({summary:t,onJumpToEvidence:s}){if(!t.hasPreviousRun)return e.jsxs("section",{className:"movement-banner",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),e.jsx("span",{className:"text-zinc-500",children:"First run — no comparison yet"})]});const n=t.gained,i=t.lost,a=n===0&&i===0?"· no changes":n>i?"· improving":i>n?"· declining":"";return e.jsxs("section",{className:"movement-banner",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"movement-banner-label",children:"Since last run"}),n>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-emerald-400 font-medium",onClick:s,title:"Jump to the queries that gained citations",children:["+",n," gained"]}):e.jsx("span",{className:"text-zinc-500",children:"+0 gained"}),e.jsx("span",{className:"text-zinc-700 mx-1",children:"·"}),i>0?e.jsxs("button",{type:"button",className:"movement-banner-chip text-rose-400 font-medium",onClick:s,title:"Jump to the queries that lost citations",children:["−",i," lost"]}):e.jsx("span",{className:"text-zinc-500",children:"−0 lost"}),e.jsx("span",{className:"text-zinc-400 ml-2",children:a})]}),t.gainedQueries?.length||t.lostQueries?.length?e.jsxs("div",{className:"movement-banner-detail",children:[t.gainedQueries&&t.gainedQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-emerald-500/90",children:"Gained:"})," ",e.jsx("span",{className:"text-zinc-300",children:Fn(t.gainedQueries)})]}),t.lostQueries&&t.lostQueries.length>0&&e.jsxs("p",{children:[e.jsx("span",{className:"text-rose-500/90",children:"Lost:"})," ",e.jsx("span",{className:"text-zinc-300",children:Fn(t.lostQueries)})]})]}):null]})}function Fn(t,s=4){return t.length<=s?t.map(i=>`"${i}"`).join(", "):`${t.slice(0,s).map(i=>`"${i}"`).join(", ")}, and ${t.length-s} more`}function Nl({summary:t,projectLabel:s}){const n=t.breakdown;if(n.perCompetitor.length===0)return null;const i=n.projectMentionSnapshots+n.competitorMentionSnapshots;if(i===0)return null;const a=[{label:`${s} (you)`,mentions:n.projectMentionSnapshots,isYou:!0},...n.perCompetitor.map(o=>({label:o.domain,mentions:o.mentionSnapshots,isYou:!1}))].sort((o,u)=>u.mentions-o.mentions),l=a[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:a.map(o=>{const u=o.mentions/i*100;return e.jsxs("li",{className:"mention-share-breakdown-row",children:[e.jsx("span",{className:`mention-share-breakdown-label ${o.isYou?"text-zinc-100 font-medium":"text-zinc-400"}`,children:o.label}),e.jsx("div",{className:"mention-share-breakdown-bar",children:e.jsx("div",{className:`mention-share-breakdown-bar-fill ${o.isYou?"bg-emerald-500/70":"bg-zinc-500/60"}`,style:{width:`${Math.max(o.mentions/l*100,2)}%`}})}),e.jsx("span",{className:"mention-share-breakdown-count",children:o.mentions}),e.jsxs("span",{className:"mention-share-breakdown-share",children:[u.toFixed(1),"%"]})]},o.label)})})]})}const wl={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 zl({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:i}=Gn(),[a,l]=r.useState(null),o=s.rows.length>0;if(t.length===0&&!o)return e.jsx("p",{className:"text-sm text-zinc-500",children:"No outstanding opportunities. Trigger a sweep to surface fresh signals."});const u=["write","investigate","monitor"],m=new Map;for(const p of t){const f=m.get(p.actionGroup)??[];f.push(p),m.set(p.actionGroup,f)}return e.jsxs("div",{className:"opportunities-grid",children:[u.map(p=>{const f=m.get(p);if(!f||f.length===0)return null;const d=wl[p];return e.jsxs("div",{className:`opportunity-card opportunity-card-${p}`,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:f.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:d.subtitle}),e.jsx("div",{className:"opportunity-card-list",children:f.map(A=>{const L=a===A.id,D=A.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${A.tone} ${D?"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400":""}`,onClick:D?()=>l(L?null:A.id):void 0,onKeyDown:D?b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l(L?null:A.id))}:void 0,tabIndex:D?0:void 0,role:D?"button":void 0,"aria-expanded":D?L:void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[D&&e.jsx(vs,{size:12,className:`mt-1 shrink-0 text-zinc-500 transition-transform duration-150 ${L?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug",children:A.title}),A.detail&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:A.detail})]})]})}),L&&e.jsx("div",{className:"opportunity-item-detail",children:A.affectedPhrases.map((b,k)=>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(_s,{state:b.citationState}),e.jsx("span",{className:"text-xs text-zinc-300 truncate",children:b.query}),b.provider&&e.jsx(Et,{provider:b.provider})]}),b.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 whitespace-nowrap",onClick:$=>{$.stopPropagation(),i(b.evidenceId)},children:"View →"})]},b.evidenceId||`${A.id}-${k}`))})]},A.id)})})]},p)}),o&&e.jsx(Sl,{suggestedQueries:s,projectName:n})]})}function Sl({suggestedQueries:t,projectName:s}){const n=br(),[i,a]=r.useState(new Set),l=f=>{a(d=>new Set(d).add(f)),n.mutate({projectName:s,queries:[f]},{onSuccess:()=>{ee({tone:"positive",title:`Tracking "${f}"`}),a(d=>{const A=new Set(d);return A.delete(f),A})},onError:d=>{ee({tone:"negative",title:`Couldn't add "${f}"`,detail:String(d)}),a(A=>{const L=new Set(A);return L.delete(f),L})}})},{rows:o,totalCandidates:u,skippedAlreadyTracked:m}=t,p=m>0?`GSC queries you're getting impressions for · ${m} 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:u>o.length?`${o.length} of ${u}`:o.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:p}),e.jsx("div",{className:"opportunity-card-list",children:o.map(f=>{const d=i.has(f.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-zinc-100 leading-snug truncate",title:f.query,children:f.query}),e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:f.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:d,onClick:()=>l(f.query),children:d?"Adding…":"+ Track"})]},f.query)})})]})}function Ml(t){const{projectId:s}=Ni({from:"/projects/$projectId"}),i=ir()?.dashboard.projects.find(d=>d.project.id===s)?.project.name??null,a=$e({...ar({client:U}),enabled:!i}),l=i??a.data?.find(d=>d.id===s)?.name??null,{commandCenter:o,isLoading:u,refetch:m}=rr(l),p=!i&&a.isLoading||u;return!l&&!i&&a.isSuccess&&!u?e.jsx("div",{className:"page-container",children:e.jsxs(Q,{className:"surface-card empty-card",children:[e.jsx("h1",{children:"Project not found"}),e.jsxs("p",{children:['Could not find a project with ID "',s,'".']}),e.jsx(C,{asChild:!0,children:e.jsx(pt,{to:"/",children:"Return to overview"})})]})}):!o||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(d=>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"})]},d))}),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(d=>e.jsx("div",{className:"skeleton-text-sm w-full"},d))})]})]}):e.jsx(Cl,{model:o,refetch:m,...t})}function kl({items:t,activeTab:s}){const[n,i]=r.useState(!1),a=r.useRef(null);if(r.useEffect(()=>{if(!n)return;const o=m=>{a.current&&!a.current.contains(m.target)&&i(!1)},u=m=>{m.key==="Escape"&&i(!1)};return document.addEventListener("pointerdown",o),document.addEventListener("keydown",u),()=>{document.removeEventListener("pointerdown",o),document.removeEventListener("keydown",u)}},[n]),t.length===0)return null;const l=t.some(o=>o.key===s);return e.jsxs("div",{className:"project-subnav-more",ref:a,children:[e.jsxs("button",{type:"button",className:`project-subnav-link project-subnav-more-trigger ${l?"project-subnav-link-active":""}`,"aria-haspopup":"menu","aria-expanded":n,onClick:()=>i(o=>!o),children:["More",e.jsx(Hn,{className:"h-3.5 w-3.5","aria-hidden":"true"})]}),n?e.jsx("div",{className:"project-subnav-menu",role:"menu",children:t.map(o=>e.jsx(pt,{to:o.href,role:"menuitem",className:`project-subnav-menu-item ${o.key===s?"project-subnav-menu-item-active":""}`,"aria-current":o.key===s?"page":void 0,onClick:()=>i(!1),children:o.label},o.key))}):null]})}function Cl({tab:t,model:s,refetch:n}){const i=wi(),a=ft(),[l,o]=r.useState(!1),[u,m]=r.useState(!1),[p,f]=r.useState(!1),[d,A]=r.useState(""),[L,D]=r.useState(!1),[b,k]=r.useState(null),[$,M]=r.useState(!1),[R,y]=r.useState(""),[j,x]=r.useState(!1),[T,q]=r.useState(!1),[E,G]=r.useState(""),[S,P]=r.useState(!1),[B,w]=r.useState(!1),[Y,ae]=r.useState(""),[pe,K]=r.useState(!1),[W,de]=r.useState(void 0),[he,g]=r.useState(!1),[O,H]=r.useState(null),[le,ue]=r.useState(null),[Me,we]=r.useState(!1),ne=s?.visibilityEvidence??[],te=s?.project.name??"",je=s?.project.displayName||s?.project.name||te,ke=cr(),be=(s?.recentRuns??[]).some(h=>h.kind===ps["answer-visibility"]&&(h.status===pn.running||h.status===pn.queued)),Ce=r.useMemo(()=>(s?.project.locations??[]).map(h=>h.label),[s?.project.locations]),xe=r.useMemo(()=>new Set(ne.map(h=>h.location??"")),[ne]),Re=xe.has(""),Ae=r.useMemo(()=>[...new Set(ne.map(h=>h.query))].sort((h,V)=>h.localeCompare(V)),[ne]),z=r.useMemo(()=>{const h=[...xe].filter(Boolean);return h.length>1?h:Ce},[xe,Ce]);r.useEffect(()=>{if(W===void 0||W===""||!te){ue(null),we(!1);return}we(!0),lr(te,W).then(h=>{ue(h),we(!1)}).catch(()=>{ue(null),we(!1)})},[W,te]);const I=r.useMemo(()=>{if(!le)return null;const h=new Map;for(const V of le){for(const[re,Te]of Object.entries(V.providerRuns??{}))h.set(`${V.query}::${re}`,Te.map(ce=>({runId:ce.runId,citationState:ce.citationState,createdAt:ce.createdAt,answerMentioned:ce.answerMentioned,visibilityState:ce.visibilityState,visibilityTransition:ce.visibilityTransition,mentionState:ce.mentionState,mentionTransition:ce.mentionTransition})));(!V.providerRuns||Object.keys(V.providerRuns).length===0)&&h.set(`${V.query}::`,V.runs.map(re=>({runId:re.runId,citationState:re.citationState,createdAt:re.createdAt,answerMentioned:re.answerMentioned,visibilityState:re.visibilityState,visibilityTransition:re.visibilityTransition,mentionState:re.mentionState,mentionTransition:re.mentionTransition})))}return h},[le]),Pe=r.useMemo(()=>{let h=W!==void 0?ne.filter(V=>W===""?!V.location:V.location===W):ne;if(O){const V=O.toLowerCase();h=h.filter(re=>re.competitorDomains.some(Te=>Te.toLowerCase()===V))}return I?h.map(V=>{const re=I.get(`${V.query}::${V.provider}`)??I.get(`${V.query}::`);return re?{...V,runHistory:re}:V}):h},[ne,W,O,I]);async function We(){try{await ke.mutateAsync({projectName:te,projectLabel:je,sourceAction:"project-run"}),n()}catch{}}async function ye(){m(!0);try{await xr(te),ee({title:"Project deleted",detail:`${je} was removed.`,tone:"positive",dedupeKey:`project:delete:${te}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(h){console.error("Failed to delete project:",h)}finally{m(!1)}}async function jt(){try{const h=await mr(te),V=typeof h=="string"?h:JSON.stringify(h,null,2),re=new Blob([V],{type:"text/yaml"}),Te=URL.createObjectURL(re),ce=document.createElement("a");ce.href=Te,ce.download=`${te}.yaml`,ce.click()}catch(h){ee({title:"Export failed",detail:h instanceof Error?h.message:"Could not export project YAML.",tone:"negative"})}}async function ct(){const h=d.split(`
5
+ `).map(V=>V.trim()).filter(Boolean);if(h.length!==0){D(!0);try{await fr(te,h),n(),A("")}finally{D(!1)}}}async function qe(h){k(h);try{await gr(te,[h]),n()}catch(V){ee({title:"Could not remove query",detail:V instanceof Error?V.message:`Failed to remove "${h}"`,tone:"negative",dedupeKey:"query:remove",dedupeMode:"replace"})}finally{k(null)}}async function lt(){const h=R.trim();if(h){x(!0);try{const re=(await ur(te)).map(ce=>ce.domain),Te=[...new Set([...re,h])];await hr(te,Te),n(),y(""),M(!1)}finally{x(!1)}}}async function Ie(h){try{await pr(te,[h]),n()}catch(V){ee({title:"Could not remove competitor",detail:V instanceof Error?V.message:`Failed to remove ${h}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function Ye(){const h=E.trim();if(h){P(!0);try{const V=s?.project.ownedDomains??[];await gn(te,[...V,h]),n(),G(""),q(!1)}finally{P(!1)}}}async function tt(h){P(!0);try{const V=s?.project.ownedDomains??[];await gn(te,V.filter(re=>re!==h)),n()}finally{P(!1)}}async function bt(){const h=Y.trim();if(h){K(!0);try{const V=s?.project.aliases??[],re=h.toLowerCase();if(V.some(Te=>Te.toLowerCase()===re)){ae(""),w(!1);return}await fn(te,[...V,h]),n(),ae(""),w(!1)}finally{K(!1)}}}async function zt(h){K(!0);try{const V=s?.project.aliases??[];await fn(te,V.filter(re=>re!==h)),n()}finally{K(!1)}}async function Ut(h,V){await jr(h,V),await a.invalidateQueries({queryKey:Kn({client:U})})}const ze=h=>!Number.isNaN(Number.parseInt(h,10)),Oe=`/projects/${s.project.id}`,Fe=[{key:"overview",label:"AI Visibility",href:Oe},{key:"search-console",label:"Search Engines",href:`${Oe}/search-console`},{key:"activity",label:"Activity",href:`${Oe}/activity`},{key:"technical-aeo",label:"Technical AEO",href:`${Oe}/technical-aeo`},{key:"local",label:"Local Presence",href:`${Oe}/local`},{key:"discovery",label:"Query Discovery",href:`${Oe}/discovery`},{key:"backlinks",label:"Backlinks",href:`${Oe}/backlinks`}],ot=[{key:"report",label:"Report",href:`${Oe}/report`}],st={key:"settings",label:"Settings",href:`${Oe}/settings`};return e.jsxs("div",{className:"page-container",children:[l?e.jsxs(Q,{className:"surface-card p-6 mb-6 border-rose-800/60",children:[e.jsx("h3",{className:"text-base font-semibold text-rose-400 mb-2",children:"Delete project?"}),e.jsxs("p",{className:"text-sm text-zinc-400 mb-4",children:["This will permanently delete ",e.jsx("strong",{className:"text-zinc-200",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(C,{type:"button",variant:"destructive",disabled:u,onClick:Z(ye),children:u?"Deleting...":"Yes, delete project"}),e.jsx(C,{type:"button",variant:"outline",disabled:u,onClick:()=>o(!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,(s.project.ownedDomains??[]).length===0&&!T&&e.jsx("button",{type:"button",className:"ml-2 rounded px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800/60 transition-colors",onClick:()=>q(!0),children:"+ add domain"})," "," · ",s.contextLabel]}),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(h=>e.jsx("span",{className:"tag",children:h},h))]}),((s.project.ownedDomains??[]).length>0||T)&&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-zinc-500 mr-1",children:"Also tracking"}),(s.project.ownedDomains??[]).map(h=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[h,e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-zinc-500 hover:bg-zinc-700/40 hover:text-zinc-200 transition-colors",disabled:S,onClick:()=>{tt(h)},"aria-label":`Remove ${h}`,children:"×"})]},h)),T?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-1.5 py-0.5 text-xs text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none w-40",type:"text",placeholder:"docs.example.com",value:E,onChange:h=>G(h.target.value),onKeyDown:h=>{h.key==="Enter"&&Ye()},autoFocus:!0}),e.jsx(C,{type:"button",size:"sm",disabled:!E.trim()||S,onClick:Z(Ye),children:S?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{q(!1),G("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-zinc-700 px-2 py-0.5 text-[10px] uppercase tracking-wide text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors",onClick:()=>q(!0),children:"+ domain"})]}),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-zinc-500 mr-1",children:["Also known as",e.jsx(Ne,{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(h=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-zinc-700/60 bg-zinc-800/40 px-2 py-0.5 text-xs text-zinc-300",children:[h,e.jsx("button",{type:"button",className:"-mr-1 ml-0.5 inline-flex items-center justify-center rounded p-1 leading-none text-zinc-500 hover:bg-zinc-700/40 hover:text-zinc-200 transition-colors",disabled:pe,onClick:()=>{zt(h)},"aria-label":`Remove ${h}`,children:"×"})]},h)),B?e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx("input",{className:"rounded border border-zinc-700 bg-transparent px-1.5 py-0.5 text-xs text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none w-40",type:"text",placeholder:"LlamaParse",value:Y,onChange:h=>ae(h.target.value),onKeyDown:h=>{h.key==="Enter"&&bt()},autoFocus:!0}),e.jsx(C,{type:"button",size:"sm",disabled:!Y.trim()||pe,onClick:Z(bt),children:pe?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{w(!1),ae("")},children:"Cancel"})]}):e.jsx("button",{type:"button",className:"rounded-full border border-dashed border-zinc-700 px-2 py-0.5 text-[10px] uppercase tracking-wide text-zinc-500 hover:text-zinc-300 hover:border-zinc-500 transition-colors",onClick:()=>w(!0),children:"+ alias"})]})]}),e.jsxs("div",{className:"page-header-right",children:[e.jsx("p",{className:"text-sm text-zinc-500",children:s.dateRangeLabel}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(C,{type:"button",variant:"outline",size:"icon",onClick:Z(jt),"aria-label":"Export project as YAML",children:e.jsx(Ys,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(C,{type:"button",variant:"outline",size:"icon",onClick:()=>o(!0),"aria-label":"Delete project",children:e.jsx(Tr,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(C,{type:"button",disabled:ke.isPending||be,onClick:Z(We),children:ke.isPending?"Starting…":be?"Sweep running…":"Run now"})]})]})]}),e.jsxs("nav",{className:"project-subnav","aria-label":"Project sections",children:[Fe.map(h=>e.jsx(pt,{to:h.href,className:`project-subnav-link ${h.key===t?"project-subnav-link-active":""}`,"aria-current":h.key===t?"page":void 0,children:h.label},h.key)),e.jsxs("div",{className:"project-subnav-trailing",children:[e.jsx(kl,{items:ot,activeTab:t}),e.jsx(pt,{to:st.href,className:`project-subnav-link ${t==="settings"?"project-subnav-link-active":""}`,"aria-current":t==="settings"?"page":void 0,children:st.label},st.key)]})]}),t==="overview"?e.jsxs(e.Fragment,{children:[e.jsx(Bc,{projectName:s.project.name}),e.jsx(vl,{summary:s.movementSummary,onJumpToEvidence:()=>document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})}),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:"Competitive landscape"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[s.competitors.length," tracked"]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>M(!$),children:$?"Cancel":"+ Add competitor"})]})]}),e.jsxs("section",{className:"metric-grid",children:[e.jsx("h2",{className:"sr-only",children:"Mention share and competitive gaps"}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Mention share",e.jsx(Ne,{text:"Of all brand mentions in answer text across your tracked queries (you + tracked competitors), the % that were you. Head-to-head AI prominence, not market share. Measured from your most recent run."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.mentionShareSummary.value}),ze(s.mentionShareSummary.value)?e.jsx("span",{className:"text-zinc-600",children:"%"}):null]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.mentionShareSummary.tone}`,style:{width:s.mentionShareSummary.progress!==void 0?`${Math.min(Math.max(s.mentionShareSummary.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.mentionShareSummary.delta})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Mention Gaps",e.jsx(Ne,{text:"Queries where a competitor was mentioned in the answer but your brand wasn't."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.mentionGaps.value}),e.jsxs("span",{className:"text-zinc-600",children:[" / ",s.queryCounts.total]})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.mentionGaps.tone}`,style:{width:s.mentionGaps.progress!==void 0?`${Math.min(Math.max(s.mentionGaps.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.mentionGaps.delta})]}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Citation Gaps",e.jsx(Ne,{text:"Queries where a competitor was cited as a source but you weren't."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.gapQueries.value}),e.jsxs("span",{className:"text-zinc-600",children:[" / ",s.queryCounts.total]})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.gapQueries.tone}`,style:{width:s.gapQueries.progress!==void 0?`${Math.min(Math.max(s.gapQueries.progress,0),100)}%`:"0%"}})}),e.jsx("p",{className:"metric-card-detail",children:s.gapQueries.delta})]})]}),e.jsx(Nl,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name}),$&&e.jsxs("div",{className:"mt-4 mb-3 flex gap-2 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",children:[e.jsx("input",{className:"flex-1 rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",type:"text",placeholder:"competitor.com",value:R,onChange:h=>y(h.target.value),onKeyDown:h=>{h.key==="Enter"&&lt()}}),e.jsx(C,{type:"button",size:"sm",disabled:!R.trim()||j,onClick:Z(lt),children:j?"Adding...":"Add"})]}),e.jsx("div",{className:"mt-4",children:e.jsx(sc,{competitors:s.competitors,onSelectCompetitor:h=>{H(h),document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})},onRemoveCompetitor:h=>{Ie(h)},activeFilter:O})})]}),e.jsxs("section",{id:"evidence-section",className:"page-section-divider scroll-mt-24",children:[e.jsxs("div",{className:"section-head section-head-inline",children:[e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Answer evidence"}),e.jsx("h2",{children:"What the LLMs said"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("p",{className:"supporting-copy",children:[Ae.length," queries tracked"]}),e.jsx(C,{type:"button",variant:"outline",size:"sm",onClick:()=>f(!p),children:p?"Done":"Manage queries"})]})]}),p&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",children:[Ae.length>0?e.jsx("ul",{className:"mb-3 max-h-64 divide-y divide-zinc-800/60 overflow-y-auto rounded border border-zinc-800/60",children:Ae.map(h=>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-zinc-200",title:h,children:h}),e.jsx("button",{type:"button",className:"shrink-0 rounded px-1.5 py-0.5 text-xs text-zinc-500 transition-colors hover:text-rose-400 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-rose-500 disabled:opacity-50","aria-label":`Remove query ${h}`,title:`Stop tracking "${h}"`,disabled:b!==null,onClick:()=>{qe(h)},children:b===h?"Removing…":"Remove"})]},h))}):e.jsx("p",{className:"mb-3 text-xs text-zinc-500",children:"No queries tracked yet. Add some below."}),e.jsx("textarea",{className:"w-full resize-none rounded border border-zinc-700 bg-transparent px-2 py-1.5 text-sm text-zinc-200 placeholder-zinc-600 focus:border-zinc-500 focus:outline-none",rows:3,placeholder:"Enter queries to add, one per line",value:d,onChange:h=>A(h.target.value)}),e.jsxs("div",{className:"mt-2 flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs text-zinc-500",children:[d.split(`
6
+ `).filter(h=>h.trim()).length," to add"]}),e.jsx(C,{type:"button",size:"sm",disabled:!d.trim()||L,onClick:Z(ct),children:L?"Adding...":"Add queries"})]})]}),s.project.locations&&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 ${W===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":W===void 0,onClick:()=>{de(void 0)},children:"All locations"}),s.project.locations.map(h=>e.jsx("button",{className:`filter-chip ${W===h.label?"filter-chip-active":""}`,type:"button","aria-pressed":W===h.label,onClick:()=>{de(h.label),g(!1)},children:h.label},h.label)),Re&&e.jsx("button",{className:`filter-chip ${W===""?"filter-chip-active":""}`,type:"button","aria-pressed":W==="",onClick:()=>{de(""),g(!1)},children:"No location"}),z.length>1&&W===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${he?"filter-chip-active":""}`,type:"button","aria-pressed":he,onClick:()=>g(h=>!h),title:"Side-by-side location comparison",children:"Compare"})]}),O&&e.jsxs("div",{className:"mb-3 flex items-center gap-2 rounded-md border border-rose-900/40 bg-rose-950/20 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] uppercase tracking-wide text-rose-400",children:"Competitor filter"}),e.jsxs("span",{className:"text-sm text-zinc-200",children:["Showing queries where ",e.jsx("span",{className:"font-semibold",children:O})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-zinc-400 hover:text-zinc-200",onClick:()=>H(null),children:"Clear filter ×"})]}),e.jsx(Xr,{evidence:Pe,compareLocations:he})]}),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:"Opportunities"}),e.jsx("h2",{children:"What to act on next"})]})}),e.jsx(zl,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:te})]}),e.jsx(zc,{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:["Visibility by model ",e.jsx(Ne,{text:"Per-model citation rate today. Same query set, different LLMs — gaps between providers point at content / source issues, not the metric. The trend over time is in the chart above (the By engine view)."})]})]})}),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:"Score"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(h=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(Et,{provider:h.provider}),h.model&&e.jsx("span",{className:"text-[11px] font-mono text-zinc-500",children:h.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:`font-semibold ${or[dr(h.score)]}`,children:[h.score,"%"]})}),e.jsxs("td",{className:"text-zinc-500",children:[h.cited," of ",h.total]})]},`${h.provider}::${h.model??"unknown"}`))})]})})]}),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:"Run timeline"}),e.jsx("h2",{children:"Recent execution history"})]})}),e.jsx("div",{className:"run-list",children:s.recentRuns.map(h=>e.jsx(Ar,{run:h},h.id))})]})]}):t==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(hl,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:Ut,onRefresh:()=>{n()}}),e.jsx(gl,{projectName:s.project.name}),e.jsx(jl,{projectName:s.project.name})]}):t==="report"?e.jsx(Xc,{projectName:s.project.name}):t==="discovery"?e.jsx(qc,{projectName:te}):t==="technical-aeo"?e.jsx(Hc,{projectName:s.project.name}):t==="activity"?e.jsx(cc,{projectName:s.project.name}):t==="backlinks"?e.jsx(wc,{projectName:s.project.name}):t==="local"?e.jsx(fc,{projectName:s.project.name,projectId:s.project.id}):e.jsx(yl,{projectName:s.project.name})]})}export{Ml as ProjectPage};