@ainyc/canonry 4.61.1 → 4.62.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 +0,0 @@
1
- import{j as e,r as c,L as yt,n as xt,u as Ue,o as Yt,A as ei,h as ti}from"./vendor-tanstack-Dq7p98wZ.js";import{c as Cs,T as ie,t as si,a as ni,u as gn,C as ii,b as As,P as wt,B as z,h as ai,d as ri,e as ci,f as Fe,g as q,i as Y,I as Pe,j as At,k as li,l as H,m as oi,n as di,o as xi,p as mi,q as fn,r as ui,s as hi,S as dt,v as pi,w as gi,x as fi,y as ji,z as Qs,A as bi,G as Ce,D as Is,E as yi,F as vi,H as Ni,J as wi,K as zi,L as ee,M as Ks,N as jn,O as Si,Q as ki,R as Ci,U as Ai,V as Ii,W as Li,X as Di,Y as $i,Z as Ri,_ as Pi,$ as Ti,a0 as Ei,a1 as Mi,a2 as Oi,a3 as Bi,a4 as _i,a5 as hs,a6 as Gi,a7 as qi,a8 as Fi,a9 as Ui,aa as Qi,ab as ps,ac as bn,ad as yn,ae as vn,af as Ki,ag as Vi,ah as Hi,ai as Wi,aj as Yi,ak as Xi,al as Ji,am as Nn,an as Zi,ao as ea,ap as ta,aq as sa,ar as na,as as ia,at as aa,au as ra,av as ca,aw as la,ax as oa,ay as da,az as xa,aA as ma,aB as ua,aC as is,aD as ha,aE as pa,aF as Vs,aG as ga,aH as fa,aI as ja,aJ as ba,aK as ya,aL as va,aM as Na,aN as wa,aO as za,aP as Sa,aQ as Hs,aR as ka,aS as Ca,aT as wn,aU as Aa,aV as Ws,aW as Ys,aX as Ia,aY as La,aZ as Da,a_ as $a,a$ as Ra,b0 as Pa,b1 as Ta,b2 as Ea,b3 as zn,b4 as Sn,b5 as Ma,b6 as kn,b7 as Oa,b8 as Cn,b9 as Ba,ba as _a,bb as Ut,bc as Ga,bd as qa,be as Fa,bf as Xs}from"./index-BQxaYi-t.js";import{R as Ua}from"./RunRow-ve7H_XIu.js";import{f as gs,C as Xt,a as ft,b as fs,c as Dt,d as We,e as $t,g as Js,h as Qa}from"./ChartPrimitives-Bjow7aaC.js";import{u as Ka,t as Va,R as js}from"./server-traffic-C5f87b84.js";import{R as bs,C as ys,X as vs,Y as Ns,T as ws,L as Ha,A as Lt}from"./vendor-recharts-DWvKDyBF.js";import{C as An,D as Ls,a as Wa,T as Ya}from"./trash-2-BFSmyr_7.js";import"./vendor-radix-B57xfQbP.js";import"./vendor-markdown-DK7fbRNb.js";const Xa=[["path",{d:"M5 12h14",key:"1ays0h"}]],Ja=Cs("minus",Xa);const Za=[["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"}]],er=Cs("unplug",Za);const tr=[["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"}]],sr=Cs("upload",tr),nr=new Set(["a","an","and","for","from","in","near","of","on","or","the","to"]);function In(t){return t.toLowerCase().match(/[a-z0-9]+/g)??[]}function Ln(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 Dn(t){const s=t.meta.location;return s?new Set([s.label,s.city,s.region,s.country].flatMap(In).map(Ln).filter(Boolean)):new Set}function $n(t,s){const n=In(t).map(Ln).filter(Boolean).filter(i=>!nr.has(i)).filter(i=>!s.has(i));return[...new Set(n)].sort().join(" ")}function ir(t){return t.title.match(/"([^"]+)"/)?.[1]??t.successMetric.match(/"([^"]+)"/)?.[1]??t.title}function ar(t,s){const n=Dn(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=$n(ir(l),n);!o||i.has(o)||(i.add(o),a.push(l))}return a}function rr(t){const s=Dn(t),n=t.contentOpportunities;if(n.length<=1||s.size===0)return n;const i=new Set;return n.filter(a=>{const l=$n(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 cr(t,s){return s<=0?null:Math.round((t-s)/s*100)}function rs(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 zs({state:t,label:s}){return e.jsx(ie,{tone:ni(t),children:s??si(t)})}function Zs({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,x)=>e.jsx("div",{className:`h-2.5 w-2.5 rounded-sm ${i[o.citationState]??"bg-zinc-700"} ${o.model&&x>0&&n[x-1]?.model&&n[x-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&&x>0&&n[x-1]?.model&&n[x-1].model!==o.model?"model changed":null].filter(Boolean).join(" — ")},x))}),e.jsx("span",{className:"text-[9px] text-zinc-600 shrink-0",children:l})]})}function lr(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 or=320;function en(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 tn(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 sn(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 x=t.length-1;x>=0&&t[x].citationState===a;x--)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 dr(t,s){return s==="citations"?t:t.map(n=>({...n,citationState:en(n,s),runHistory:n.runHistory.map(i=>({...i,citationState:en(i,s)}))}))}function xr({evidence:t,compareLocations:s=!1,defaultDensity:n="detailed"}){const{openEvidence:i}=gn(),[a,l]=c.useState(new Set),[o,x]=c.useState("mentions"),[u,g]=c.useState(n),b=c.useMemo(()=>{const h=dr(t,o),S=new Map;for(const L of h){const M=L.query,D=s?L.location??null:null,y=s?JSON.stringify([M,D]):M,v=S.get(y)??{key:y,phrase:M,location:D,items:[]};v.items.push(L),S.set(y,v)}return[...S.values()]},[t,o,s]),d=h=>{l(S=>{const L=new Set(S);return L.has(h)?L.delete(h):L.add(h),L})},k=o==="mentions"?"mentioned":"cited",A=o==="mentions"?"Mention History":"Citation History",T=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:()=>x("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:()=>x("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(h=>h.size===b.length?new Set:new Set(b.map(S=>S.key)))},children:a.size===b.length&&b.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":u==="compact",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="compact"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>g("compact"),children:"Compact"}),e.jsx("button",{type:"button",role:"tab","aria-selected":u==="detailed",className:`px-2.5 py-1 text-xs font-medium rounded transition-colors ${u==="detailed"?"bg-zinc-800 text-zinc-100":"text-zinc-400 hover:text-zinc-200"}`,onClick:()=>g("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:A}),e.jsx("th",{scope:"col",children:"Change"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:b.map(({key:h,phrase:S,location:L,items:M})=>{const D=a.has(h),y=M.map(E=>E.citationState),v=y.includes("cited")?"cited":y.includes("emerging")?"emerging":y.includes("lost")?"lost":y.every(E=>E==="pending")?"pending":"not-cited",w=lr(M),Q=M.filter(E=>E.citationState===ii.cited||E.citationState==="emerging").length,X=sn(w,o);return e.jsxs(c.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(h),onKeyDown:E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),d(h))},tabIndex:0,role:"button","aria-expanded":D,children:[e.jsx("td",{children:e.jsx(As,{size:14,className:`transition-transform duration-150 text-zinc-500 ${D?"rotate-90":""}`})}),e.jsx("td",{className:"evidence-query-cell",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium text-zinc-100",children:S}),s&&e.jsx("span",{className:"ml-2 text-[10px] uppercase tracking-wide text-zinc-500",children:L??"No location"}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:M.map(E=>e.jsx(wt,{provider:E.provider},E.id))})]})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(zs,{state:v,label:tn(v,o)}),e.jsxs("span",{className:"text-[11px] text-zinc-500",title:`${Q} of ${M.length} engines ${T}`,children:[Q,"/",M.length]})]})}),e.jsx("td",{children:e.jsx(Zs,{history:w})}),e.jsx("td",{className:"evidence-change-cell",children:X}),e.jsx("td",{})]}),D&&M.map(E=>e.jsxs(c.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(wt,{provider:E.provider})}),e.jsx("td",{children:e.jsx(zs,{state:E.citationState,label:tn(E.citationState,o)})}),e.jsx("td",{children:e.jsx(Zs,{history:E.runHistory})}),e.jsx("td",{className:"evidence-change-cell",children:sn(E.runHistory,o)}),e.jsx("td",{children:e.jsx(z,{variant:"ghost",size:"sm",type:"button",onClick:B=>{B.stopPropagation(),i(E.id)},children:"View"})})]}),u==="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(hr,{item:E,onViewFull:()=>i(E.id)})})]})]},E.id))]},h)})})]})}),e.jsxs("p",{className:"sr-only","aria-live":"polite",children:["Showing ",k==="cited"?"citations (sources)":"mentions (answer text)","."]})]})}function mr(t){const s=(t.matchedTerms??[]).filter(a=>a.trim().length>2),n=[...t.competitorDomains.flatMap(a=>{const l=ri(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 ur(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 hr({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}=ur(t.answerSnippet,or),l=mr(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:ai(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 pr({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 x=i!=null&&i.toLowerCase()===o.domain.toLowerCase(),u=[a?"cursor-pointer hover:bg-zinc-800/30 transition-colors":"",x?"bg-rose-950/20":""].filter(Boolean).join(" ");return e.jsxs("tr",{className:u,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:ci(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:g=>{g.stopPropagation(),n(o.domain)},children:"Remove"})})]},o.id)})})]})})}function nn({eyebrow:t,title:s,status:n,tone:i,targetLabel:a,targetValue:l,coverageValue:o,note:x,updatedAt:u,active:g,onClick:b}){return e.jsxs("button",{type:"button",onClick:b,className:`surface-card w-full text-left transition-colors ${g?"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:x}),e.jsx("span",{children:u?`Updated ${Fe(u)}`:"No recent sync yet"})]})]})}function Qt({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 gr=6,zt="__other__",vt="_socialTotal";function fr(t,s=gr){const n=new Map;for(const b of t)n.set(b.source,(n.get(b.source)??0)+b.sessions);const i=[...n.entries()].sort((b,d)=>d[1]!==b[1]?d[1]-b[1]:b[0].localeCompare(d[0])),a=i.slice(0,s),l=new Set(a.map(([b])=>b)),o=Math.max(0,i.length-s),x=new Map;for(const b of t){let d=x.get(b.date);d||(d={date:b.date,[vt]:0},x.set(b.date,d));const k=l.has(b.source)?b.source:zt;d[k]=(d[k]??0)+b.sessions,d[vt]=(d[vt]??0)+b.sessions}const u=[...x.values()].sort((b,d)=>String(b.date).localeCompare(String(d.date))),g=a.map(([b])=>b);return o>0&&g.push(zt),{data:u,sources:g,otherCount:o}}function Nt(t){return t.replace(/\+/g," ")}function Rn(t,s=30){return t.length<=s?t:t.slice(0,Math.max(1,s-1))+"…"}const jr=["7d","30d","90d","all"],it=$t,Ss=We.textDim,Pn=We.textFaint,It=25;function Kt(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:t.toLocaleString()}function Tn(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 br({projectName:t}){const{data:s,isLoading:n,isError:i}=Ka(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(yt,{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(yt,{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(ie,{tone:Va(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?Tn(l.lastSyncedAt):"never"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(yt,{to:"/traffic/$projectName/$sourceId",params:{projectName:t,sourceId:l.id},className:"text-blue-400 hover:underline text-xs",children:"Detail →"})})]},l.id))})]})})]})}function yr({projectName:t}){return e.jsxs("div",{className:"space-y-10",children:[e.jsx(br,{projectName:t}),e.jsx(vr,{projectName:t})]})}function vr({projectName:t}){const s=xt(),[n,i]=c.useState(null),[a,l]=c.useState(null),[o,x]=c.useState(!0),[u,g]=c.useState(!1),[b,d]=c.useState(!1),[k,A]=c.useState(null),[T,h]=c.useState(null),[S,L]=c.useState("sessions"),[M,D]=c.useState("desc"),[y,v]=c.useState("sessions"),[w,Q]=c.useState("desc"),[X,E]=c.useState("sessions"),[B,C]=c.useState("desc"),[R,O]=c.useState("sessions"),[te,xe]=c.useState("desc"),[fe,J]=c.useState([]),[F,se]=c.useState([]),[ce,le]=c.useState([]),[p,$]=c.useState(!1),[_,he]=c.useState("30d");async function pe(j){x(!0),A(null);try{const G=await s.fetchQuery({...li({client:H,path:{name:t}}),staleTime:At});if(j.current)return;if(i(G),!G.connected){l(null),J([]),se([]),le([]),x(!1);return}const P=_==="all"?void 0:_,[U,$e,et,ge]=await Promise.all([s.fetchQuery({...oi({client:H,path:{name:t},query:P?{window:P}:void 0}),staleTime:At}).then(me=>me),s.fetchQuery({...di({client:H,path:{name:t},query:P?{window:P}:void 0}),staleTime:At}).catch(()=>[]),s.fetchQuery({...xi({client:H,path:{name:t},query:P?{window:P}:void 0}),staleTime:At}).catch(()=>[]),s.fetchQuery({...mi({client:H,path:{name:t},query:P?{window:P}:void 0}),staleTime:At}).catch(()=>[])]);if(j.current)return;l(U),J($e),se(et),le(ge),x(!1)}catch(G){if(j.current)return;A(G instanceof Error?G.message:"Failed to load GA4 data"),x(!1)}}c.useEffect(()=>{const j={current:!1};return pe(j),()=>{j.current=!0}},[t,_,s]);async function ve(){g(!0),A(null),h(null);try{const j=await fn(t);h(`Synced ${j.rowCount.toLocaleString()} page rows, ${j.aiReferralCount.toLocaleString()} AI and ${j.socialReferralCount.toLocaleString()} social referral rows (${j.days} days)`),await s.invalidateQueries({predicate:G=>{const P=G.queryKey[0];return typeof P?._id=="string"&&P._id.startsWith("getApiV1ProjectsByNameGa")}}),await pe({current:!1})}catch(j){A(j instanceof Error?j.message:"Sync failed")}finally{g(!1)}}async function Z(){d(!0),A(null),h(null);try{await ui(t),await s.invalidateQueries({predicate:j=>{const G=j.queryKey[0];return typeof G?._id=="string"&&G._id.startsWith("getApiV1ProjectsByNameGa")}}),i({connected:!1,propertyId:null,clientEmail:null,lastSyncedAt:null,createdAt:null,updatedAt:null}),l(null),h("GA4 disconnected")}catch(j){A(j instanceof Error?j.message:"Disconnect failed")}finally{d(!1)}}function ae(j){S===j?D(G=>G==="desc"?"asc":"desc"):(L(j),D("desc"))}function Ne(j){y===j?Q(G=>G==="desc"?"asc":"desc"):(v(j),Q("desc"))}function ye(j){X===j?C(G=>G==="desc"?"asc":"desc"):(E(j),C("desc"))}function Ae(j){R===j?xe(G=>G==="desc"?"asc":"desc"):(O(j),xe("desc"))}const Se=c.useMemo(()=>a?.topPages?[...a.topPages].sort((j,G)=>{const P=j[S],U=G[S];return typeof P=="string"&&typeof U=="string"?M==="asc"?P.localeCompare(U):U.localeCompare(P):M==="asc"?P-U:U-P}):[],[a?.topPages,S,M]),De=c.useMemo(()=>a?.aiReferrals?[...a.aiReferrals].sort((j,G)=>{const P=j[y],U=G[y];return typeof P=="string"&&typeof U=="string"?w==="asc"?P.localeCompare(U):U.localeCompare(P):w==="asc"?P-U:U-P}):[],[a?.aiReferrals,y,w]),oe=c.useMemo(()=>a?.aiReferralLandingPages?[...a.aiReferralLandingPages].sort((j,G)=>{const P=j[R],U=G[R];return typeof P=="string"&&typeof U=="string"?te==="asc"?P.localeCompare(U):U.localeCompare(P):te==="asc"?P-U:U-P}):[],[a?.aiReferralLandingPages,R,te]),je=c.useMemo(()=>a?.socialReferrals?[...a.socialReferrals].sort((j,G)=>{const P=j[X],U=G[X];return typeof P=="string"&&typeof U=="string"?B==="asc"?P.localeCompare(U):U.localeCompare(P):B==="asc"?P-U:U-P}):[],[a?.socialReferrals,X,B]),{socialChartData:Qe,socialChartSources:N,socialOtherCount:I}=c.useMemo(()=>{const j=fr(ce);return{socialChartData:j.data,socialChartSources:j.sources,socialOtherCount:j.otherCount}},[ce]),{chartData:Me,chartSources:Te,dateRange:Le}=c.useMemo(()=>{const j=[...new Set(fe.map(ge=>ge.source))],G=new Map;for(const ge of F)G.set(ge.date,{_totalSessions:ge.sessions,_organicSessions:ge.organicSessions});const P=new Map;for(const ge of fe){const me=`${ge.date}::${ge.source}`,mt=P.get(me)??0;P.set(me,Math.max(mt,ge.sessions))}for(const[ge,me]of P){const[mt,Et]=ge.split("::");let lt=G.get(mt);lt||(lt={_totalSessions:0,_organicSessions:0},G.set(mt,lt)),lt[Et]=(lt[Et]??0)+me}const U=[...G.entries()].sort(([ge],[me])=>ge.localeCompare(me)).map(([ge,me])=>({date:ge,...me})),$e=U.map(ge=>ge.date),et=$e.length>0?{start:$e[0],end:$e[$e.length-1]}:null;return{chartData:U,chartSources:j,dateRange:et}},[fe,F]);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(Nr,{projectName:t,onConnected:()=>{(async()=>(await s.invalidateQueries({predicate:j=>{const G=j.queryKey[0];return typeof G?._id=="string"&&G._id.startsWith("getApiV1ProjectsByNameGa")}}),await pe({current:!1})))()}});const at=a?.organicSharePctDisplay??"0%",rt=a?.channelBreakdown?.organic.sharePctDisplay??at,Ye=a?.channelBreakdown?.organic.sessions??a?.totalOrganicSessions??0,ct=a?.aiSessionsDeduped??0,Oe=a?.channelBreakdown?.ai.sessions??a?.aiSessionsBySession??0,Xe=a?.channelBreakdown?.ai.sharePctDisplay??a?.aiSharePctBySessionDisplay??"0%",Je=a?new Set(a.aiReferrals.map(j=>j.source.toLowerCase())).size:0,Ke=De[0]??null,m=a?.totalDirectSessions??0,V=a?.directSharePctDisplay??"0%",K=a?.channelBreakdown?.direct.sessions??m,Ee=a?.channelBreakdown?.direct.sharePctDisplay??V,de=a?.channelBreakdown?.other.sessions??a?.otherSessions??0,Zt=a?.channelBreakdown?.other.sharePctDisplay??a?.otherSharePctDisplay??"0%",Ze=a?.socialSessions??0,Pt=a?.socialSharePctDisplay??"0%",es=a?.channelBreakdown?.social.sessions??Ze,Ps=a?.channelBreakdown?.social.sharePctDisplay??Pt,Tt=a?new Set(a.socialReferrals.map(j=>j.source.toLowerCase())).size:0,we=je[0]??null;return e.jsxs(e.Fragment,{children:[k&&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:k}),T&&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:T}),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(z,{variant:"outline",size:"sm",disabled:u,onClick:Y(ve),children:[e.jsx(js,{className:`w-3.5 h-3.5 mr-1.5 ${u?"animate-spin":""}`}),u?"Syncing…":"Sync"]}),e.jsxs(z,{variant:"ghost",size:"sm",className:"text-rose-400 hover:text-rose-300",disabled:b,onClick:Y(Z),children:[e.jsx(er,{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(Pe,{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:jr.map(j=>e.jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-full border transition-colors ${_===j?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>he(j),children:j==="all"?"All":j},j))})]}),a?e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(cs,{value:Kt(a.totalSessions),label:"Total Sessions",subtitle:a.totalSessions.toLocaleString(),tone:"neutral"}),e.jsx(cs,{value:Kt(a.totalOrganicSessions),label:"Organic Sessions",subtitle:`${at} of total`,tone:"positive"}),e.jsx(cs,{value:Kt(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(z,{variant:"outline",size:"sm",disabled:u,onClick:Y(ve),children:[e.jsx(js,{className:`w-3.5 h-3.5 mr-1.5 ${u?"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(Pe,{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."})]})]}),Le&&e.jsxs("p",{className:"text-xs text-zinc-500",children:[new Date(Le.start+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric"})," – ",new Date(Le.end+"T00:00:00").toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})]})]}),Me.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:Te.length>0?"AI vs. total sessions":"All sessions (baseline)"}),Te.length===0&&e.jsx("p",{className:"text-xs text-zinc-500 mt-0.5",children:"AI referral sessions will be overlaid here once detected"})]}),Te.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(bs,{width:"100%",height:"100%",children:e.jsxs(ys,{data:Me,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vs,{dataKey:"date",tick:ft,tickLine:!1,axisLine:{stroke:Xt},tickFormatter:gs}),e.jsx(Ns,{tick:ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ws,{...Dt,labelFormatter:fs,formatter:(j,G)=>{const P=typeof j=="number"?j.toLocaleString():String(j??0),U=String(G??"");return U==="_totalSessions"?[P,"Total Sessions"]:U==="_organicSessions"?[P,"Organic Sessions"]:[P,U]}}),e.jsx(Ha,{wrapperStyle:{fontSize:11,color:We.text},formatter:j=>j==="_totalSessions"?"Total Sessions":j==="_organicSessions"?"Organic Sessions":j}),e.jsx(Lt,{type:"monotone",dataKey:"_totalSessions",stroke:We.textFaint,fill:We.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),Te.map((j,G)=>e.jsx(Lt,{type:"monotone",dataKey:j,stackId:"ai",stroke:it[G%it.length],fill:it[G%it.length],fillOpacity:.4,strokeWidth:1.5},j))]})})})]}),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(qe,{label:"Organic",value:rt,hint:`${Ye.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(qe,{label:"Social",value:Ps,hint:`${es.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(qe,{label:"Direct",value:Ee,hint:`${K.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(qe,{label:"Known AI referrers (lower bound)",value:Xe,hint:`${Oe.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(qe,{label:"Other channels",value:Zt,hint:`${de.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."})]}),Ke&&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:Ke.source})," via ",Ke.medium,", accounting for ",Ke.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 — sources detected"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:a.aiReferrals.length>0?`${Je} 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(Ie,{label:"Source",sortKey:"source",current:y,dir:w,onSort:Ne,align:"left"}),e.jsx(Ie,{label:"Medium",sortKey:"medium",current:y,dir:w,onSort:Ne,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:y,dir:w,onSort:Ne,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:y,dir:w,onSort:Ne,align:"right"})]})}),e.jsx("tbody",{children:De.map(j=>e.jsx(zr,{referral:j,totalSessions:ct},`${j.source}:${j.medium}:${j.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 — landing pages"})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:oe.length>0?`${oe.length} rows`:"No landing-page rows"})]}),oe.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(Ie,{label:"Landing Page",sortKey:"landingPage",current:R,dir:te,onSort:Ae,align:"left"}),e.jsx(Ie,{label:"Source",sortKey:"source",current:R,dir:te,onSort:Ae,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Attribution"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:R,dir:te,onSort:Ae,align:"right"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:R,dir:te,onSort:Ae,align:"right"})]})}),e.jsx("tbody",{children:oe.map(j=>e.jsx(Sr,{row:j},`${j.landingPage}:${j.source}:${j.medium}:${j.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(Pe,{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."})]})]}),Qe.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"})]}),I>0&&e.jsxs("p",{className:"text-xs text-zinc-500",children:["Showing top ",N.length-1," sources · ",I," more grouped as Other"]})]}),e.jsx("div",{className:"h-64",children:e.jsx(bs,{width:"100%",height:"100%",children:e.jsxs(ys,{data:Qe,margin:{top:4,right:4,bottom:0,left:0},children:[e.jsx(vs,{dataKey:"date",tick:ft,tickLine:!1,axisLine:{stroke:Xt},tickFormatter:gs}),e.jsx(Ns,{tick:ft,tickLine:!1,axisLine:!1,allowDecimals:!1,width:36}),e.jsx(ws,{...Dt,labelFormatter:fs,formatter:(j,G)=>{const P=typeof j=="number"?j.toLocaleString():String(j??0),U=String(G??"");if(U===vt)return[P,"Total Social"];if(U===zt){const $e=`Other (${I} source${I===1?"":"s"})`;return[P,$e]}return[P,Nt(U)]}}),e.jsx(Lt,{type:"monotone",dataKey:vt,stroke:Pn,fill:We.surface,fillOpacity:.4,strokeWidth:1.5,dot:!1}),N.map((j,G)=>{const U=j===zt?Ss:it[G%it.length];return e.jsx(Lt,{type:"monotone",dataKey:j,stackId:"social",stroke:U,fill:U,fillOpacity:.4,strokeWidth:1.5},j)})]})})}),e.jsx(Cr,{sources:N,otherCount:I})]}),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(qe,{label:"Social Sessions",value:Kt(Ze),hint:`${Ze.toLocaleString()} sessions`,tone:"positive",tooltip:"Total sessions classified as Organic Social or Paid Social by GA4's default channel grouping."}),e.jsx(qe,{label:"Share of Traffic",value:Pt,hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions that originated from social media platforms."}),e.jsx(qe,{label:"Platforms",value:String(Tt),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."})]}),we&&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:`${we.source} via ${we.medium}`,children:Rn(Nt(we.source),64)}),e.jsxs("p",{className:"text-xs text-sky-200/70 mt-0.5 truncate",title:we.medium,children:["via ",Nt(we.medium)," · ",we.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(qe,{label:"Social Sessions",value:"0",hint:"0 sessions",tone:"neutral",tooltip:"Total sessions attributed to social media platforms."}),e.jsx(qe,{label:"Share of Traffic",value:"0%",hint:"of total sessions",tone:"neutral",tooltip:"Percentage of your total site sessions from social media."}),e.jsx(qe,{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?je.length>It&&!p?`Top ${It} of ${je.length}`:`${je.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(Ie,{label:"Source",sortKey:"source",current:X,dir:B,onSort:ye,align:"left"}),e.jsx(Ie,{label:"Medium",sortKey:"medium",current:X,dir:B,onSort:ye,align:"left"}),e.jsx("th",{className:"py-1 font-medium text-left",children:"Channel"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:X,dir:B,onSort:ye,align:"right"}),e.jsx("th",{className:"py-1 font-medium text-right",children:"Share"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:X,dir:B,onSort:ye,align:"right"})]})}),e.jsx("tbody",{children:(p?je:je.slice(0,It)).map(j=>e.jsx(kr,{referral:j,totalSessions:Ze},`${j.source}:${j.medium}:${j.channelGroup}`))})]})}),je.length>It&&e.jsx("div",{className:"mt-3 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>$(j=>!j),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:p?`Show top ${It}`:`Show all ${je.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(Pe,{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(Ie,{label:"Landing Page",sortKey:"landingPage",current:S,dir:M,onSort:ae,align:"left"}),e.jsx(Ie,{label:"Sessions",sortKey:"sessions",current:S,dir:M,onSort:ae,align:"right"}),e.jsx(Ie,{label:"Organic",sortKey:"organicSessions",current:S,dir:M,onSort:ae,align:"right"}),e.jsx("th",{className:"text-right py-1 font-medium",children:"Organic %"}),e.jsx(Ie,{label:"Users",sortKey:"users",current:S,dir:M,onSort:ae,align:"right"})]})}),e.jsx("tbody",{children:Se.map(j=>e.jsx(wr,{page:j},j.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 ${Tn(a.lastSyncedAt)}`:"Never synced"}),e.jsx("span",{children:a?`${a.topPages.length} pages · ${a.aiReferrals.length} AI rows · ${a.socialReferrals.length} social rows`:""})]})]})}function Nr({projectName:t,onConnected:s}){const[n,i]=c.useState(""),[a,l]=c.useState(null),[o,x]=c.useState(null),[u,g]=c.useState(!1),[b,d]=c.useState(null),k=c.useRef(null),A=c.useCallback(h=>{const S=h.target.files?.[0];if(!S)return;d(null),l(S.name);const L=new FileReader;L.onload=()=>{const M=L.result;try{const D=JSON.parse(M);if(!D.client_email||!D.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)."),x(null);return}x(M)}catch{d("File is not valid JSON. Please upload a service account key file (.json) downloaded from Google Cloud Console."),x(null)}},L.onerror=()=>{d("Failed to read file."),x(null)},L.readAsText(S)},[]);async function T(){if(d(null),!n.trim()){d("Property ID is required.");return}if(!o){d("Please upload a service account key file.");return}g(!0);try{await hi(t,{propertyId:n.trim(),keyJson:o});try{await fn(t)}catch{}s()}catch(h){d(h instanceof Error?h.message:"Failed to connect GA4")}finally{g(!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."}),b&&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:b}),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:h=>i(h.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:k,type:"file",accept:".json,application/json",onChange:A,className:"hidden"}),e.jsxs("button",{type:"button",onClick:()=>k.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(sr,{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(z,{variant:"default",size:"sm",disabled:u||!n.trim()||!o,onClick:Y(T),children:u?"Connecting & syncing…":"Connect GA4"})]})}function Ie({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 En={positive:"text-emerald-400",caution:"text-amber-400",negative:"text-rose-400",neutral:"text-zinc-50"};function cs({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 ${En[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function qe({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(Pe,{text:a})]}),e.jsx("p",{className:`text-xl font-semibold tabular-nums ${En[i]}`,children:t}),e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:n})]})}function wr({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 Mn={session:"Session",first_user:"First Visit",manual_utm:"UTM"},On={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 zr({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=Mn[t.sourceDimension]??t.sourceDimension,a=On[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 Sr({row:t}){const s=Mn[t.sourceDimension]??t.sourceDimension,n=On[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 kr({referral:t,totalSessions:s}){const n=s>0?(t.sessions/s*100).toFixed(1):"0.0",i=t.channelGroup==="Paid Social"?"Paid":"Organic",a=Nt(t.source),l=Nt(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 Cr({sources:t,otherCount:s}){const n=[{key:vt,color:Pn,label:"Total",tooltip:"All social sessions across every source."}];for(let i=0;i<t.length;i++){const a=t[i];if(a===zt)n.push({key:zt,color:Ss,label:`Other (${s})`,tooltip:`${s} smaller source${s===1?"":"s"} grouped together`});else{const l=Nt(a);n.push({key:a,color:it[i%it.length]??Ss,label:Rn(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 Ar=["7d","30d","90d","all"],Vt=500,st=25;function Ir({projectName:t,refreshNonce:s}){const n=xt(),[i,a]=c.useState(!1),[l,o]=c.useState([]),[x,u]=c.useState([]),[g,b]=c.useState([]),[d,k]=c.useState(null),[A,T]=c.useState([]),[h,S]=c.useState([]),[L,M]=c.useState(null),[D,y]=c.useState(""),[v,w]=c.useState(""),[Q,X]=c.useState("30"),[E,B]=c.useState(!1),[C,R]=c.useState("30d"),[O,te]=c.useState({startDate:"",endDate:"",query:"",page:"",limit:"20"}),[xe,fe]=c.useState(0),[J,F]=c.useState(!1),[se,ce]=c.useState(0),[le,p]=c.useState(!1),[$,_]=c.useState(""),[he,pe]=c.useState(!0),[ve,Z]=c.useState(!1),[ae,Ne]=c.useState(!1),[ye,Ae]=c.useState(!1),[Se,De]=c.useState(!1),[oe,je]=c.useState(!1),[Qe,N]=c.useState(!1),[I,Me]=c.useState(null),[Te,Le]=c.useState(!1),[at,rt]=c.useState(!1),[Ye,ct]=c.useState(null),[Oe,Xe]=c.useState(""),[Je,Ke]=c.useState(!1),[m,V]=c.useState(!1),[K,Ee]=c.useState("indexed"),[de,Zt]=c.useState(null),Ze=!!(O.query.trim()||O.page.trim()||de),Pt=de!==null,es=c.useMemo(()=>{if(!de)return g;const{key:r,dir:f}=de;return[...g].sort((W,ne)=>{const ke=r===dt.CTR?Number.isFinite(W.ctr)?W.ctr:0:W[r],Re=r===dt.CTR?Number.isFinite(ne.ctr)?ne.ctr:0:ne[r];return f==="asc"?ke-Re:Re-ke})},[g,de]),[Ps,Tt]=c.useState([]),[we,j]=c.useState(null),[G,P]=c.useState(1);c.useEffect(()=>{P(1)},[I,K,we]);const U=c.useMemo(()=>we?(I?.reasonGroups??[]).find(r=>r.reason===we):void 0,[I,we]),$e=c.useMemo(()=>I?K==="indexed"?I.indexed:K==="deindexed"?I.deindexed:K==="notIndexed"?we?U?.urls??[]:(I.reasonGroups??[]).length===0?I.notIndexed:[]:[]:[],[I,K,we,U]),et=Math.max(1,Math.ceil($e.length/st)),ge=Math.min(Math.max(1,G),et),me=(ge-1)*st,mt=$e.length>st,Et=$e.length===0?0:me+1,lt=Math.min(me+st,$e.length),Bn=c.useMemo(()=>I?.indexed.slice(me,me+st)??[],[I,me]),_n=c.useMemo(()=>I?.notIndexed.slice(me,me+st)??[],[I,me]),Gn=c.useMemo(()=>I?.deindexed.slice(me,me+st)??[],[I,me]),qn=c.useMemo(()=>(U?.urls??[]).slice(me,me+st),[U,me]),[St,Mt]=c.useState(!1),[Ts,re]=c.useState(null),[Es,Ve]=c.useState(null),be=l.find(r=>r.connectionType==="gsc"),Fn=g.length>0||A.length>0||h.length>0,ts=pi(),kt=gi(),ss=fi();async function Ms(r){if(!r){u([]),y("");return}Ne(!0);try{const{sites:f}=await n.fetchQuery({...Ii({client:H,path:{name:t}}),staleTime:Ce});u(f),y(r.propertyId??f[0]?.siteUrl??"")}catch(f){u([]),re(f instanceof Error?f.message:"Failed to load Search Console properties")}finally{Ne(!1)}}async function ut(r){De(!0);const f=r??xe;try{const W=parseInt(O.limit,10)||20,ne=Ze?Vt:W+1,ke=Ze?0:f,Re={limit:String(ne)};O.startDate&&(Re.startDate=O.startDate),O.endDate&&(Re.endDate=O.endDate),O.query&&(Re.query=O.query),O.page&&(Re.page=O.page),ke>0&&(Re.offset=String(ke)),C&&C!=="all"&&!O.startDate&&(Re.window=C);const Be=await n.fetchQuery({...yi({client:H,path:{name:t},query:Re}),staleTime:Ce});Ze?(F(!1),b(Be),ce(Be.length),p(!0)):(F(Be.length>W),b(Be.slice(0,W)),ce(0),p(!1))}catch(W){b([]),F(!1),ce(0),re(W instanceof Error?W.message:"Failed to load GSC performance data")}finally{De(!1)}}async function ns(){try{const r={};O.startDate&&(r.startDate=O.startDate),O.endDate&&(r.endDate=O.endDate),C&&C!=="all"&&!O.startDate&&(r.window=C);const f=await n.fetchQuery({...vi({client:H,path:{name:t},query:r}),staleTime:Ce});k(f)}catch{k(null)}}async function Ot(){je(!0);try{const r=$.trim()||void 0,f={limit:"20"};r&&(f.url=r);const[W,ne]=await Promise.all([n.fetchQuery({...Ci({client:H,path:{name:t},query:f}),staleTime:Ce}),n.fetchQuery({...Ai({client:H,path:{name:t}}),staleTime:Ce})]);T(W),S(ne)}catch(r){T([]),S([]),re(r instanceof Error?r.message:"Failed to load GSC inspection history")}finally{je(!1)}}async function Os(){Le(!0);try{const[r,f]=await Promise.all([n.fetchQuery({...jn({client:H,path:{name:t}}),staleTime:Ce}),n.fetchQuery({...Si({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>[])]);Me(r),Tt(f)}catch(r){Me(null),Tt([]),re(r instanceof Error?r.message:"Failed to load coverage data")}finally{Le(!1)}}async function Bs(r){Mt(!0),re(null);try{const f=await Ks(t,{urls:r}),{succeeded:W,failed:ne,total:ke}=f.summary;ee({title:"Indexing requested",detail:ne===0?`${W} URL${W!==1?"s":""} submitted for indexing.`:`${W}/${ke} submitted successfully, ${ne} failed.`,tone:ne===0?"positive":"caution",dedupeKey:`gsc:indexing:${t}`,dedupeMode:"replace"})}catch(f){re(f instanceof Error?f.message:"Failed to request indexing")}finally{Mt(!1)}}async function Un(){Mt(!0),re(null);try{const r=await Ks(t,{urls:[],allUnindexed:!0}),{succeeded:f,failed:W,total:ne}=r.summary;ee({title:"Indexing requested",detail:W===0?`${f} unindexed URL${f!==1?"s":""} submitted for indexing.`:`${f}/${ne} submitted successfully, ${W} failed.`,tone:W===0?"positive":"caution",dedupeKey:`gsc:indexing-all:${t}`,dedupeMode:"replace"})}catch(r){re(r instanceof Error?r.message:"Failed to request indexing")}finally{Mt(!1)}}async function Bt(){if(Oe.trim()){Ke(!0),re(null);try{await zi(t,"gsc",Oe.trim()),await n.invalidateQueries({predicate:r=>{const f=r.queryKey[0];return typeof f?._id=="string"&&f._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(r=>r.map(f=>f.connectionType==="gsc"?{...f,sitemapUrl:Oe.trim()}:f)),ee({title:"Sitemap URL saved",detail:`${t} will use the updated sitemap URL.`,tone:"positive",dedupeKey:`gsc:sitemap:${t}`,dedupeMode:"drop"}),Xe("")}catch(r){re(r instanceof Error?r.message:"Failed to save sitemap URL")}finally{Ke(!1)}}}async function _s(){re(null);try{const r=await kt.mutateAsync({projectName:t,projectLabel:t});ct(r.sitemaps),o(f=>f.map(W=>W.connectionType==="gsc"?{...W,sitemapUrl:r.primarySitemapUrl}:W))}catch{}}async function Qn(){rt(!0),re(null);try{const r=await Di(t);n.setQueryData($i({client:H,path:{name:t}}),r),ct(r.sitemaps),r.sitemaps.length===0&&Ve("No sitemaps found in this GSC property. Submit a sitemap in Google Search Console first.")}catch(r){re(r instanceof Error?r.message:"Failed to list sitemaps")}finally{rt(!1)}}async function Gs(){pe(!0),re(null);try{const[r,f]=await Promise.all([bi().catch(()=>null),n.fetchQuery({...Is({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>[])]);a(!!r?.google?.configured),o(f);const W=f.find(ne=>ne.connectionType==="gsc");await Promise.all([Ms(W),ut(),ns(),Ot(),Os()])}finally{pe(!1)}}c.useEffect(()=>{Gs()},[t,s]),c.useEffect(()=>{fe(0),ut(0),ns()},[C]);const qs=c.useRef(!1);c.useEffect(()=>{if(!qs.current){qs.current=!0;return}fe(0),ut(0)},[Pt]);async function Kn(){if(!i){re("Google OAuth app credentials are not configured yet. Set them on the Settings page first.");return}Z(!0),re(null),Ve(null);try{const{authUrl:r}=await wi(t,"gsc");if(!r.startsWith("https://accounts.google.com/")){re("Unexpected OAuth redirect URL. Please try again.");return}const f=window.open(r,"_blank","width=600,height=700");if(!f){window.location.assign(r);return}Ve("Finish the Google consent flow in the popup, then close it to refresh this project.");const W=window.setInterval(()=>{f.closed&&(window.clearInterval(W),Ve(null),n.invalidateQueries({predicate:ne=>{const ke=ne.queryKey[0];return typeof ke?._id=="string"&&ke._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),Gs())},1e3)}catch(r){re(r instanceof Error?r.message:"Failed to start OAuth flow")}finally{Z(!1)}}async function Vn(){re(null),Ve(null);try{await Ni(t,"gsc"),await n.invalidateQueries({predicate:r=>{const f=r.queryKey[0];return typeof f?._id=="string"&&f._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(r=>r.filter(f=>f.connectionType!=="gsc")),u([]),y("")}catch(r){re(r instanceof Error?r.message:"Failed to disconnect")}}async function Hn(){if(D){Ae(!0),re(null);try{await Li(t,"gsc",D),await n.invalidateQueries({predicate:r=>{const f=r.queryKey[0];return typeof f?._id=="string"&&f._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),o(r=>r.map(f=>f.connectionType==="gsc"?{...f,propertyId:D}:f)),ee({title:"GSC property updated",detail:`${t} is now linked to ${D}.`,tone:"positive",dedupeKey:`gsc:property:${t}`,dedupeMode:"drop"})}catch(r){re(r instanceof Error?r.message:"Failed to save GSC property")}finally{Ae(!1)}}}async function Wn(){re(null),Ve(null);try{await ts.mutateAsync({projectName:t,projectLabel:t,opts:{days:parseInt(Q,10)||void 0,full:E||void 0}}),await n.invalidateQueries({predicate:r=>{const f=r.queryKey[0];return typeof f?._id=="string"&&f._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}})}catch{}}async function Fs(){if(v.trim()){N(!0),re(null),Ve(null);try{const r=await ki(t,v.trim());await n.invalidateQueries({predicate:f=>{const W=f.queryKey[0];return typeof W?._id=="string"&&W._id.startsWith("getApiV1ProjectsByNameGoogleGsc")}}),M(r),w(""),await Ot()}catch(r){re(r instanceof Error?r.message:"Failed to inspect URL")}finally{N(!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"})]})}),Ts&&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:[Ts,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>re(null),children:"×"})]}),Es&&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:[Es,e.jsx("button",{type:"button",className:"ml-2 text-emerald-400 hover:text-emerald-200",onClick:()=>Ve(null),children:"×"})]}),he?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading…"}):e.jsxs("div",{className:"space-y-3",children:[be?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:be.domain}),e.jsx("span",{className:"text-zinc-700",children:"·"}),e.jsxs("span",{children:["Last updated ",Fe(be.updatedAt)]}),e.jsx("button",{type:"button",className:"ml-auto text-zinc-500 transition-colors hover:text-rose-400",onClick:Y(Vn),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(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(z,{type:"button",variant:"outline",size:"sm",disabled:ve,onClick:Y(Kn),children:ve?"Opening…":"Connect Google Search Console"}):e.jsx(z,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsx(yt,{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."})]})]})]}),be&&!be.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(z,{type:"button",size:"sm",disabled:kt.isPending||!be.propertyId,onClick:Y(_s),children:kt.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:Oe,onChange:r=>Xe(r.target.value),onKeyDown:r=>r.key==="Enter"&&void Bt()}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:Je||!Oe.trim(),onClick:Y(Bt),children:Je?"Saving…":"Save sitemap URL"})]})]})]})]})}),(be||Fn)&&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(z,{type:"button",variant:"outline",size:"sm",disabled:St,onClick:()=>{Un()},children:St?"Requesting…":`Request indexing (${I.notIndexed.length})`}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Te,onClick:()=>{Os()},children:Te?"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 r=I.summary.indexed+I.summary.notIndexed,f=r>0?I.summary.indexed/r:0,W=r>0?I.summary.notIndexed/r:0,ne=54,ke=2*Math.PI*ne,Re=ke*(1-f),Be=ke*W,ht=ke*f;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:ne,fill:"none",stroke:"rgba(255,255,255,0.04)",strokeWidth:"14"}),e.jsx("circle",{cx:"64",cy:"64",r:ne,fill:"none",stroke:Js.positiveDeep,strokeWidth:"14",strokeDasharray:ke,strokeDashoffset:Re,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:ne,fill:"none",stroke:We.textFaint,strokeWidth:"14",strokeDasharray:`${Be} ${ke-Be}`,strokeDashoffset:-ht,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:[(f*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(r=>{const f=r==="indexed"?I.indexed.length:r==="notIndexed"?I.notIndexed.length:I.deindexed.length,W=r==="indexed"?"Indexed":r==="notIndexed"?"Not Indexed":"Deindexed";return e.jsxs("button",{type:"button",className:`rounded-full px-3 py-1 text-xs font-medium transition-colors ${K===r?"bg-zinc-700 text-zinc-100":"text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200"}`,onClick:()=>{Ee(r),j(null)},children:[W," (",f,")"]},r)})}),e.jsxs("div",{className:"mt-3 overflow-x-auto",children:[K==="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:Bn.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.crawlTime?r.crawlTime.split("T")[0]:"—"}),e.jsx("td",{className:"text-zinc-400",children:r.isMobileFriendly===!0?"Yes":r.isMobileFriendly===!1?"No":"—"})]},r.id))})]}),K==="notIndexed"&&!we&&(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(r=>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:()=>j(r.reason),onKeyDown:f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),j(r.reason))},tabIndex:0,role:"button","aria-label":`View ${r.reason} pages`,children:[e.jsx("td",{className:"text-zinc-200",children:r.reason}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:r.count})]},r.reason))})]}),K==="notIndexed"&&!we&&(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:_n.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.coverageState??"Unknown"})]},r.id))})]}),K==="notIndexed"&&we&&(()=>{const r=(I.reasonGroups??[]).find(f=>f.reason===we);return r?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:()=>j(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:r.reason}),e.jsxs("p",{className:"mt-1 text-xs text-zinc-500",children:[r.count," affected page",r.count!==1?"s":""]})]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:St,onClick:()=>{Bs(r.urls.map(f=>f.url))},children:St?"Requesting…":`Request indexing (${r.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:qn.map(f=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:f.url}),e.jsx("td",{className:"text-zinc-400",children:f.crawlTime?f.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:St,onClick:()=>{Bs([f.url])},title:"Request indexing",children:"Index"})})]},f.id))})]})]}):null})(),K==="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:Gn.map((r,f)=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.previousState}),e.jsx("td",{className:"text-zinc-400",children:r.currentState}),e.jsx("td",{className:"text-zinc-400",children:r.transitionDate.split("T")[0]})]},`${r.url}-${f}`))})]}),(K==="indexed"&&I.indexed.length===0||K==="notIndexed"&&!we&&I.notIndexed.length===0||K==="deindexed"&&I.deindexed.length===0)&&e.jsx("p",{className:"text-sm text-zinc-500",children:"No URLs in this category."}),mt&&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:Et.toLocaleString("en-US")}),"–",e.jsx("span",{className:"text-zinc-300",children:lt.toLocaleString("en-US")})," of"," ",e.jsx("span",{className:"text-zinc-300",children:$e.length.toLocaleString("en-US")})," URLs"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>P(r=>Math.max(1,r-1)),disabled:ge<=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(Qa,{className:"size-3.5"}),"Prev"]}),e.jsxs("span",{className:"tabular-nums",children:["Page ",e.jsx("span",{className:"text-zinc-200",children:ge})," of"," ",e.jsx("span",{className:"text-zinc-200",children:et})]}),e.jsxs("button",{type:"button",onClick:()=>P(r=>Math.min(et,r+1)),disabled:ge>=et,"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(As,{className:"size-3.5"})]})]})]})]})]}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:Te?"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:Ar.map(r=>e.jsx("button",{type:"button",role:"tab","aria-selected":C===r,className:`px-2.5 py-1 text-xs rounded-full border transition-colors ${C===r?"bg-zinc-700 border-zinc-600 text-zinc-50":"border-zinc-800 text-zinc-400 hover:border-zinc-700 hover:text-zinc-300"}`,onClick:()=>R(r),children:r==="all"?"All":r},r))}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Se,onClick:()=>{fe(0),ut(0),ns()},children:Se?"Loading…":"Apply filters"})]})]}),d&&d.daily.length>0&&(()=>{const r=d.daily,f=Math.max(...r.map(ue=>ue.impressions),1),{clicks:W,impressions:ne,ctr:ke}=d.totals,Re=(ke*100).toFixed(1),Be=700,ht=220,_e={top:12,bottom:36,left:48,right:12},Yn=Be-_e.left-_e.right,pt=ht-_e.top-_e.bottom,Ct=Yn/r.length,_t=Math.max(Math.min(Ct*.35,24),4),Us=Math.max(_t*.15,1),Xn=ue=>{if(ue<=0)return 1;const He=Math.pow(10,Math.floor(Math.log10(ue))),Ge=ue/He,tt=Ge<=1.5?1.5:Ge<=3?3:Ge<=5?5:10;return Math.ceil(tt*He)},Gt=4,qt=Math.ceil(Xn(f)/Gt)*Gt,Jn=Array.from({length:Gt+1},(ue,He)=>qt/Gt*He),Zn=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:W.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:ne.toLocaleString()})]})]}),e.jsxs("span",{className:"text-xs text-zinc-500",children:["CTR ",e.jsxs("span",{className:"text-amber-400 tabular-nums font-medium",children:[Re,"%"]})]})]}),e.jsx("div",{className:"relative w-full",style:{aspectRatio:`${Be} / ${ht}`},children:e.jsxs("svg",{viewBox:`0 0 ${Be} ${ht}`,className:"h-full w-full",children:[Jn.map((ue,He)=>{const Ge=_e.top+pt-ue/qt*pt;return e.jsxs("g",{children:[e.jsx("line",{x1:_e.left,y1:Ge,x2:Be-_e.right,y2:Ge,stroke:"rgba(255,255,255,0.06)",strokeWidth:"1"}),e.jsx("text",{x:_e.left-6,y:Ge+3.5,textAnchor:"end",fill:We.text,fontSize:"10",fontFamily:"inherit",children:Zn(ue)})]},`t-${He}`)}),r.map((ue,He)=>{const Ge=_e.left+Ct*He+Ct/2,tt=ue.impressions/qt*pt,Ft=ue.clicks/qt*pt;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:Ge-_t-Us/2,y:_e.top+pt-tt,width:_t,height:Math.max(tt,1),rx:2,fill:$t[1],opacity:.85}),e.jsx("rect",{x:Ge+Us/2,y:_e.top+pt-Ft,width:_t,height:Math.max(Ft,1),rx:2,fill:Js.positiveDeep,opacity:.85})]},ue.date)}),(()=>{const ue=Math.min(r.length,7);return Array.from({length:ue},(He,Ge)=>{const tt=r.length===1?0:Math.round(Ge/(ue-1)*(r.length-1)),Ft=_e.left+Ct*tt+Ct/2;return e.jsx("text",{x:Ft,y:ht-8,textAnchor:"middle",fill:We.textDim,fontSize:"10",fontFamily:"inherit",children:r[tt].date.slice(5)},`xl-${tt}`)})})()]})})]})})(),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:O.startDate,onChange:r=>te(f=>({...f,startDate:r.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:O.endDate,onChange:r=>te(f=>({...f,endDate:r.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:O.query,onChange:r=>te(f=>({...f,query:r.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:O.page,onChange:r=>te(f=>({...f,page:r.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:O.limit,onChange:r=>te(f=>({...f,limit:r.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 ",Vt.toLocaleString()," matching rows load so sorting covers the full set."]}),g.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(dt).map(r=>e.jsx("th",{className:"text-right","aria-sort":de?.key===r?de.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:()=>Zt(f=>f?.key===r?f.dir==="desc"?{key:r,dir:"asc"}:null:{key:r,dir:"desc"}),children:[ji[r],de?.key===r?de.dir==="desc"?" ↓":" ↑":""]})},r))]})}),e.jsx("tbody",{children:es.map((r,f)=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-400",children:r.date}),e.jsx("td",{className:"max-w-xs truncate text-zinc-200",children:r.query}),e.jsx("td",{className:"max-w-xs truncate text-zinc-400",children:r.page}),e.jsx("td",{className:"text-right tabular-nums text-zinc-300",children:r.clicks.toLocaleString()}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:r.impressions.toLocaleString()}),e.jsxs("td",{className:"text-right tabular-nums text-zinc-400",children:[(Number.isFinite(r.ctr)?r.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"text-right tabular-nums text-zinc-400",children:r.position.toFixed(1)})]},`${r.date}:${r.query}:${r.page}:${f}`))})]})}),le?e.jsx("div",{className:"mt-3 text-xs text-zinc-500",children:e.jsxs("span",{className:"tabular-nums",children:["Showing ",se.toLocaleString()," matching row",se===1?"":"s",se>=Vt?` (capped at ${Vt.toLocaleString()} — narrow the filter to see more)`:""]})}):(xe>0||J)&&(()=>{const r=parseInt(O.limit,10)||20,f=xe+1,W=xe+g.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 ",f.toLocaleString()," – ",W.toLocaleString(),J?"+":""]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Se||xe===0,onClick:()=>{const ne=Math.max(0,xe-r);fe(ne),ut(ne)},children:"Previous"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:Se||!J,onClick:()=>{const ne=xe+r;fe(ne),ut(ne)},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:v,onChange:r=>w(r.target.value),onKeyDown:r=>r.key==="Enter"&&void Fs()}),e.jsx(z,{type:"button",size:"sm",disabled:Qe||!be?.propertyId||!v.trim(),onClick:Y(Fs),children:Qe?"Inspecting…":"Inspect URL"})]}),L&&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:L.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:L.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:Qs(L.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:Fe(L.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(z,{type:"button",variant:"outline",size:"sm",disabled:oe,onClick:()=>{Ot()},children:oe?"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:$,onChange:r=>_(r.target.value)}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:oe,onClick:()=>{Ot()},children:"Apply filter"})]}),A.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:A.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-300",children:r.indexingState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.verdict??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:r.coverageState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Qs(r.isMobileFriendly??null)}),e.jsx("td",{className:"text-zinc-400",children:Fe(r.inspectedAt)})]},r.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"})]})}),h.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:h.map(r=>e.jsxs("tr",{children:[e.jsx("td",{className:"max-w-sm truncate text-zinc-200",children:r.url}),e.jsx("td",{className:"text-zinc-400",children:r.previousState??"Unknown"}),e.jsx("td",{className:"text-zinc-300",children:r.currentState??"Unknown"}),e.jsx("td",{className:"text-zinc-400",children:Fe(r.transitionDate)})]},`${r.url}:${r.transitionDate}`))})]})}):e.jsx("p",{className:"mt-3 text-sm text-zinc-500",children:"No deindexed transitions recorded."})]})]}),be&&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:()=>V(r=>!r),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 ${m?"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"})]})}),m&&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:D,disabled:ae||x.length===0,onChange:r=>y(r.target.value),children:x.length===0?e.jsx("option",{value:"",children:ae?"Loading properties…":"No properties available"}):x.map(r=>e.jsxs("option",{value:r.siteUrl,children:[r.siteUrl," · ",r.permissionLevel]},r.siteUrl))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:ae,onClick:()=>{Ms(be)},children:ae?"Refreshing…":"Refresh properties"}),e.jsx(z,{type:"button",size:"sm",disabled:!D||ye,onClick:Y(Hn),children:ye?"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:Q,onChange:r=>X(r.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:r=>B(r.target.checked)}),"Replace existing imported rows for the requested range"]})]}),e.jsx(z,{type:"button",size:"sm",disabled:ts.isPending||!be.propertyId,onClick:Y(Wn),children:ts.isPending?"Queueing…":"Queue sync"}),!be.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:[be.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:be.sitemapUrl})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:at||!be.propertyId,onClick:()=>{Qn()},children:at?"Loading…":"Browse sitemaps from GSC"}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:kt.isPending||!be.propertyId,onClick:Y(_s),children:kt.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."}),Ye&&Ye.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 (",Ye.length,")"]}),Ye.map(r=>{const f=r.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:r.path}),r.lastSubmitted&&e.jsxs("p",{className:"text-zinc-500",children:["Submitted: ",r.lastSubmitted.split("T")[0]]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-zinc-300",children:[f.indexed," / ",f.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:()=>Xe(r.path),children:"Use"})]})]},r.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:be.sitemapUrl?"Update sitemap URL…":"https://example.com/sitemap.xml",value:Oe,onChange:r=>Xe(r.target.value),onKeyDown:r=>r.key==="Enter"&&Oe.trim()&&void Bt()}),e.jsx(z,{type:"button",size:"sm",disabled:Je||!Oe.trim(),onClick:Y(Bt),children:Je?"Saving…":be.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(z,{type:"button",size:"sm",variant:"outline",disabled:ss.isPending||!be.propertyId,onClick:Y(async()=>{const f=document.getElementById(`gsc-sitemap-inspect-${t}`)?.value?.trim()||be.sitemapUrl||void 0;re(null),Ve(null);try{await ss.mutateAsync({projectName:t,projectLabel:t,opts:{sitemapUrl:f}})}catch{}}),children:ss.isPending?"Queueing…":"Inspect sitemap"})]}),!be.propertyId&&e.jsx("p",{className:"text-xs text-amber-400",children:"Select a Search Console property first."})]})]})]})]})]})]})}const an=["BUSINESS_DIRECTION_REQUESTS","WEBSITE_CLICKS","CALL_CLICKS","BUSINESS_BOOKINGS","BUSINESS_CONVERSATIONS","BUSINESS_IMPRESSIONS_DESKTOP_SEARCH","BUSINESS_IMPRESSIONS_MOBILE_SEARCH","BUSINESS_IMPRESSIONS_DESKTOP_MAPS","BUSINESS_IMPRESSIONS_MOBILE_MAPS"],Lr={BUSINESS_DIRECTION_REQUESTS:"Direction requests",WEBSITE_CLICKS:"Website clicks",CALL_CLICKS:"Call clicks",BUSINESS_BOOKINGS:"Bookings",BUSINESS_CONVERSATIONS:"Conversations",BUSINESS_IMPRESSIONS_DESKTOP_SEARCH:"Search impressions (desktop)",BUSINESS_IMPRESSIONS_MOBILE_SEARCH:"Search impressions (mobile)",BUSINESS_IMPRESSIONS_DESKTOP_MAPS:"Maps impressions (desktop)",BUSINESS_IMPRESSIONS_MOBILE_MAPS:"Maps impressions (mobile)"};function Dr(t){return Lr[t]??t}function rn(t){const s=Object.keys(t),n=an.filter(a=>a in t),i=s.filter(a=>!an.includes(a)).sort();return[...n,...i]}function $r({delta:t}){if(t==null)return e.jsx("span",{className:"text-zinc-600",title:"No prior 7-day window to compare",children:"—"});const s=t>0?"text-emerald-400":t<0?"text-rose-400":"text-zinc-400",n=t>0?"+":"";return e.jsxs("span",{className:`font-mono text-xs ${s}`,children:[n,t,"%"]})}function Rr({projectName:t}){const s=xt(),n=Ue(Is({client:H,path:{name:t}})),i=n.data?.find(h=>h.connectionType==="gbp"),a=!!i,l=Ue({...Ri({client:H,path:{name:t}}),enabled:a}),o=Ue({...Pi({client:H,path:{name:t}}),enabled:a}),x=Ue({...Ti({client:H,path:{name:t}}),enabled:a});function u(){s.invalidateQueries({predicate:h=>{const S=h.queryKey[0];return typeof S?._id=="string"&&S._id.startsWith("getApiV1ProjectsByNameGbp")}})}const g=Yt({...Ei(),onSuccess:()=>{ee("Google Business Profile sync started.","positive"),u()}}),b=Yt({...Mi(),onSuccess:()=>u()});if(n.isLoading||!i)return null;const d=l.data,k=o.data?.locations??[],A=x.data?.keywords??[],T=k.length>0?k[0].accountName:i.domain;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.jsx("h2",{children:"Google Business Profile"}),e.jsx("p",{className:"mt-1 max-w-3xl text-sm leading-6 text-zinc-500",children:"How AI answer engines and Maps surface this business — performance, search terms, booking CTAs, and profile completeness."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ie,{tone:"positive",children:"Connected"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:g.isPending,onClick:()=>g.mutate({client:H,path:{name:t},body:{}}),children:g.isPending?"Syncing…":"Sync"})]})]}),e.jsxs("p",{className:"mb-4 text-xs text-zinc-500",children:[T?e.jsxs(e.Fragment,{children:["Account ",e.jsx("span",{className:"font-mono text-zinc-400",children:T})," · "]}):null,o.data?`${o.data.totalSelected} of ${o.data.totalDiscovered} locations selected`:"Loading locations…"]}),d&&e.jsxs("div",{className:"mb-6",children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Performance · last 7 days vs prior 7"}),rn(d.performance.totals).length===0?e.jsx("p",{className:"text-sm text-zinc-500",children:"No performance data yet — run a sync."}):e.jsx("div",{className:"metric-grid grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:rn(d.performance.totals).map(h=>e.jsxs("div",{className:"metric-card rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:Dr(h)}),e.jsxs("div",{className:"mt-1 flex items-baseline justify-between",children:[e.jsx("span",{className:"font-mono text-lg text-zinc-50",children:(d.performance.totals[h]??0).toLocaleString()}),e.jsx($r,{delta:d.performance.deltaPct[h]})]}),e.jsxs("div",{className:"mt-0.5 text-[11px] text-zinc-600",children:[(d.performance.recent7d[h]??0).toLocaleString()," recent · ",(d.performance.prior7d[h]??0).toLocaleString()," prior"]})]},h))})]}),d&&e.jsxs("div",{className:"mb-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(ls,{label:"Reservation CTA",present:d.placeActions.hasReservationCta}),e.jsx(ls,{label:"Booking CTA",present:d.placeActions.hasBookingCta}),e.jsx(ls,{label:"Direct booking link",present:d.placeActions.hasDirectMerchantCta,absentTone:"caution",absentHint:"Only aggregator/OTA links — AI may surface third-party booking"}),e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:"Lodging profile"}),d.lodging.lodgingLocationCount===0?e.jsx("div",{className:"mt-1 text-sm text-zinc-500",children:"Not a lodging property"}):e.jsxs("div",{className:"mt-1 flex items-baseline justify-between",children:[e.jsxs("span",{className:"font-mono text-lg text-zinc-50",children:[d.lodging.populatedLodgingCount,"/",d.lodging.lodgingLocationCount]}),d.lodging.emptyLodgingCount>0?e.jsxs(ie,{tone:"caution",children:[d.lodging.emptyLodgingCount," empty"]}):e.jsx(ie,{tone:"positive",children:"complete"})]})]})]}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"section-head section-head-inline mb-2",children:[e.jsx("p",{className:"eyebrow eyebrow-soft",children:"Search terms"}),x.data&&x.data.total>0&&e.jsxs("span",{className:"text-[11px] text-zinc-600",children:[x.data.thresholdedPct,"% privacy-thresholded"]})]}),A.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:A.slice(0,25).map(h=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-300",children:h.keyword}),e.jsx("td",{className:"text-right font-mono text-zinc-200",children:h.valueCount!==null?h.valueCount.toLocaleString():e.jsxs("span",{className:"text-zinc-500",title:"Privacy floor — Google withheld the exact count",children:["<",h.valueThreshold]})}),e.jsxs("td",{className:"text-right font-mono text-[11px] text-zinc-600",children:[h.periodStart,"–",h.periodEnd]})]},`${h.locationName}:${h.keyword}`))})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"eyebrow eyebrow-soft mb-2",children:"Locations"}),k.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:k.map(h=>e.jsxs("tr",{children:[e.jsx("td",{className:"text-zinc-200",children:h.displayName}),e.jsx("td",{className:"text-zinc-500",children:h.storefrontAddress??"—"}),e.jsx("td",{children:e.jsx(ie,{tone:h.selected?"positive":"neutral",children:h.selected?"Tracked":"Not tracked"})}),e.jsx("td",{className:"text-right",children:e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:b.isPending,onClick:()=>b.mutate({client:H,path:{name:t,locationName:h.locationName},body:{selected:!h.selected}}),children:h.selected?"Untrack":"Track"})})]},h.id))})]})]})]})})}function ls({label:t,present:s,absentTone:n="neutral",absentHint:i}){return e.jsxs("div",{className:"rounded-lg border border-zinc-800/60 bg-zinc-900/30 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-zinc-500",children:t}),e.jsx("div",{className:"mt-1",title:s?void 0:i,children:s?e.jsx(ie,{tone:"positive",children:"Present"}):e.jsx(ie,{tone:n,children:"Absent"})})]})}function os({children:t,label:s="More info",placement:n="top",className:i}){const a=c.useId(),[l,o]=c.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(Wa,{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 ot=50;function gt(t){return typeof window>"u"?t:`${window.__CANONRY_CONFIG__?.basePath?.replace(/\/$/,"")??""}${t}`}function Ht(t){return t.toLocaleString()}function Pr(t){const s=Number(t);return Number.isFinite(s)?`${(s*100).toFixed(1)}%`:"—"}function Tr(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 Er(t){const s=t.filter(n=>n.kind===bn["backlink-extract"]&&!yn(n.status));return s.length===0?null:s.reduce((n,i)=>n.createdAt>i.createdAt?n:i)}function Mr(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 Or({projectName:t}){const[s,n]=c.useState(null),[i,a]=c.useState(null),[l,o]=c.useState([]),[x,u]=c.useState(null),[g,b]=c.useState(null),[d,k]=c.useState(null),[A,T]=c.useState(Date.now()),[h,S]=c.useState(0),[L,M]=c.useState(!0),[D,y]=c.useState(!1),[v,w]=c.useState(null),Q=c.useRef(null),X=c.useCallback(async()=>{M(!0),w(null);try{const[F,se,ce,le,p]=await Promise.all([Oi().catch(()=>null),Bi(t,{excludeCrawlers:!0}).catch(()=>null),_i(t,{limit:ot,offset:h,excludeCrawlers:!0}).catch(_=>{if(_ instanceof hs&&_.code==="NOT_FOUND")return null;throw _}),Gi(t).catch(()=>[]),qi(t).catch(()=>[])]);u(F),n(se),a(ce),o(le);const $=Er(p);b($),Q.current=$?.id??null}catch(F){w(F instanceof Error?F.message:"Failed to load backlinks")}finally{M(!1)}},[t,h]);c.useEffect(()=>{X()},[X]),c.useEffect(()=>{if(!g)return;const F=g.id;let se=!1;const ce=async()=>{try{const p=await vn(F);if(se)return;yn(p.status)?(b(null),k(p),await X()):b($=>$?.id===p.id?{...$,...p}:$)}catch{}},le=window.setInterval(()=>{ce()},3e3);return()=>{se=!0,window.clearInterval(le)}},[g,X]),c.useEffect(()=>{if(!g)return;const F=window.setInterval(()=>T(Date.now()),1e3);return()=>window.clearInterval(F)},[g]),c.useEffect(()=>{if(!d||d.status==="failed")return;const F=window.setTimeout(()=>k(null),1e4);return()=>window.clearTimeout(F)},[d]);async function E(){y(!0),w(null);try{const F=await Ki(t);b(F),Q.current=F.id}catch(F){F instanceof hs&&F.code==="MISSING_DEPENDENCY"?w("DuckDB is not installed. Visit the Backlinks admin page to install it."):w(F instanceof Error?F.message:"Failed to trigger extract")}finally{y(!1)}}const B=c.useMemo(()=>l.slice().sort((F,se)=>F.queriedAt.localeCompare(se.queriedAt)).map(F=>({date:F.queriedAt,linkingDomains:F.totalLinkingDomains})),[l]),C=i?.rows??[],R=i?.total??0,O=s?.excludedLinkingDomains??0,te=R>ot,xe=Math.floor(h/ot)+1,fe=Math.max(1,Math.ceil(R/ot));return c.useEffect(()=>{h>0&&h>=R&&S(0)},[h,R]),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."]})]})}),v&&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:v})}),g&&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(Fi,{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:g.status}),e.jsxs("span",{className:"text-xs text-zinc-500 tabular-nums",children:[Mr(g.startedAt??null,g.createdAt)," elapsed · refreshing every 3s"]}),e.jsxs("span",{className:"sr-only",children:["now=",A]})]}),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&&!g&&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(An,{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:Ui(d.error)}):d.status!=="failed"?e.jsx("p",{className:"text-xs text-zinc-500 mt-1",children:"Backlinks refreshed from the cached release."}):null]})]})}),J()]});function J(){if(L)return e.jsx(q,{className:"surface-card p-6",children:e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading backlinks…"})});const F=s!==null&&s.totalLinkingDomains>0,se=d?.status==="failed",ce=s!==null&&s.totalLinkingDomains===0&&!se,le=x?.status==="ready",p=x?.status==="failed",$=x&&(x.status==="downloading"||x.status==="querying"||x.status==="queued");return F?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:Ht(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:Ht(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:Pr(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 ",Tr(s.queriedAt),O>0&&e.jsxs(e.Fragment,{children:[" · ",e.jsxs("span",{className:"text-zinc-500",children:[O," crawler/proxy domain",O===1?"":"s"," hidden"]})]})]}),B.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(bs,{width:"100%",height:"100%",children:e.jsxs(ys,{data:B,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:$t[0],stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:$t[0],stopOpacity:0})]})}),e.jsx(vs,{dataKey:"date",tick:ft,stroke:Xt,tickFormatter:gs}),e.jsx(Ns,{tick:ft,stroke:Xt,allowDecimals:!1}),e.jsx(ws,{contentStyle:Dt.contentStyle,labelStyle:Dt.labelStyle,itemStyle:Dt.itemStyle,labelFormatter:fs}),e.jsx(Lt,{type:"monotone",dataKey:"linkingDomains",name:"Referring domains",stroke:$t[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"}),te&&e.jsxs("p",{className:"text-xs text-zinc-600",children:["Page ",xe," of ",fe," · ",Ht(R)," 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:[C.map(_=>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:_.linkingDomain}),e.jsx("td",{className:"px-4 py-2 text-right text-zinc-400 tabular-nums",children:Ht(_.numHosts)})]},_.linkingDomain)),C.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"px-4 py-4 text-sm text-zinc-500",colSpan:2,children:O>0&&R===0?`Every referring domain in this release was a crawler/proxy host (${O} hidden).`:"No referring domains in this release."})})]})]})}),te&&e.jsxs("div",{className:"flex items-center justify-end gap-2 mt-2",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:h===0,onClick:()=>S(_=>Math.max(0,_-ot)),children:"Previous"}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:h+ot>=R,onClick:()=>S(_=>_+ot),children:"Next"})]})]}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 flex-wrap",children:[e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:D||g!==null,onClick:Y(E),children:[e.jsx(Ls,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),g?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsxs(os,{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(z,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:gt("/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(Qi,{className:"h-5 w-5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1",children:[!x&&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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:gt("/backlinks"),children:"Set up backlinks"})})})]}),$&&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 (",x.status,x.phaseDetail?` — ${x.phaseDetail}`:"","). Backlinks will appear here once it finishes."]}),e.jsx("div",{className:"mt-4",children:e.jsx(z,{asChild:!0,type:"button",variant:"outline",size:"sm",children:e.jsx("a",{href:gt("/backlinks"),children:"View sync status"})})})]}),p&&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:x.error??"The workspace release sync failed. Retry from the Backlinks admin page."}),e.jsx("div",{className:"mt-4",children:e.jsx(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:gt("/backlinks"),children:"Go to Backlinks admin"})})})]}),le&&!$&&!ce&&!se&&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:x.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(z,{type:"button",size:"sm",disabled:D||g!==null,onClick:Y(E),children:[e.jsx(ps,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),g?"Extract running…":D?"Queuing…":"Run extract"]}),e.jsxs(os,{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"}),"."]})]})]})]}),se&&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:x?.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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:gt("/backlinks"),children:"Go to Backlinks admin"})})})]}),ce&&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(z,{asChild:!0,type:"button",size:"sm",children:e.jsx("a",{href:gt("/backlinks"),children:"Go to Backlinks admin"})}),e.jsxs(z,{type:"button",variant:"outline",size:"sm",disabled:D||g!==null,onClick:Y(E),children:[e.jsx(ps,{className:"h-4 w-4 mr-1.5","aria-hidden":!0}),g?"Extract running…":D?"Queuing…":"Re-run extract"]}),e.jsxs(os,{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 Br({projectName:t}){const s=Ue({...Hi({client:H,path:{name:t}}),staleTime:Vi}),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(Pe,{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(Pe,{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(_r,{data:n}),e.jsx(Gr,{data:n}),n.competitorGaps.length>0&&e.jsx(Qr,{data:n})]})}function _r({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(Wt,{label:"Cited + mentioned",value:`${n} / ${s}`,helper:"In sources AND named in answer",tone:n>0?"positive":"neutral"}),e.jsx(Wt,{label:"Cited only",value:`${i} / ${s}`,helper:"In sources, not named in answer",tone:i>0?"positive-dim":"neutral"}),e.jsx(Wt,{label:"Mentioned only",value:`${a} / ${s}`,helper:"Named in answer, no source link",tone:a>0?"caution":"neutral"}),e.jsx(Wt,{label:"Invisible",value:`${l} / ${s}`,helper:"No engine cites or mentions",tone:l>0?"negative":"neutral"})]})}function Wt({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 Gr({data:t}){const s=c.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(qr,{}),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(wt,{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(Ja,{className:"inline h-3.5 w-3.5 text-zinc-700","aria-label":"no data"}):e.jsx(Fr,{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 qr(){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(jt,{active:!0,tone:"cited"}),e.jsx("span",{children:"cited (in sources)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(jt,{active:!0,tone:"mentioned"}),e.jsx("span",{children:"mentioned (in answer)"})]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(jt,{active:!1,tone:"cited"}),e.jsx(jt,{active:!1,tone:"mentioned"}),e.jsx("span",{children:"neither"})]})]})}function Fr({provider:t}){const s=Ur(t);return e.jsxs("span",{className:"inline-flex items-center justify-center gap-1",title:s,children:[e.jsx(jt,{active:t.cited,tone:"cited"}),e.jsx(jt,{active:t.mentioned,tone:"mentioned"})]})}function Ur(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 jt({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 Qr({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(Pe,{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(wt,{provider:s.provider})}),e.jsx("td",{className:"text-zinc-300",children:s.citingCompetitors.join(", ")})]},`${s.queryId}::${s.provider}`))})]})})]})}const ks=new Set(["queued","seeding","probing"]);function Kr({projectName:t}){const s=xt(),[n,i]=c.useState(null),[a,l]=c.useState(""),[o,x]=c.useState("100"),u=Ue({...Wi({client:H,path:{name:t},query:{limit:"10"}}),refetchInterval:y=>y.state.data?.some(w=>ks.has(w.status))?3e3:!1}),g=u.data??[];c.useEffect(()=>{!n&&g[0]&&i(g[0].id)},[n,g]);const b=g.find(y=>y.id===n)??null,d=Ue({...Yi({client:H,path:{name:t,id:n??""}}),enabled:!!n,refetchInterval:b&&ks.has(b.status)?3e3:!1}),k=d.data??null,A=Ue({...Xi({client:H,path:{name:t,id:n??""}}),enabled:!!(n&&b?.status==="completed")}),T=Yt({mutationFn:()=>{const y={},v=a.trim();v&&(y.icpDescription=v);const w=Number.parseInt(o,10);return Number.isFinite(w)&&w>0&&(y.maxProbes=w),Ji(t,y)},onSuccess:async y=>{i(y.sessionId),l(""),await ln(s,t,y.sessionId),ee({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=>{ee({title:"Discovery failed to start",detail:y instanceof Error?y.message:"Could not start discovery.",tone:"negative"})}}),h=Yt({mutationFn:y=>{if(!n)throw new Error("Select a completed discovery session first.");return Zi(t,n,y)},onSuccess:async y=>{await ln(s,t,y.sessionId),s.invalidateQueries({queryKey:Nn({client:H})}),s.invalidateQueries({predicate:v=>Array.isArray(v.queryKey)&&v.queryKey[0]==="projects"&&v.queryKey.length>1}),ee({title:"Queries added",detail:Yr(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"})}}),S=k??b,L=A.data??null,M=(L?.queriesByBucket.cited.length??0)+(L?.queriesByBucket.aspirational.length??0),D=c.useMemo(()=>(k?.probes??[]).slice(0,30),[k?.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(z,{type:"button",variant:"outline",size:"sm",disabled:u.isFetching,onClick:()=>{u.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(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=>x(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(z,{type:"button",size:"sm",disabled:T.isPending,onClick:()=>T.mutate(),children:[e.jsx(ps,{size:14}),T.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"})]}),u.isFetching&&e.jsx(ie,{tone:"neutral",children:"Loading"})]}),g.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:g.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:cn(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:S?ds(S.id):"No run selected"})]}),S&&e.jsx(ie,{tone:cn(S.status),children:S.status})]}),S?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(nt,{label:"Questions tested",value:S.probeCount??0}),e.jsx(nt,{label:"Already cited",value:S.citedCount??0,tone:"positive"}),e.jsx(nt,{label:"Opportunities",value:S.aspirationalCount??0,tone:"caution"}),e.jsx(nt,{label:"Low value",value:S.wastedCount??0,tone:"negative"})]}),S.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:S.error}),S.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:S.icpDescription})]}),S.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:S.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."})]}),S?.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(z,{type:"button",size:"sm",disabled:h.isPending||M===0,onClick:()=>h.mutate(void 0),children:[e.jsx(An,{size:14}),h.isPending?"Adding…":"Add recommended queries"]})]}),A.isLoading?e.jsx("p",{className:"text-sm text-zinc-500",children:"Loading recommendations…"}):L?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(nt,{label:"Queries to add",value:M,tone:"positive"}),e.jsx(nt,{label:"Already cited",value:L.queriesByBucket.cited.length,tone:"positive"}),e.jsx(nt,{label:"Opportunities",value:L.queriesByBucket.aspirational.length,tone:"caution"}),e.jsx(nt,{label:"Low value (skipped)",value:L.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."}),L.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:L.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(ie,{tone:"neutral",children:"Loading"})]}),D.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:D.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:Vr(y.bucket),children:Wr(y.bucket)})}),e.jsx("td",{className:"text-zinc-400",children:y.citedDomains.length>0?y.citedDomains.slice(0,3).join(", "):"-"})]},y.id))})]})})]})]})]})]})}function nt({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 cn(t){return t==="completed"?"positive":t==="failed"?"negative":ks.has(t)?"caution":"neutral"}function Vr(t){return t==="cited"?"positive":t==="aspirational"?"caution":t==="wasted-surface"?"negative":"neutral"}const Hr={cited:"Already cited",aspirational:"Opportunity","wasted-surface":"Low value"};function Wr(t){return t?Hr[t]:"Not classified"}function ds(t){return t.length>8?t.slice(0,8):t}function Yr(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 ln(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:ea({client:H})})])}const Xr={critical:"negative",high:"negative",medium:"caution",low:"neutral"};function ze(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 Jr(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 Zr(t){const s=[t.city,t.region,t.country].filter(Boolean).join(", ");return s?`${t.label} (${s})`:t.label}function ec({projectName:t}){const[s,n]=c.useState(!1),[i,a]=c.useState(null),l=Ue(ta({client:H,path:{name:t}}));async function o(){n(!0),a(null);try{await sa(t,"client")}catch(u){const g=u instanceof hs||u instanceof Error?u.message:"Download failed";a(g)}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 u=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:u})})}const x=l.data;return x?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:x.meta.project.displayName}),e.jsxs("p",{className:"page-subtitle",children:[x.meta.project.canonicalDomain," · ",x.meta.project.country," / ",x.meta.project.language.toUpperCase(),x.meta.location?` · Location: ${Zr(x.meta.location)}`:" · No location set"," · ","Generated ",Jr(x.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(z,{variant:"secondary",size:"sm",onClick:Y(o),disabled:s,children:[e.jsx(Ls,{className:"size-4"}),s?"Preparing…":"Download report HTML"]})})]}),e.jsx(cc,{report:x}),e.jsx(hc,{report:x,audience:"client"}),e.jsx(nc,{report:x}),e.jsx(dc,{report:x,audience:"client",projectName:t}),e.jsx(xc,{report:x})]}):null}const on="AI Visibility — Server-Side",dn="AI engine attention",tc="What AI engines actually do in your server logs over the last 7 days — the other half of citations.",sc="Live telemetry from your server logs.";function nc({report:t}){const s=t.serverActivity;if(!s)return null;if(!s.hasData)return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Rt,{eyebrow:dn,title:on,subtitle:sc}),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:cr(s.verifiedCrawlerHits.current+s.unverifiedCrawlerHits.current,s.verifiedCrawlerHits.prior+s.unverifiedCrawlerHits.prior)},i=rs(n,"requests"),a=`${ze(s.verifiedCrawlerHits.current)} verified · ${ze(s.unverifiedCrawlerHits.current)} unverified${i?` · ${i}`:""}`,l=rs(s.aiUserFetchHits,"requests"),o=rs(s.referralArrivals,"sessions"),x=s.byOperator.filter(u=>u.verifiedHits>0||u.unverifiedHits>0||u.userFetchHits>0||u.referralArrivals>0).slice(0,5);return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Rt,{eyebrow:dn,title:on,subtitle:tc}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-3",children:[e.jsx(us,{label:"AI bot requests observed",value:ze(n.current),subtitle:a}),e.jsx(us,{label:"AI user-fetch requests",value:ze(s.aiUserFetchHits.current),subtitle:l||"ChatGPT-User, Perplexity-User, MistralAI-User"}),e.jsx(us,{label:"AI referral sessions",value:ze(s.referralArrivals.current),subtitle:o})]}),x.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:x.map(u=>e.jsxs("tr",{children:[e.jsx("td",{className:"evidence-query-cell",children:u.operator}),e.jsx("td",{children:ze(u.verifiedHits+u.unverifiedHits)}),e.jsx("td",{children:ze(u.userFetchHits)}),e.jsx("td",{children:ze(u.referralArrivals)})]},u.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 ic(t,s){return t.audience==="both"||t.audience===s}const ac={gemini:"Gemini",openai:"ChatGPT",claude:"Claude",perplexity:"Perplexity",local:"Local model","cdp:chatgpt":"ChatGPT (browser)"};function Jt(t){return ac[t]??t.charAt(0).toUpperCase()+t.slice(1)}function rc(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 cc({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=rc(t.whatsChanged.citationRate),x=n.providers.length>0?n.providers.map(Jt).join(", "):`${ze(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(xs,{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(xs,{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(xs,{label:"AI tools tested",value:ze(s.providerCount),subtitle:x})]}),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((u,g)=>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(g+1).padStart(2,"0")}),e.jsxs("span",{children:['"',u,'"']})]},g))})]}),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(u=>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:Jt(u.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(u.citationRate,1.5)}%`}})}),e.jsxs("span",{className:"text-right text-sm font-semibold text-zinc-100",children:[u.citationRate,"% ",e.jsxs("span",{className:"font-normal text-zinc-500",children:["(",u.citedCount,"/",u.totalCount,")"]})]})]},u.provider))})]}),t.clientSummary.confidenceNotes.length>0&&e.jsx("div",{className:"mt-4 grid gap-2",children:t.clientSummary.confidenceNotes.map((u,g)=>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:u},g))})]})}function xs({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 lc(t){switch(t){case"immediate":return"Do now";case"short-term":return"This month";case"medium-term":return"Next quarter"}}function oc(t){switch(t){case"high":return"Strong evidence";case"medium":return"Some evidence";case"low":return"Worth trying"}}function dc({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=>ic(d,s)),a=ar(t,i),l=s==="client",o=na(),[x,u]=c.useState(new Set),g=x.size>0?a.filter(d=>!d.targetRef||!x.has(d.targetRef)):a,b=d=>{if(!d.targetRef)return;const k=d.targetRef;u(A=>new Set(A).add(k)),o.mutate({projectName:n,body:{targetRef:k}},{onSuccess:()=>{ee({tone:"positive",title:`Dismissed "${d.title}"`,detail:"Will not appear in future reports until un-dismissed."})},onError:A=>{ee({tone:"negative",title:`Couldn't dismiss "${d.title}"`,detail:String(A)}),u(T=>{const h=new Set(T);return h.delete(k),h})}})};return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Rt,{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."}),g.length===0?e.jsx(Rs,{message:"No recommendations yet — run an AI check to populate this."}):e.jsx("div",{className:"grid gap-3 lg:grid-cols-2",children:g.map((d,k)=>{const A=d.evidence.length>0?d.evidence:d.why,T=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:k+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:aa(d),children:l?lc(d.horizon):ia(d.horizon)}),!l&&e.jsx(ie,{tone:"neutral",children:ra(d.category)}),e.jsx(ie,{tone:"neutral",children:l?oc(d.confidence):`${ca(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(pc,{items:A,limit:3,className:"mt-3"}),T&&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((h,S)=>e.jsx("li",{children:h},S))})]}),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((h,S)=>e.jsx("li",{children:h},S))})]})]}),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:()=>b(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 xn({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 xc({report:t}){const s=t.aiSourceOrigin.topDomains.slice(0,5),n=t.gsc,i=t.indexingHealth,a=rr(t).slice(0,5),l=s.length>0?Math.max(...s.map(u=>u.count)):0,o=n?Math.max(...n.topQueries.slice(0,5).map(u=>u.impressions),1):0,x=s.length>0||n!==null||i!==null||a.length>0;return e.jsxs("section",{className:"page-section-divider",children:[e.jsx(Rt,{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."}),x?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(u=>e.jsx(xn,{label:u.domain+(u.isCompetitor?" (competitor)":""),value:u.count,displayValue:`${ze(u.count)}×`,max:l,barClass:"bg-zinc-400/70"},u.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:[ze(i.indexed)," of ",ze(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:ze(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:ze(n.totalImpressions)})," Google searches and got ",e.jsx("span",{className:"font-semibold text-zinc-200",children:ze(n.totalClicks)})," ",n.totalClicks===1?"click":"clicks"," this period."]}),n.topQueries.length>0&&e.jsx("div",{className:"mt-4 space-y-3",children:n.topQueries.slice(0,5).map(u=>e.jsx(xn,{label:u.query,value:u.impressions,displayValue:`${ze(u.impressions)} ${u.impressions===1?"search":"searches"}`,max:o,barClass:"bg-sky-500/70"},u.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((u,g)=>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:u.query}),e.jsx("p",{className:"mt-0.5 text-xs text-zinc-400",children:la(u.action)})]},g))})]})]}):e.jsx(Rs,{message:"No supporting evidence yet — this fills in after the first AI check."})]})}const mc=14;function Ds(t){return t==="up"?"positive":t==="down"?"negative":"neutral"}function $s(t){return t==="up"?"↑":t==="down"?"↓":"→"}function ms({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=Ds(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:$s(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 mn({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=Ds(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:[ze(s.current)," ",e.jsx("span",{className:"text-sm font-medium",children:$s(s.direction)})]}),e.jsxs("p",{className:"mt-1 text-[11px] text-zinc-500",children:[i,ze(s.deltaAbs)," ",n," vs prior ",mc," days"]})]})}function uc({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=Ds(a.direction),x=o==="positive"?"text-emerald-400":o==="negative"?"text-rose-400":"text-zinc-300";return e.jsxs("tr",{children:[e.jsx("td",{children:i?Jt(a.provider):a.provider}),e.jsxs("td",{children:[a.prior,"%"]}),e.jsxs("td",{children:[a.current,"%"]}),e.jsxs("td",{className:x,children:[l,a.deltaAbs.toFixed(1),"% ",$s(a.direction)]})]},a.provider)})})]})})]})}function un({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:Xr[l.severity],children:oa(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?Jt(l.provider):l.provider})]},l.id))})]})})]})}function hc({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(Rt,{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(Rs,{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(ms,{label:i?"AI links to your website":"Citation rate",delta:n.citationRate,unit:"%"}),e.jsx(ms,{label:i?"AI mentions your name":"Mention rate",delta:n.mentionRate,unit:"%"}),e.jsx(ms,{label:i?"Questions AI answered with you":"Cited queries",delta:n.citedQueryCount,unit:"count"}),e.jsx(mn,{label:i?"Visitors from Google":"GSC clicks",delta:n.gscClicksDelta,countLabel:i?"visits":"clicks"}),e.jsx(mn,{label:i?"Visitors from AI tools":"AI referral sessions",delta:n.aiReferralsDelta,countLabel:i?"visits":"sessions"})]}),e.jsx(uc,{movements:n.providerMovements,audience:s}),e.jsx(un,{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(un,{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 us({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 Rt({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 pc({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 Rs({message:t}){return e.jsx("p",{className:"text-sm text-zinc-500 py-4 text-center",children:t})}function gc({project:t,onUpdateProject:s,onRefresh:n}){const[i,a]=c.useState(!1),[l,o]=c.useState(!1),[x,u]=c.useState(null),[g,b]=c.useState(t.displayName),[d,k]=c.useState(t.canonicalDomain),[A,T]=c.useState(t.country),[h,S]=c.useState(t.language),[L,M]=c.useState(t.ownedDomains??[]),[D,y]=c.useState(""),[v,w]=c.useState(t.aliases??[]),[Q,X]=c.useState(""),[E,B]=c.useState(null),[C,R]=c.useState(!1),[O,te]=c.useState(!1),[xe,fe]=c.useState(""),[J,F]=c.useState(""),[se,ce]=c.useState(""),[le,p]=c.useState(""),[$,_]=c.useState("");c.useEffect(()=>{i||(b(t.displayName),k(t.canonicalDomain),T(t.country),S(t.language),M(t.ownedDomains??[]),w(t.aliases??[]))},[t,i]);function he(){a(!1),u(null),b(t.displayName),k(t.canonicalDomain),T(t.country),S(t.language),M(t.ownedDomains??[]),w(t.aliases??[]),y(""),X("")}function pe(){const N=D.trim();N&&(L.includes(N)||M([...L,N]),y(""))}function ve(N){M(L.filter(I=>I!==N))}function Z(){const N=Q.trim();if(!N)return;const I=N.toLowerCase();v.some(Me=>Me.toLowerCase()===I)||w([...v,N]),X("")}function ae(N){w(v.filter(I=>I!==N))}async function Ne(){if(!(!g.trim()||!d.trim()||!A.trim()||!h.trim())){o(!0),u(null);try{await s(t.name,{displayName:g.trim(),canonicalDomain:d.trim(),ownedDomains:L,aliases:v,country:A.trim(),language:h.trim()}),a(!1),ee({title:"Project settings saved",detail:`${g.trim()} was updated.`,tone:"positive",dedupeKey:`project:update:${t.name}`,dedupeMode:"replace"})}catch(N){u(N instanceof Error?N.message:"Failed to save")}finally{o(!1)}}}async function ye(){const N=xe.trim(),I=J.trim(),Me=se.trim(),Te=le.trim();if(!(!N||!I||!Me||!Te)){R(!0),B(null);try{const Le={label:N,city:I,region:Me,country:Te};$.trim()&&(Le.timezone=$.trim()),await ma(t.name,Le),n(),fe(""),F(""),ce(""),p(""),_(""),te(!1),ee({title:"Location added",detail:`${N} is now available for ${t.name}.`,tone:"positive",dedupeKey:`project:location:add:${t.name}:${N}`,dedupeMode:"drop"})}catch(Le){B(Le instanceof Error?Le.message:"Failed to add location")}finally{R(!1)}}}async function Ae(N){R(!0),B(null);try{await xa(t.name,N),n(),ee({title:"Location removed",detail:`${N} was removed from ${t.name}.`,tone:"positive",dedupeKey:`project:location:remove:${t.name}:${N}`,dedupeMode:"drop"})}catch(I){B(I instanceof Error?I.message:"Failed to remove location")}finally{R(!1)}}async function Se(N){R(!0),B(null);try{await da(t.name,N),n(),ee({title:"Default location updated",detail:`${N} is now the default for ${t.name}.`,tone:"positive",dedupeKey:`project:location:default:${t.name}`,dedupeMode:"replace"})}catch(I){B(I instanceof Error?I.message:"Failed to set default location")}finally{R(!1)}}const De=g!==t.displayName||d!==t.canonicalDomain||A!==t.country||h!==t.language||JSON.stringify(L)!==JSON.stringify(t.ownedDomains??[])||JSON.stringify(v)!==JSON.stringify(t.aliases??[]),oe="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",je="block text-xs font-medium text-zinc-400 mb-1",Qe=xe.trim()&&J.trim()&&se.trim()&&le.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(z,{type:"button",variant:"outline",size:"sm",onClick:()=>a(!0),children:"Edit settings"})]}),x&&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:[x,e.jsx("button",{type:"button",className:"ml-2 text-rose-400 hover:text-rose-200",onClick:()=>u(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:je,children:"Display name"}),e.jsx("input",{className:oe,type:"text",value:g,onChange:N=>b(N.target.value),placeholder:"My Project"})]}),e.jsxs("div",{children:[e.jsx("label",{className:je,children:"Canonical domain"}),e.jsx("input",{className:oe,type:"text",value:d,onChange:N=>k(N.target.value),placeholder:"example.com"})]}),e.jsxs("div",{children:[e.jsx("label",{className:je,children:"Country"}),e.jsx("input",{className:oe,type:"text",value:A,onChange:N=>T(N.target.value),placeholder:"US",maxLength:2})]}),e.jsxs("div",{children:[e.jsx("label",{className:je,children:"Language"}),e.jsx("input",{className:oe,type:"text",value:h,onChange:N=>S(N.target.value),placeholder:"en"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:je,children:"Owned domains"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:L.map(N=>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:[N,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ve(N),"aria-label":`Remove ${N}`,children:"×"})]},N))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${oe} flex-1`,type:"text",placeholder:"docs.example.com",value:D,onChange:N=>y(N.target.value),onKeyDown:N=>N.key==="Enter"&&(N.preventDefault(),pe())}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:!D.trim(),onClick:pe,children:"Add"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:je,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:v.map(N=>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:[N,e.jsx("button",{type:"button",className:"ml-0.5 text-zinc-500 hover:text-zinc-200 transition-colors",onClick:()=>ae(N),"aria-label":`Remove ${N}`,children:"×"})]},N))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{className:`${oe} flex-1`,type:"text",placeholder:"Facebook",value:Q,onChange:N=>X(N.target.value),onKeyDown:N=>N.key==="Enter"&&(N.preventDefault(),Z())}),e.jsx(z,{type:"button",variant:"outline",size:"sm",disabled:!Q.trim(),onClick:Z,children:"Add"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-zinc-800/60",children:[e.jsx(z,{type:"button",disabled:l||!De||!g.trim()||!d.trim(),onClick:Y(Ne),children:l?"Saving...":"Save changes"}),e.jsx(z,{type:"button",variant:"outline",disabled:l,onClick:he,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(N=>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:N},N))}):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(N=>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:N},N))}):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:()=>B(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(N=>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 ${N.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:[N.label,N.label===t.defaultLocation?" ★":""]})}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:N.city}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:N.region}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-300",children:N.country}),e.jsx("td",{className:"py-1.5 pr-3 text-zinc-500",children:N.timezone??"—"}),e.jsx("td",{className:"py-1.5",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[N.label!==t.defaultLocation&&e.jsx("button",{type:"button",disabled:C,onClick:()=>{Se(N.label)},className:"text-[10px] text-zinc-500 hover:text-emerald-400 transition-colors disabled:opacity-40","aria-label":`Set ${N.label} as default location`,children:"Set default"}),e.jsx("button",{type:"button",disabled:C,onClick:()=>{Ae(N.label)},className:"text-[10px] text-zinc-500 hover:text-rose-400 transition-colors disabled:opacity-40","aria-label":`Remove location ${N.label}`,children:"Remove"})]})})]},N.label))})]}):e.jsx("p",{className:"text-zinc-500 text-xs mb-2",children:"No locations configured"}),O?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:oe,type:"text",value:xe,onChange:N=>fe(N.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:oe,type:"text",value:J,onChange:N=>F(N.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:oe,type:"text",value:se,onChange:N=>ce(N.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:oe,type:"text",value:le,onChange:N=>p(N.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:oe,type:"text",value:$,onChange:N=>_(N.target.value),placeholder:"America/New_York"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[e.jsx(z,{type:"button",size:"sm",disabled:C||!Qe,onClick:Y(ye),children:C?"Adding...":"Add location"}),e.jsx(z,{type:"button",size:"sm",variant:"outline",disabled:C,onClick:()=>{te(!1),B(null)},children:"Cancel"})]})]}):e.jsx(z,{type:"button",size:"sm",variant:"outline",onClick:()=>te(!0),children:"+ Add location"})]})]})]})})})]})}const fc=[{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"}],hn=["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 jc({projectName:t}){const[s,n]=c.useState("loading"),[i,a]=c.useState(!1),[l,o]=c.useState("daily"),[x,u]=c.useState(6),[g,b]=c.useState(""),[d,k]=c.useState("UTC"),[A,T]=c.useState(!1),[h,S]=c.useState(""),[L,M]=c.useState(!1),[D,y]=c.useState(!1),[v,w]=c.useState(null);c.useEffect(()=>{ua(t).then(n).catch(()=>n(null))},[t]);const Q=()=>{if(s&&s!=="loading"){const C=pa(s.preset??null,s.cronExpr);o(C.freq),u(C.hour),b(C.customCron);const R=hn.includes(s.timezone);k(R?s.timezone:"Other"),T(!R),S(R?"":s.timezone)}else o("daily"),u(6),b(""),k("UTC"),T(!1),S("");w(null),a(!0)},X=async()=>{M(!0),w(null);try{const R={timezone:A?h.trim()||"UTC":d};l==="custom"?R.cron=g.trim():R.preset=fa(l,x);const O=await Vs(t,R);n(O),a(!1),ee({title:"Schedule saved",detail:is(O.preset??null,O.cronExpr,O.timezone),tone:"positive",dedupeKey:`schedule:${t}`,dedupeMode:"replace"})}catch(C){w(C instanceof Error?C.message:"Failed to save schedule")}finally{M(!1)}},E=async()=>{if(!(!s||s==="loading")){M(!0),w(null);try{const C={timezone:s.timezone,enabled:!s.enabled};s.preset?C.preset=s.preset:C.cron=s.cronExpr;const R=await Vs(t,C);n(R),ee({title:R.enabled?"Schedule resumed":"Schedule paused",detail:is(R.preset??null,R.cronExpr,R.timezone),tone:"positive",dedupeKey:`schedule:toggle:${t}`,dedupeMode:"replace"})}catch(C){w(C instanceof Error?C.message:"Failed to update schedule")}finally{M(!1)}}},B=async()=>{y(!0),w(null);try{await ga(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(C){w(C instanceof Error?C.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(z,{type:"button",variant:"outline",size:"sm",onClick:Q,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:is(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(z,{type:"button",variant:"outline",size:"sm",disabled:L,onClick:Y(E),children:s.enabled?"Pause":"Resume"}),e.jsx(z,{type:"button",variant:"ghost",size:"sm",disabled:D,onClick:Y(B),children:D?"Removing...":"Remove"})]})]}),v&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:v})]}),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:C=>o(C.target.value),children:fc.map(C=>e.jsx("option",{value:C.value,children:C.label},C.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:x,disabled:l==="twice-daily"||l==="custom",onChange:C=>u(parseInt(C.target.value)),children:Array.from({length:24},(C,R)=>e.jsx("option",{value:R,children:ha(R)},R))})]})]}),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:g,onChange:C=>b(C.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:A?"Other":d,onChange:C=>{C.target.value==="Other"?(T(!0),k("Other")):(T(!1),k(C.target.value))},children:[hn.map(C=>e.jsx("option",{value:C,children:C},C)),e.jsxs("option",{value:"Other",children:["Other (enter manually)","…"]})]}),A&&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:h,onChange:C=>S(C.target.value)})]}),v&&e.jsx("p",{className:"text-rose-400 text-sm",children:v}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),w(null)},children:"Cancel"}),e.jsx(z,{type:"button",size:"sm",disabled:L||l==="custom"&&!g.trim(),onClick:Y(X),children:L?"Saving...":"Save schedule"})]})]})]})}const bc=[{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 yc({projectName:t}){const[s,n]=c.useState("loading"),[i,a]=c.useState(!1),[l,o]=c.useState(""),[x,u]=c.useState(["citation.lost","citation.gained"]),[g,b]=c.useState(!1),[d,k]=c.useState(null),[A,T]=c.useState({}),[h,S]=c.useState(new Set);c.useEffect(()=>{ja(t).then(n).catch(()=>n([]))},[t]);const L=v=>{u(w=>w.includes(v)?w.filter(Q=>Q!==v):[...w,v])},M=async()=>{if(!(!l.trim()||x.length===0)){b(!0),k(null);try{const v=await ba(t,{channel:"webhook",url:l.trim(),events:x});n(w=>w==="loading"?[v]:[...w,v]),o(""),u(["citation.lost","citation.gained"]),a(!1),ee({title:"Webhook added",detail:`Notifications will be sent to ${v.url}.`,tone:"positive",dedupeKey:`notification:add:${t}`,dedupeMode:"drop"})}catch(v){k(v instanceof Error?v.message:"Failed to add webhook")}finally{b(!1)}}},D=async v=>{if(!h.has(v)){S(w=>new Set(w).add(v));try{await va(t,v),n(w=>w==="loading"?w:w.filter(Q=>Q.id!==v)),ee({title:"Webhook removed",detail:`${t} no longer sends notifications to this endpoint.`,tone:"positive",dedupeKey:`notification:remove:${t}:${v}`,dedupeMode:"drop"})}catch(w){k(w instanceof Error?w.message:"Failed to remove webhook")}finally{S(w=>{const Q=new Set(w);return Q.delete(v),Q})}}},y=async v=>{T(w=>({...w,[v]:{state:"testing"}}));try{const w=await ya(t,v);T(Q=>({...Q,[v]:{state:w.ok?"ok":"fail",status:w.status}})),w.ok&&ee({title:"Test notification sent",detail:`Webhook returned status ${w.status}.`,tone:"positive",dedupeKey:`notification:test:${t}:${v}`,dedupeMode:"replace"})}catch{T(w=>({...w,[v]:{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(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!i),k(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:v=>o(v.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:bc.map(v=>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:x.includes(v.value),onChange:()=>L(v.value)}),e.jsx("span",{className:"text-sm text-zinc-300",children:v.label})]},v.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(z,{type:"button",variant:"outline",size:"sm",onClick:()=>{a(!1),k(null)},children:"Cancel"}),e.jsx(z,{type:"button",size:"sm",disabled:g||!l.trim()||x.length===0,onClick:Y(M),children:g?"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(v=>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:v.urlHost,children:v.urlDisplay??v.url})}),e.jsx("td",{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:v.events.map(w=>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:w.replace("."," ")},w))})}),e.jsx("td",{children:e.jsx(ie,{tone:v.enabled?"positive":"neutral",children:v.enabled?"Active":"Paused"})}),e.jsx("td",{children:e.jsxs("div",{className:"flex items-center gap-1 justify-end",children:[A[v.id]&&(()=>{const w=A[v.id],Q=w.state==="testing"?"Sending…":w.state==="ok"?`Delivered${w.status?` (${w.status})`:""}`:`Failed${w.status?` (${w.status})`:""}`;return e.jsx(ie,{tone:w.state==="ok"?"positive":w.state==="fail"?"negative":"neutral",children:Q})})(),e.jsx(z,{variant:"ghost",size:"sm",type:"button",disabled:A[v.id]?.state==="testing",onClick:()=>{y(v.id)},children:"Test"}),e.jsx(z,{variant:"ghost",size:"sm",type:"button",disabled:h.has(v.id),onClick:()=>{D(v.id)},children:h.has(v.id)?"Removing…":"Remove"})]})})]},v.id))})]}),d&&e.jsx("p",{className:"text-rose-400 text-sm mt-2",children:d})]})]})}function bt(t,s){return t.invalidateQueries({predicate:n=>{const i=n.queryKey[0];return typeof i?._id=="string"&&i._id.startsWith(s)}})}function vc({projectName:t,refreshNonce:s}){const n=xt(),[i,a]=c.useState(null),[l,o]=c.useState([]),[x,u]=c.useState(null),[g,b]=c.useState([]),[d,k]=c.useState([]),[A,T]=c.useState(null),[h,S]=c.useState(""),[L,M]=c.useState(""),[D,y]=c.useState(""),[v,w]=c.useState(!0),[Q,X]=c.useState(!1),[E,B]=c.useState(null),[C,R]=c.useState("performance");c.useEffect(()=>{O()},[t,s]);async function O(){w(!0),B(null);try{const p=await n.fetchQuery({...zn({client:H,path:{name:t}}),staleTime:Ce});if(a(p),p.connected){const[$,_,he,pe]=await Promise.all([n.fetchQuery({...Sn({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>null),n.fetchQuery({...kn({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>[]),n.fetchQuery({...Ba({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>[]),p.siteUrl?Promise.resolve([]):n.fetchQuery({..._a({client:H,path:{name:t}}),staleTime:Ce}).then(ve=>ve.sites).catch(()=>[])]);u($),b(_),k(he),o(pe)}else u(null),b([]),k([]),o([])}catch(p){B(p instanceof Error?p.message:"Failed to load Bing data")}finally{w(!1)}}async function te(){if(L.trim()){B(null);try{const p=await Ga(t,L.trim());await bt(n,"getApiV1ProjectsByNameBing"),M(""),p.availableSites.length>0&&o(p.availableSites),await O()}catch(p){B(p instanceof Error?p.message:"Failed to connect")}}}async function xe(){try{await qa(t),await bt(n,"getApiV1ProjectsByNameBing"),a(null),o([]),u(null),b([]),k([]),T(null),y(""),B(null)}catch(p){B(p instanceof Error?p.message:"Failed to disconnect")}}async function fe(){if(D)try{await Fa(t,D),await bt(n,"getApiV1ProjectsByNameBing"),await O()}catch(p){B(p instanceof Error?p.message:"Failed to set site")}}async function J(){if(h.trim())try{const p=await Cn(t,h.trim());await bt(n,"getApiV1ProjectsByNameBing"),T(p),b($=>[p,...$])}catch(p){B(p instanceof Error?p.message:"Inspection failed")}}async function F(p){X(!0),B(null);try{const $=await Xs(t,{urls:[p]}),{succeeded:_,failed:he,total:pe}=$.summary;ee({title:"Bing submission requested",detail:he===0?`${_} URL submitted to Bing.`:`${_}/${pe} submitted successfully, ${he} failed.`,tone:he===0?"positive":"caution",dedupeKey:`bing:indexing:${t}:${p}`,dedupeMode:"replace"})}catch($){const _=$ instanceof Error?$.message:"Submission failed";B(_),ee({title:"Bing submission failed",detail:_,tone:"negative",dedupeKey:`bing:indexing:${t}:${p}`,dedupeMode:"replace"})}finally{X(!1)}}async function se(){X(!0),B(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 p=await Xs(t,{allUnindexed:!0}),{succeeded:$,failed:_,total:he}=p.summary;ee({title:"Bing submissions requested",detail:_===0?`${$}/${he} URL${he!==1?"s":""} submitted to Bing.`:`${$}/${he} submitted successfully, ${_} failed.`,tone:_===0?"positive":"caution",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}catch(p){const $=p instanceof Error?p.message:"Batch submission failed";B($),ee({title:"Bing submissions failed",detail:$,tone:"negative",dedupeKey:`bing:indexing-all:${t}`,dedupeMode:"replace"})}finally{X(!1)}}if(v)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(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:L,onChange:p=>M(p.target.value),onKeyDown:p=>{p.key==="Enter"&&te()}}),e.jsx(z,{size:"sm",disabled:!L.trim(),onClick:Y(te),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(ie,{tone:"positive",children:"Connected"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:Y(xe),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?Fe(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:D,onChange:p=>y(p.target.value),children:[e.jsx("option",{value:"",children:"Select a site..."}),l.map(p=>e.jsxs("option",{value:p.url,children:[p.url,p.verified?" (verified)":""]},p.url))]}),e.jsx(z,{size:"sm",disabled:!D,onClick:Y(fe),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 ce=[{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"}],le=ce.find(p=>p.key===C)??ce[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(ie,{tone:"positive",children:"Connected"}),e.jsx(z,{size:"sm",variant:"ghost",onClick:Y(xe),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?Fe(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:le.eyebrow}),e.jsx("h3",{children:le.title})]}),e.jsx("p",{className:"text-xs text-zinc-500",children:x?.lastInspectedAt?`Last inspected ${Fe(x.lastInspectedAt)}`:"No inspection history yet"})]}),e.jsx("div",{className:"flex gap-1 border-b border-zinc-800",children:ce.map(p=>e.jsx("button",{className:`px-3 py-1.5 text-xs font-medium border-b-2 transition-colors ${C===p.key?"border-zinc-200 text-zinc-200":"border-transparent text-zinc-500 hover:text-zinc-300"}`,onClick:()=>R(p.key),children:p.label},p.key))}),C==="coverage"&&x&&e.jsxs("div",{className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-4",children:[e.jsx(Qt,{label:"Indexed",value:x.summary.indexed,tone:"positive"}),e.jsx(Qt,{label:"Not in index",value:x.summary.notIndexed+(x.summary.unknown??0),tone:"negative"}),e.jsx(Qt,{label:"Status unknown",value:x.summary.unknown??0,tone:"neutral"}),e.jsx(Qt,{label:"Coverage",value:`${x.summary.percentage}%`,tone:"neutral"})]}),x.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 (",x.notIndexed.length,")"]}),e.jsx(z,{size:"sm",variant:"ghost",disabled:Q,onClick:Y(se),children:Q?"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:x.notIndexed.map(p=>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:p.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:p.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:Q,onClick:()=>{F(p.url)},children:"Submit"})})]},p.id))})]})})]}),(x.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 (",(x.unknown??[]).length,")"]}),e.jsx(z,{size:"sm",variant:"ghost",disabled:Q,onClick:Y(se),children:Q?"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:(x.unknown??[]).map(p=>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:p.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:p.lastCrawledDate?Fe(p.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:Q,onClick:()=>{F(p.url)},children:"Submit"})})]},p.id))})]})})]}),x.indexed.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"mb-2 text-xs font-medium text-zinc-400",children:["Indexed (",x.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:x.indexed.map(p=>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:p.url}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:p.lastCrawledDate?Fe(p.lastCrawledDate):"—"})]},p.id))})]})})]})]}),C==="coverage"&&!x&&e.jsx("p",{className:"mt-4 text-xs text-zinc-500",children:"No coverage data yet. Inspect URLs to build coverage data."}),C==="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:h,onChange:p=>S(p.target.value),onKeyDown:p=>{p.key==="Enter"&&J()}}),e.jsx(z,{size:"sm",disabled:!h.trim(),onClick:Y(J),children:"Inspect"})]}),A&&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:A.url}),e.jsxs("div",{className:"text-zinc-400",children:["In Index: ",e.jsx("span",{className:A.inIndex?"text-emerald-400":"text-rose-400",children:A.inIndex?"Yes":"No"})," · ","HTTP: ",A.httpCode??"—"," · ","Crawled: ",A.lastCrawledDate??"—"]})]}),g.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:g.map(p=>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:p.url}),e.jsx("td",{className:"py-1.5 px-3",children:e.jsx(ie,{tone:p.inIndex?"positive":"negative",children:p.inIndex?"Yes":"No"})}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:p.httpCode??"—"}),e.jsx("td",{className:"py-1.5 px-3 text-zinc-400",children:Fe(p.inspectedAt)})]},p.id))})]})})]}),C==="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:Ut[dt.Clicks]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-16",children:Ut[dt.Impressions]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:Ut[dt.CTR]}),e.jsx("th",{className:"text-right py-1.5 px-3 text-zinc-500 font-medium w-14",children:Ut[dt.Position]})]})}),e.jsx("tbody",{children:d.map((p,$)=>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:p.query}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-200",children:p.clicks}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:p.impressions}),e.jsxs("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:[(Number.isFinite(p.ctr)?p.ctr*100:0).toFixed(1),"%"]}),e.jsx("td",{className:"py-1.5 px-3 text-right text-zinc-400",children:p.averagePosition.toFixed(1)})]},$))})]})})})]})]})}function Nc({projectName:t}){const s=xt(),[n,i]=c.useState("google"),[a,l]=c.useState(!0),[o,x]=c.useState("idle"),[u,g]=c.useState(null),b=c.useRef(null),[d,k]=c.useState(!1),[A,T]=c.useState(null),[h,S]=c.useState(null),[L,M]=c.useState(!1),[D,y]=c.useState(null),[v,w]=c.useState(null),[Q,X]=c.useState(0);async function E(p=!1){p||l(!0),g(null);try{const[$,_,he]=await Promise.all([s.fetchQuery(Ea({client:H})).catch(()=>null),s.fetchQuery({...Is({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>[]),s.fetchQuery({...zn({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>null)]),pe=_.find(ae=>ae.connectionType==="gsc")??null;k(!!$?.google?.configured),M(!!$?.bing?.configured),T(pe),y(he);const[ve,Z]=await Promise.all([pe?s.fetchQuery({...jn({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>null):Promise.resolve(null),he?.connected?s.fetchQuery({...Sn({client:H,path:{name:t}}),staleTime:Ce}).catch(()=>null):Promise.resolve(null)]);S(ve),w(Z)}catch($){g($ instanceof Error?$.message:"Failed to load search console overview")}finally{l(!1)}}async function B(){if(o!=="idle")return;b.current?.abort();const p=new AbortController;b.current=p;const $=p.signal;x("syncing"),g(null);const _=[];try{async function he(){if(!A)return;const ae=await Ma(t);if(!ae?.id)return;const Ne=2e3,Ae=Date.now()+12e4;for(;Date.now()<Ae;){if($.aborted||(await new Promise(De=>setTimeout(De,Ne)),$.aborted))return;const Se=await vn(ae.id).catch(()=>null);if(!Se)break;if(["completed","failed","cancelled"].includes(Se.status)){Se.status!=="completed"&&_.push(`Google sync ${Se.status}`);break}}}const pe=10;async function ve(){if(!D?.connected)return;const ae=await s.fetchQuery({...kn({client:H,path:{name:t}}),staleTime:0}).catch(()=>[]),Ne=[...new Set(ae.map(ye=>ye.url))];if(Ne.length===0){await Oa(t).catch(()=>null);return}for(let ye=0;ye<Ne.length;ye+=pe){if($.aborted)return;const Ae=Ne.slice(ye,ye+pe),De=(await Promise.allSettled(Ae.map(oe=>Cn(t,oe)))).filter(oe=>oe.status==="rejected").length;De>0&&_.push(`${De} Bing inspection(s) failed`)}}const Z=await Promise.allSettled([he(),ve()]);for(const ae of Z)ae.status==="rejected"&&_.push(ae.reason instanceof Error?ae.reason.message:"Sync failed");if($.aborted)return;x("reloading"),await Promise.all([bt(s,"getApiV1ProjectsByNameGoogleGsc"),bt(s,"getApiV1ProjectsByNameBing")]),await E(!0),X(ae=>ae+1),_.length>0&&g(`Partial refresh: ${_.join("; ")}`)}catch(he){$.aborted||g(he instanceof Error?he.message:"Refresh failed")}finally{$.aborted||x("idle")}}c.useEffect(()=>(E(),()=>{b.current?.abort()}),[t]);const C=A?"positive":d?"caution":"negative",R=A?"Connected":d?"Ready to connect":"Needs setup",O=h?`${h.summary.percentage}% indexed`:A?"Awaiting coverage":"No coverage data",te=h?`${h.summary.notIndexed} not indexed${h.summary.deindexed>0?` · ${h.summary.deindexed} deindexed`:""}`:A?"Run sitemap inspection to populate coverage":d?"Connect Search Console for this domain":"Add Google OAuth credentials in Settings",xe=h?.lastSyncedAt??h?.lastInspectedAt??A?.updatedAt??null,fe=D?.connected?"positive":L?"caution":"negative",J=D?.connected?"Connected":L?"Ready to connect":"Needs setup",F=v?`${v.summary.percentage}% indexed`:D?.connected?"Awaiting coverage":"No coverage data",se=v?v.summary.notIndexed+(v.summary.unknown??0):0,ce=v?`${se} not in index`:D?.connected?"Inspect URLs to populate coverage":L?"Connect Bing Webmaster Tools for this domain":"Add a Bing API key in Settings",le=v?.lastInspectedAt??D?.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 console"}),e.jsx("h2",{children:"Search Engine Intelligence"}),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(z,{type:"button",variant:"outline",size:"sm",disabled:a||o!=="idle",onClick:()=>{B()},children:a?"Loading…":o==="syncing"?"Refreshing Google & Bing…":o==="reloading"?"Reloading workspaces…":"Refresh all"})]}),u&&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:u}),e.jsxs("div",{className:"grid gap-3 lg:grid-cols-2",children:[e.jsx(nn,{eyebrow:"Google",title:"Google Search Console",status:a?"Loading…":R,tone:a?"neutral":C,targetLabel:"Selected property",targetValue:A?.propertyId??"No property selected",coverageValue:a?"Loading…":O,note:a?"Loading overview…":te,updatedAt:xe,active:n==="google",onClick:()=>i("google")}),e.jsx(nn,{eyebrow:"Bing",title:"Bing Webmaster Tools",status:a?"Loading…":J,tone:a?"neutral":fe,targetLabel:"Selected site",targetValue:D?.siteUrl??"No site selected",coverageValue:a?"Loading…":F,note:a?"Loading overview…":ce,updatedAt:le,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(([p,$])=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===p,className:`project-subnav-link ${n===p?"project-subnav-link-active":""}`,onClick:()=>i(p),children:$},p))}),n==="google"&&e.jsx(Ir,{projectName:t,refreshNonce:Q}),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(vc,{projectName:t,refreshNonce:Q})]})]})}function wc({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:pn(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:pn(t.lostQueries)})]})]}):null]})}function pn(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 zc({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,x)=>x.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"}),e.jsx("ul",{className:"mention-share-breakdown-rows",children:a.map(o=>{const x=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:[x.toFixed(1),"%"]})]},o.label)})})]})}const Sc={positive:"rgb(52 211 153)",caution:"rgb(251 191 36)",negative:"rgb(251 113 133)",neutral:"rgb(161 161 170)"};function kc({trend:t,currentScore:s}){if(!t||t.length<2)return e.jsx("span",{className:"text-[11px] text-zinc-600",children:"—"});const n=96,i=24,a=100,l=t.length>1?n/(t.length-1):0,o=t.map((b,d)=>`${(d*l).toFixed(2)},${(i-b/a*i).toFixed(2)}`).join(" "),x=Sc[wn(s)],u=(t.length-1)*l,g=i-t[t.length-1]/a*i;return e.jsxs("svg",{width:n,height:i,viewBox:`0 0 ${n} ${i}`,className:"overflow-visible","aria-label":`Trend ${t.join(", ")}`,role:"img",children:[e.jsx("polyline",{points:o,fill:"none",stroke:x,strokeWidth:1.5,strokeLinejoin:"round",strokeLinecap:"round"}),e.jsx("circle",{cx:u,cy:g,r:2.5,fill:x})]})}const Cc={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 Ac({insights:t,suggestedQueries:s,projectName:n}){const{openEvidence:i}=gn(),[a,l]=c.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 x=["write","investigate","monitor"],u=new Map;for(const g of t){const b=u.get(g.actionGroup)??[];b.push(g),u.set(g.actionGroup,b)}return e.jsxs("div",{className:"opportunities-grid",children:[x.map(g=>{const b=u.get(g);if(!b||b.length===0)return null;const d=Cc[g];return e.jsxs("div",{className:`opportunity-card opportunity-card-${g}`,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:b.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:d.subtitle}),e.jsx("div",{className:"opportunity-card-list",children:b.map(k=>{const A=a===k.id,T=k.affectedPhrases.length>0;return e.jsxs("div",{children:[e.jsx("div",{className:`opportunity-item opportunity-item-${k.tone} ${T?"cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400":""}`,onClick:T?()=>l(A?null:k.id):void 0,onKeyDown:T?h=>{(h.key==="Enter"||h.key===" ")&&(h.preventDefault(),l(A?null:k.id))}:void 0,tabIndex:T?0:void 0,role:T?"button":void 0,"aria-expanded":T?A:void 0,children:e.jsxs("div",{className:"flex items-start gap-1.5 min-w-0",children:[T&&e.jsx(As,{size:12,className:`mt-1 shrink-0 text-zinc-500 transition-transform duration-150 ${A?"rotate-90":""}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-zinc-100 leading-snug",children:k.title}),k.detail&&e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:k.detail})]})]})}),A&&e.jsx("div",{className:"opportunity-item-detail",children:k.affectedPhrases.map((h,S)=>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(zs,{state:h.citationState}),e.jsx("span",{className:"text-xs text-zinc-300 truncate",children:h.query}),h.provider&&e.jsx(wt,{provider:h.provider})]}),h.evidenceId&&e.jsx("button",{type:"button",className:"text-[11px] text-zinc-400 hover:text-zinc-200 whitespace-nowrap",onClick:L=>{L.stopPropagation(),i(h.evidenceId)},children:"View →"})]},h.evidenceId||`${k.id}-${S}`))})]},k.id)})})]},g)}),o&&e.jsx(Ic,{suggestedQueries:s,projectName:n})]})}function Ic({suggestedQueries:t,projectName:s}){const n=Ta(),[i,a]=c.useState(new Set),l=b=>{a(d=>new Set(d).add(b)),n.mutate({projectName:s,queries:[b]},{onSuccess:()=>{ee({tone:"positive",title:`Tracking "${b}"`}),a(d=>{const k=new Set(d);return k.delete(b),k})},onError:d=>{ee({tone:"negative",title:`Couldn't add "${b}"`,detail:String(d)}),a(k=>{const A=new Set(k);return A.delete(b),A})}})},{rows:o,totalCandidates:x,skippedAlreadyTracked:u}=t,g=u>0?`GSC queries you're getting impressions for · ${u} already tracked`:"GSC queries you're getting impressions for but aren't tracking yet";return e.jsxs("div",{className:"opportunity-card opportunity-card-track",children:[e.jsxs("div",{className:"opportunity-card-head",children:[e.jsx("p",{className:"opportunity-card-title",children:"Track new queries"}),e.jsx("span",{className:"opportunity-card-count",children:x>o.length?`${o.length} of ${x}`:o.length})]}),e.jsx("p",{className:"opportunity-card-subtitle",children:g}),e.jsx("div",{className:"opportunity-card-list",children:o.map(b=>{const d=i.has(b.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:b.query,children:b.query}),e.jsx("p",{className:"text-[11px] text-zinc-500 mt-0.5 leading-snug",children:b.reason})]}),e.jsx("button",{type:"button",className:"suggested-query-add",disabled:d,onClick:()=>l(b.query),children:d?"Adding…":"+ Track"})]},b.query)})})]})}function _c(t){const{projectId:s}=ei({from:"/projects/$projectId"}),i=Na()?.dashboard.projects.find(d=>d.project.id===s)?.project.name??null,a=Ue({...wa({client:H}),enabled:!i}),l=i??a.data?.find(d=>d.id===s)?.name??null,{commandCenter:o,isLoading:x,refetch:u}=za(l),g=!i&&a.isLoading||x;return!l&&!i&&a.isSuccess&&!x?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(z,{asChild:!0,children:e.jsx(yt,{to:"/",children:"Return to overview"})})]})}):!o||g?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(Lc,{model:o,refetch:u,...t})}function Lc({tab:t,model:s,refetch:n}){const i=ti(),a=xt(),[l,o]=c.useState(!1),[x,u]=c.useState(!1),[g,b]=c.useState(!1),[d,k]=c.useState(""),[A,T]=c.useState(!1),[h,S]=c.useState(!1),[L,M]=c.useState(""),[D,y]=c.useState(!1),[v,w]=c.useState(!1),[Q,X]=c.useState(""),[E,B]=c.useState(!1),[C,R]=c.useState(!1),[O,te]=c.useState(""),[xe,fe]=c.useState(!1),[J,F]=c.useState(void 0),[se,ce]=c.useState(!1),[le,p]=c.useState(null),[$,_]=c.useState(null),[he,pe]=c.useState(!1),ve=s?.visibilityEvidence??[],Z=s?.project.name??"",ae=s?.project.displayName||s?.project.name||Z,Ne=Sa(),ye=(s?.recentRuns??[]).some(m=>m.kind===bn["answer-visibility"]&&(m.status===Hs.running||m.status===Hs.queued)),Ae=c.useMemo(()=>(s?.project.locations??[]).map(m=>m.label),[s?.project.locations]),Se=c.useMemo(()=>new Set(ve.map(m=>m.location??"")),[ve]),De=Se.has(""),oe=c.useMemo(()=>{const m=[...Se].filter(Boolean);return m.length>1?m:Ae},[Se,Ae]);c.useEffect(()=>{if(J===void 0||J===""||!Z){_(null),pe(!1);return}pe(!0),ka(Z,J).then(m=>{_(m),pe(!1)}).catch(()=>{_(null),pe(!1)})},[J,Z]);const je=c.useMemo(()=>{if(!$)return null;const m=new Map;for(const V of $){for(const[K,Ee]of Object.entries(V.providerRuns??{}))m.set(`${V.query}::${K}`,Ee.map(de=>({runId:de.runId,citationState:de.citationState,createdAt:de.createdAt,answerMentioned:de.answerMentioned,visibilityState:de.visibilityState,visibilityTransition:de.visibilityTransition,mentionState:de.mentionState,mentionTransition:de.mentionTransition})));(!V.providerRuns||Object.keys(V.providerRuns).length===0)&&m.set(`${V.query}::`,V.runs.map(K=>({runId:K.runId,citationState:K.citationState,createdAt:K.createdAt,answerMentioned:K.answerMentioned,visibilityState:K.visibilityState,visibilityTransition:K.visibilityTransition,mentionState:K.mentionState,mentionTransition:K.mentionTransition})))}return m},[$]),Qe=c.useMemo(()=>{let m=J!==void 0?ve.filter(V=>J===""?!V.location:V.location===J):ve;if(le){const V=le.toLowerCase();m=m.filter(K=>K.competitorDomains.some(Ee=>Ee.toLowerCase()===V))}return je?m.map(V=>{const K=je.get(`${V.query}::${V.provider}`)??je.get(`${V.query}::`);return K?{...V,runHistory:K}:V}):m},[ve,J,le,je]);async function N(){try{await Ne.mutateAsync({projectName:Z,projectLabel:ae,sourceAction:"project-run"}),n()}catch{}}async function I(){u(!0);try{await Aa(Z),ee({title:"Project deleted",detail:`${ae} was removed.`,tone:"positive",dedupeKey:`project:delete:${Z}`,dedupeMode:"drop"}),i({to:"/"}),n()}catch(m){console.error("Failed to delete project:",m)}finally{u(!1)}}async function Me(){try{const m=await Ia(Z),V=typeof m=="string"?m:JSON.stringify(m,null,2),K=new Blob([V],{type:"text/yaml"}),Ee=URL.createObjectURL(K),de=document.createElement("a");de.href=Ee,de.download=`${Z}.yaml`,de.click()}catch(m){ee({title:"Export failed",detail:m instanceof Error?m.message:"Could not export project YAML.",tone:"negative"})}}async function Te(){const m=d.split(`
5
- `).map(V=>V.trim()).filter(Boolean);if(m.length!==0){T(!0);try{await La(Z,m),n(),k(""),b(!1)}finally{T(!1)}}}async function Le(){const m=L.trim();if(m){y(!0);try{const K=(await Da(Z)).map(de=>de.domain),Ee=[...new Set([...K,m])];await $a(Z,Ee),n(),M(""),S(!1)}finally{y(!1)}}}async function at(m){try{await Ra(Z,[m]),n()}catch(V){ee({title:"Could not remove competitor",detail:V instanceof Error?V.message:`Failed to remove ${m}`,tone:"negative",dedupeKey:"competitor:remove",dedupeMode:"replace"})}}async function rt(){const m=Q.trim();if(m){B(!0);try{const V=s?.project.ownedDomains??[];await Ws(Z,[...V,m]),n(),X(""),w(!1)}finally{B(!1)}}}async function Ye(m){B(!0);try{const V=s?.project.ownedDomains??[];await Ws(Z,V.filter(K=>K!==m)),n()}finally{B(!1)}}async function ct(){const m=O.trim();if(m){fe(!0);try{const V=s?.project.aliases??[],K=m.toLowerCase();if(V.some(Ee=>Ee.toLowerCase()===K)){te(""),R(!1);return}await Ys(Z,[...V,m]),n(),te(""),R(!1)}finally{fe(!1)}}}async function Oe(m){fe(!0);try{const V=s?.project.aliases??[];await Ys(Z,V.filter(K=>K!==m)),n()}finally{fe(!1)}}async function Xe(m,V){await Pa(m,V),await a.invalidateQueries({queryKey:Nn({client:H})})}const Je=m=>!Number.isNaN(Number.parseInt(m,10)),Ke=[{key:"overview",label:"Overview",href:`/projects/${s.project.id}`},{key:"search-console",label:"Search Engine Intelligence",href:`/projects/${s.project.id}/search-console`},{key:"activity",label:"Activity",href:`/projects/${s.project.id}/activity`},{key:"report",label:"Report",href:`/projects/${s.project.id}/report`},{key:"backlinks",label:"Backlinks",href:`/projects/${s.project.id}/backlinks`},{key:"discovery",label:"Discovery",href:`/projects/${s.project.id}/discovery`},{key:"settings",label:"Settings",href:`/projects/${s.project.id}/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(z,{type:"button",variant:"destructive",disabled:x,onClick:Y(I),children:x?"Deleting...":"Yes, delete project"}),e.jsx(z,{type:"button",variant:"outline",disabled:x,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&&!v&&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:()=>w(!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(m=>e.jsx("span",{className:"tag",children:m},m))]}),((s.project.ownedDomains??[]).length>0||v)&&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(m=>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:[m,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:E,onClick:()=>{Ye(m)},"aria-label":`Remove ${m}`,children:"×"})]},m)),v?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:Q,onChange:m=>X(m.target.value),onKeyDown:m=>{m.key==="Enter"&&rt()},autoFocus:!0}),e.jsx(z,{type:"button",size:"sm",disabled:!Q.trim()||E,onClick:Y(rt),children:E?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{w(!1),X("")},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:"+ 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(Pe,{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(m=>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:[m,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:xe,onClick:()=>{Oe(m)},"aria-label":`Remove ${m}`,children:"×"})]},m)),C?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:O,onChange:m=>te(m.target.value),onKeyDown:m=>{m.key==="Enter"&&ct()},autoFocus:!0}),e.jsx(z,{type:"button",size:"sm",disabled:!O.trim()||xe,onClick:Y(ct),children:xe?"...":"Add"}),e.jsx("button",{type:"button",className:"text-xs text-zinc-500 hover:text-zinc-300",onClick:()=>{R(!1),te("")},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:()=>R(!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(z,{type:"button",variant:"outline",size:"icon",onClick:Y(Me),"aria-label":"Export project as YAML",children:e.jsx(Ls,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(z,{type:"button",variant:"outline",size:"icon",onClick:()=>o(!0),"aria-label":"Delete project",children:e.jsx(Ya,{className:"h-4 w-4 text-zinc-400"})}),e.jsx(z,{type:"button",disabled:Ne.isPending||ye,onClick:Y(N),children:Ne.isPending?"Starting…":ye?"Sweep running…":"Run now"})]})]})]}),e.jsx("nav",{className:"project-subnav","aria-label":"Project sections",children:Ke.map(m=>e.jsx(yt,{to:m.href,className:`project-subnav-link ${m.key===t?"project-subnav-link-active":""}`,"aria-current":m.key===t?"page":void 0,children:m.label},m.key))}),t==="overview"?e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"aeo-hero",children:[e.jsx("h2",{className:"aeo-hero-title",children:"AEO performance"}),e.jsx("div",{className:"aeo-hero-rows",children:[{key:"mention",label:"Mentioned",tooltip:"Your domain or company name was in the answer returned by the LLM.",summary:s.mentionSummary},{key:"citation",label:"Cited",tooltip:"An LLM used a page on your domain as a source for its answer.",summary:s.visibilitySummary},{key:"mention-share",label:"Mention share",tooltip:"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.",summary:s.mentionShareSummary}].map(m=>e.jsxs("div",{className:"aeo-hero-row",children:[e.jsxs("div",{className:"aeo-hero-row-label",children:[e.jsx("span",{children:m.label}),e.jsx(Pe,{text:m.tooltip})]}),e.jsxs("div",{className:"aeo-hero-row-value",children:[e.jsx("span",{className:"text-zinc-50",children:m.summary.value}),Je(m.summary.value)?e.jsx("span",{className:"text-zinc-600",children:"%"}):null]}),e.jsx("div",{className:"aeo-hero-row-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${m.summary.tone}`,style:{width:m.summary.progress!==void 0?`${Math.min(Math.max(m.summary.progress,0),100)}%`:"0%"}})}),e.jsx("div",{className:"aeo-hero-row-detail",children:m.summary.delta})]},m.key))}),e.jsx(zc,{summary:s.mentionShareSummary,projectLabel:s.project.displayName||s.project.name}),s.providerScores.length>0&&e.jsxs("p",{className:"aeo-hero-context",children:["Across ",s.providerScores.length," ",s.providerScores.length===1?"provider":"providers","."]})]}),e.jsx(wc,{summary:s.movementSummary,onJumpToEvidence:()=>document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})}),e.jsxs("section",{className:"metric-grid",children:[e.jsx("h2",{className:"sr-only",children:"Coverage gaps and index health"}),e.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Mention Gaps",e.jsx(Pe,{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(Pe,{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.jsxs("div",{className:"metric-card",children:[e.jsxs("p",{className:"metric-card-eyebrow",children:["Index Coverage",e.jsx(Pe,{text:"Percentage of your tracked URLs that Google or Bing has indexed."})]}),e.jsxs("p",{className:"metric-card-big-value",children:[e.jsx("span",{className:"text-zinc-50",children:s.indexCoverage.value}),e.jsx("span",{className:"text-zinc-600",children:"%"})]}),e.jsx("div",{className:"metric-card-bar",children:e.jsx("div",{className:`metric-card-bar-fill progress-fill-${s.indexCoverage.tone}`,style:{width:`${Number.parseInt(s.indexCoverage.value,10)||0}%`}})}),e.jsx("p",{className:"metric-card-detail",children:s.indexCoverage.delta})]})]}),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:[new Set(s.visibilityEvidence.map(m=>m.query)).size," queries tracked"]}),e.jsx(z,{type:"button",variant:"outline",size:"sm",onClick:()=>b(!g),children:g?"Cancel":"+ Add queries"})]})]}),g&&e.jsxs("div",{className:"mb-3 rounded-lg border border-zinc-800 bg-zinc-900/40 p-3",children:[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, one per line",value:d,onChange:m=>k(m.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(m=>m.trim()).length," queries"]}),e.jsx(z,{type:"button",size:"sm",disabled:!d.trim()||A,onClick:Y(Te),children:A?"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 ${J===void 0?"filter-chip-active":""}`,type:"button","aria-pressed":J===void 0,onClick:()=>{F(void 0)},children:"All locations"}),s.project.locations.map(m=>e.jsx("button",{className:`filter-chip ${J===m.label?"filter-chip-active":""}`,type:"button","aria-pressed":J===m.label,onClick:()=>{F(m.label),ce(!1)},children:m.label},m.label)),De&&e.jsx("button",{className:`filter-chip ${J===""?"filter-chip-active":""}`,type:"button","aria-pressed":J==="",onClick:()=>{F(""),ce(!1)},children:"No location"}),oe.length>1&&J===void 0&&e.jsx("button",{className:`filter-chip filter-chip-compare ${se?"filter-chip-active":""}`,type:"button","aria-pressed":se,onClick:()=>ce(m=>!m),title:"Side-by-side location comparison",children:"Compare"})]}),le&&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:le})," surfaced"]}),e.jsx("button",{type:"button",className:"ml-auto text-xs text-zinc-400 hover:text-zinc-200",onClick:()=>p(null),children:"Clear filter ×"})]}),e.jsx(xr,{evidence:Qe,compareLocations:se})]}),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(Ac,{insights:s.insights,suggestedQueries:s.suggestedQueries,projectName:Z})]}),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:"Competitors"}),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(z,{type:"button",variant:"outline",size:"sm",onClick:()=>S(!h),children:h?"Cancel":"+ Add competitor"})]})]}),h&&e.jsxs("div",{className:"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:L,onChange:m=>M(m.target.value),onKeyDown:m=>{m.key==="Enter"&&Le()}}),e.jsx(z,{type:"button",size:"sm",disabled:!L.trim()||D,onClick:Y(Le),children:D?"Adding...":"Add"})]}),e.jsx(pr,{competitors:s.competitors,onSelectCompetitor:m=>{p(m),document.getElementById("evidence-section")?.scrollIntoView({behavior:"smooth",block:"start"})},onRemoveCompetitor:m=>{at(m)},activeFilter:le})]}),e.jsx(Br,{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(Pe,{text:"Per-model citation rate today plus a sparkline of the recent run history. Same query set, different LLMs — gaps between providers point at content / source issues, not the metric."})]})]})}),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:"Trend"}),e.jsx("th",{scope:"col",children:"Cited queries"})]})}),e.jsx("tbody",{children:s.providerScores.map(m=>e.jsxs("tr",{children:[e.jsx("td",{children:e.jsxs("div",{className:"flex flex-col items-start gap-0.5",children:[e.jsx(wt,{provider:m.provider}),m.model&&e.jsx("span",{className:"text-[11px] font-mono text-zinc-500",children:m.model})]})}),e.jsx("td",{children:e.jsxs("span",{className:`font-semibold ${Ca[wn(m.score)]}`,children:[m.score,"%"]})}),e.jsx("td",{children:e.jsx(kc,{trend:m.trend,currentScore:m.score})}),e.jsxs("td",{className:"text-zinc-500",children:[m.cited," of ",m.total]})]},`${m.provider}::${m.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(m=>e.jsx(Ua,{run:m},m.id))})]})]}):t==="settings"?e.jsxs(e.Fragment,{children:[e.jsx(gc,{project:{...s.project,displayName:s.project.displayName??s.project.name,defaultLocation:s.project.defaultLocation??null},onUpdateProject:Xe,onRefresh:()=>{n()}}),e.jsx(jc,{projectName:s.project.name}),e.jsx(yc,{projectName:s.project.name})]}):t==="report"?e.jsx(ec,{projectName:s.project.name}):t==="discovery"?e.jsx(Kr,{projectName:Z}):t==="activity"?e.jsx(yr,{projectName:s.project.name}):t==="backlinks"?e.jsx(Or,{projectName:s.project.name}):e.jsxs(e.Fragment,{children:[e.jsx(Nc,{projectName:s.project.name}),e.jsx(Rr,{projectName:s.project.name})]})]})}export{_c as ProjectPage};