PageSourceSearch

https://creators.lovable.app/assets/platform_.admin.analytics-DWkqU42U.js

js creators.lovable.app collected 2026-10-03 03:27:58 UTC 56,397 bytes, 1 lines download raw bytes

1import{j as e,C as L,d as Y,e as ne,g as E,f as Ee,r as p,h as dt,B as G,u as vs,c as _s,S as bs,L as ys}from"./index-Cbruulzy.js";import{B as je}from"./badge-DDrBl-nU.js";import{C as js,L as ws,a as Ns,X as ks,Y as Cs,T as Ss,b as Tt}from"./chart-BZSDf7bC.js";import{S as Ue,a as Pe,b as Ie,c as Oe,d as le}from"./select-MWxKtGSP.js";import{S as zt}from"./switch-BbOMZYbN.js";import{T as Ts,a as At}from"./toggle-group-D26JZmMi.js";import{A as Rt}from"./AppShell-Cm3arvdk.js";import{S as R}from"./Skeleton-k3_OO9w5.js";import{a as As,C as Rs}from"./ContentCard-Bq5QZLpn.js";import{i as Dt,d as Fe,e as Kt,f as qt,A as Ds,g as Ms,h as mt,u as Mt,r as $s,j as Ls,k as $t,l as Lt}from"./usePublicationReport-CvrdAvga.js";import{u as Es,s as et,L as Us}from"./LinksCodesDrawer-KbKh1u3t.js";import{c as tt}from"./admin-tints-BbrR6eNQ.js";import{a as Ps}from"./countries-B0tqwLww.js";import{P as Is,a as Os,b as Fs}from"./popover-DGNiKMx7.js";import{u as Ht}from"./deliverable-vocabulary-DQ73ajYV.js";import"./index-8xqJYClv.js";import"./index-CN8Upzs-.js";import"./SafeLink-AzJ1Uu2a.js";import"./platforms-DZG4UYBn.js";import"./eye-D9hCJqH4.js";import"./createLucideIcon-Dg2HsTgL.js";import"./input-NDk1Z9Qt.js";import"./table-HQzUaIL3.js";const pt=[{key:"positive",label:"Positive",color:tt.green},{key:"neutral",label:"Neutral",color:"bg-muted-hover"},{key:"mixed",label:"Mixed",color:tt.orange},{key:"negative",label:"Negative",color:tt.red}];function Vs(t){return pt.reduce((s,{key:n})=>s+t[`${n}_post_count`],0)}function Bs(t,s){return s>0&&Number.isFinite(t)?t/s:0}function Gs(t){return t?new Date(`${t.slice(0,10)}T00:00:00Z`).toLocaleDateString(void 0,{month:"short",day:"numeric",timeZone:"UTC"}):"—"}function De(t){return Math.round(t).toLocaleString()}function Ys(t){return`${(t*100).toFixed(1)}%`}function Ws(){return e.jsxs(L,{children:[e.jsxs(Y,{className:"space-y-2",children:[e.jsx(R,{className:"h-5 w-28"}),e.jsx(R,{className:"h-4 w-64"})]}),e.jsxs(E,{className:"space-y-5",children:[e.jsx(R,{className:"h-6 w-full"}),e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 sm:grid-cols-4",children:pt.map(({key:t})=>e.jsx(R,{className:"h-5 w-28"},t))}),e.jsx(R,{className:"h-16 w-full"})]})]})}function st({message:t}){return e.jsxs(L,{children:[e.jsxs(Y,{children:[e.jsx(ne,{children:"Sentiment"}),e.jsx(Ee,{children:"Comment sentiment from tracked Instagram and TikTok posts."})]}),e.jsx(E,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:t})})]})}function Zs({data:t,loading:s,error:n}){if(s)return e.jsx(Ws,{});if(n)return e.jsx(st,{message:"Couldn't load sentiment for this range. Reload to retry."});if(!t||t.scoped_post_count===0)return e.jsx(st,{message:"No eligible Instagram or TikTok posts in this range."});const r=Vs(t);if(r===0)return e.jsx(st,{message:"No eligible Instagram or TikTok posts have sentiment analysis in this range."});const l=pt.map(a=>({...a,count:t[`${a.key}_post_count`],share:Bs(t[`${a.key}_post_count`],r)}));return e.jsxs(L,{children:[e.jsxs(Y,{className:"flex flex-row flex-wrap items-start justify-between gap-3 space-y-0",children:[e.jsx("div",{children:e.jsx(ne,{children:"Sentiment"})}),e.jsxs(je,{variant:"outline",children:[De(r)," of ",De(t.scoped_post_count)," eligible posts analysed"]})]}),e.jsxs(E,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex h-6 w-full overflow-hidden rounded-md","aria-hidden":"true",children:l.map(a=>e.jsx("div",{className:`${a.color} h-full min-w-0 border-r border-card last:border-r-0`,style:{width:`${a.share*100}%`}},a.key))}),e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-2 text-xs sm:grid-cols-4",children:l.map(a=>e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 shrink-0 rounded-sm ${a.color}`,"aria-hidden":"true"}),e.jsxs("span",{className:"min-w-0 break-words",children:[a.label," ",e.jsxs("span",{className:"text-muted-foreground tabular-nums",children:[De(a.count)," · ",Ys(a.share)]})]})]},a.key))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Top themes"}),t.themes.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No themes recorded for analysed posts."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:t.themes.slice(0,6).map(a=>e.jsxs("span",{className:"max-w-full rounded-full border border-border px-2.5 py-1 text-xs break-words",children:[a.theme," ",e.jsxs("span",{className:"text-muted-foreground tabular-nums",children:["· ",De(a.post_count)," ",a.post_count===1?"post":"posts"]})]},a.theme))})]}),e.jsx("div",{className:"flex flex-wrap gap-x-6 gap-y-2 text-xs text-muted-foreground",children:e.jsxs("span",{children:[e.jsx("span",{className:"font-medium text-foreground",children:"Latest analysis"})," ",Gs(t.analysis_date_max)]})}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer select-none",children:"About these numbers"}),e.jsx("p",{className:"mt-2",children:"Only tracked Instagram and TikTok posts are included. Percentages use posts with a sentiment result; missing results are shown separately. Each theme is counted once per post."})]})]})]})}const zs="https://jxgrmfdufarwmiaiugqu.supabase.co/functions/v1/admin-crm";async function Ks(t,s,n,r){const{data:{session:l}}=await dt.auth.getSession();if(!l)throw new Error("sentiment_summary_missing_session");const a=await fetch(zs,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l.access_token}`,apikey:"sb_publishable_pa3Q_IQij0VmW-foLMM-wA_vhXc_6av"},body:JSON.stringify({action:"sentiment_summary",from:t,to:s,include_legacy:n,...r?{campaign_tag:r}:{}})});if(!a.ok)throw new Error(`sentiment_summary_${a.status}`);const o=await a.json().catch(()=>null);if(!o||o.source!=="warehouse"||!o.summary)throw new Error("sentiment_summary_unavailable");return o.summary}function qs({from:t,to:s,includeLegacy:n,campaignTag:r=null,enabled:l=!0}){const[a,o]=p.useState(null),[c,i]=p.useState(!0),[u,h]=p.useState(!1),x=Dt(t)&&Dt(s)&&t<=s;return p.useEffect(()=>{if(!l||!x){if(!l)return;o(null),i(!1),h(!1);return}let f=!1;return i(!0),h(!1),o(null),(async()=>{try{const b=await Ks(t,s,n,r);if(f)return;o(b),i(!1)}catch{if(f)return;o(null),h(!0),i(!1)}})(),()=>{f=!0}},[t,s,n,r,l,x]),{data:a,loading:c,error:u}}function re(t){return typeof t=="number"&&Number.isInteger(t)&&Number.isFinite(t)&&t>=0?t:null}function Hs(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:null}function Qs(t){if(!t||typeof t!="object")return null;const s=t;if(s.source!=="warehouse")return null;const n=re(s.eligible_account_count),r=re(s.accounts_with_data_count);if(n===null||r===null||r>n||!Array.isArray(s.accounts)||s.accounts.length!==n)return null;const l=[];
1for(const a of s.accounts){if(!a||typeof a!="object")return null;const o=a,c=re(o.account_ordinal);if(typeof o.social_account_sk!="string"||!o.social_account_sk||o.network!=="instagram"&&o.network!=="tiktok"||typeof o.account_label!="string"||!o.account_label||o.account_label.length>200||c===null||!Array.isArray(o.sources))return null;const i=[];for(const u of o.sources){if(!u||typeof u!="object")return null;const h=u;if(!ct.includes(h.geo_source)||typeof h.base_kind!="string"||typeof h.observed_at!="string"||!h.observed_at||h.base_count!==null&&re(h.base_count)===null||!Array.isArray(h.countries))return null;const x=[];for(const f of h.countries){if(!f||typeof f!="object")return null;const b=f,_=b.audience_count===null?null:re(b.audience_count),C=b.audience_share===null?null:Hs(b.audience_share);if(!/^[A-Z]{2}$/.test(String(b.country_code))||b.audience_count!==null&&_===null||b.audience_share!==null&&(C===null||C>1))return null;x.push({country_code:b.country_code,audience_count:_,audience_share:C})}i.push({geo_source:h.geo_source,base_kind:h.base_kind,base_count:h.base_count===null?null:re(h.base_count),observed_at:h.observed_at,countries:x})}l.push({social_account_sk:o.social_account_sk,network:o.network,account_label:o.account_label,account_ordinal:c,sources:i})}return{source:"warehouse",eligible_account_count:n,accounts_with_data_count:r,accounts:l}}const ct=["follower_demographics","engaged_audience_demographics","marketplace_top_countries","tiktok_audience_countries"];function Et(t,s){const r=(s==="tiktok"?["tiktok_audience_countries","marketplace_top_countries","engaged_audience_demographics","follower_demographics"]:ct).indexOf(t);return r===-1?ct.length:r}function Js(t){return[...t.sources].sort((s,n)=>Et(s.geo_source,t.network)-Et(n.geo_source,t.network))[0]??null}function Xs(t){const s=t.map(o=>o.sources.find(c=>c.geo_source==="follower_demographics"&&c.countries.some(i=>i.audience_count!=null))).filter(o=>!!o);if(s.length===0)return null;const n=new Map;let r=0,l=0;for(const o of s){o.base_count!=null&&(r+=o.base_count);for(const c of o.countries)c.audience_count!=null&&(n.set(c.country_code,(n.get(c.country_code)??0)+c.audience_count),l+=c.audience_count)}const a=[...n.entries()].sort((o,c)=>c[1]-o[1]||o[0].localeCompare(c[0])).map(([o,c])=>({country_code:o,audience_count:c,audience_share:l>0?c/l:null}));return{accountCount:s.length,coveredFollowerBase:r,knownCountryFollowers:l,countryRows:a}}function Qt(t){if(t.length===0||!t.every(n=>n.audience_count!=null))return t;const s=t.reduce((n,r)=>
1n+(r.audience_count??0),0);return s<=0?t:t.map(n=>({...n,audience_share:(n.audience_count??0)/s}))}function Ut(t,s=5){const n=Qt(t.countries),r=n.length>0&&n.every(i=>i.audience_count!=null)&&n.some(i=>(i.audience_count??0)>0),l=n.filter(i=>i.audience_count!=null).sort((i,u)=>(u.audience_count??0)-(i.audience_count??0)||i.country_code.localeCompare(u.country_code));if(r){const i=l.slice(0,s),u=l.slice(s).reduce((x,f)=>x+(f.audience_count??0),0),h=l.reduce((x,f)=>x+(f.audience_count??0),0);return[...i.map(x=>({...x,audience_share:h>0?(x.audience_count??0)/h:x.audience_share})),...u>0?[{country_code:"OTHER",audience_count:u,audience_share:h>0?u/h:null}]:[]]}const o=n.filter(i=>i.audience_share!=null).sort((i,u)=>(u.audience_share??0)-(i.audience_share??0)||i.country_code.localeCompare(u.country_code)).slice(0,s),c=Math.round(Math.max(0,1-o.reduce((i,u)=>i+(u.audience_share??0),0))*1e6)/1e6;return[...o,...c>.001?[{country_code:"OTHER",audience_count:null,audience_share:c}]:[]]}function en(t,s){return{accountsWithSource:t.filter(n=>n.sources.some(r=>r.geo_source===s)).length,eligibleAccounts:t.length}}function tn(t,s,n){const r=t==="instagram"&&n.some(a=>a.sources.some(o=>o.geo_source==="follower_demographics"&&o.countries.some(c=>c.audience_count!=null))),l=r?"overview":n.find(a=>a.sources.length>0)?.social_account_sk??"overview";return s==="overview"?r?"overview":l:n.some(a=>a.social_account_sk===s)?s:l}function Ve(t){return t==="follower_demographics"?"Follower demographics":t==="engaged_audience_demographics"?"Engaged audience":t==="tiktok_audience_countries"?"TikTok audience countries":"Marketplace top countries"}const sn=new Map(Ps.map(t=>[t.code,t.name]));function be(t){return Math.round(t).toLocaleString()}function Be(t){return t==null?"—":`${(t*100).toFixed(1)}%`}function Jt(t){return t==="OTHER"?"Other / not reported":sn.get(t)??`Reported country (${t})`}function nt(t){const s=new Date(t);return Number.isNaN(s.getTime())?"date unavailable":s.toLocaleDateString(void 0,{dateStyle:"medium"})}function Pt(t){const s=t.map(l=>new Date(l)).filter(l=>!Number.isNaN(l.getTime())).sort((l,a)=>l.getTime()-a.getTime());if(s.length===0)return null;const n=s[0].toISOString(),r=s[s.length-1].toISOString();return n===r?`Observed ${nt(n)}`:`Observed ${nt(n)}–${nt(r)}`}function nn(){return e.jsxs(L,{children:[e.jsx(Y,{className:"space-y-2",children:e.jsx(R,{className:"h-5 w-48"})}),e.jsxs(E,{className:"space-y-3",children:[e.jsx(R,{className:"h-9 w-full"}),e.jsx(R,{className:"h-8 w-full"}),e.jsx(R,{className:"h-5 w-full"}),e.jsx(R,{className:"h-5 w-5/6"}),e.jsx(R,{className:"h-5 w-2/3"})]})]})}function an({rows:t}){const s=Math.max(...t.map(n=>n.audience_count??n.audience_share??0),0);return t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No country breakdown was reported for this snapshot."}):e.jsx("div",{className:"space-y-3",children:t.map(n=>{const r=n.audience_count??n.audience_share??0,l=s>0?r/s*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[e.jsx("span",{className:"min-w-0 truncate",children:Jt(n.country_code)}),e.jsx("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:n.audience_count==null?Be(n.audience_share):`${be(n.audience_count)} · ${Be(n.audience_share)}`})]}),e.jsx("div",{className:"h-2 overflow-hidden rounded-full bg-muted","aria-hidden":"true",children:e.jsx("div",{className:"h-full rounded-full bg-primary",style:{width:`${Math.min(100,l)}%`}})})]},n.country_code)})})}function rn(t){return[...t.sources].sort((s,n)=>Ve(s.geo_source).localeCompare(Ve(n.geo_source)))}function on({network:t,scopeKey:s=null,onNetworkChange:n,data:r,loading:l,refreshing:a,error:o,onRefresh:c}){const[i,u]=p.useState("overview"),[h,x]=p.useState(null);p.useEffect(()=>{u("overview"),x(null)},[t,s]);const f=p.useMemo(()=>r?.accounts.filter(v=>v.sources.some(q=>q.geo_source==="follower_demographics"&&q.countries.some(we=>we.audience_count!=null)))??[],[r]),b=r?.accounts??[],_=tn(t,i,b),C=b.find(v=>v.social_account_sk===_)??null,y=_==="overview"?null:C,N=y?y.sources.find(v=>v.geo_source===h)??Js(y):null,m=t==="instagram"&&_==="overview"?Xs(r?.accounts??[]):null,W=f.flatMap(v=>v.sources.filter(q=>q.geo_source==="follower_demographics")),ae=m?Ut({observed_at:W[0]?.observed_at??"",countries:m.countryRows}):N?Ut(N):[],g=Qt(m?.countryRows??N?.countries??[]),w=m?Pt(W.map(v=>v.observed_at)):N?Pt([N.observed_at]):null,M=m?`${m.accountCount} of ${r?.eligible_account_count??0} eligible accounts with follower data`:y&&N?(()=>{const v=en(r?.accounts??[],N.geo_source);return`${v.accountsWithSource} of ${v.eligibleAccounts} eligible accounts with ${Ve(N.geo_source).toLowerCase()}`})():`${r?.accounts_with_data_count??0} of ${r?.eligible_account_count??0} eligible accounts with data`;if(l&&!r)return e.jsx(nn,{});const T=!!(y&&!N),K=t==="tiktok"&&!y&&!N,V=t==="instagram"&&!y&&!m&&!N;return e.jsxs(L,{children:[e.jsxs(Y,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsx(ne,{children:"Audience geography"}),e.jsx(G,{variant:"outline",size:"sm",loading:a,onClick:c,children:"Refresh"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-md border border-border p-0.5",role:"group","aria-label":"Audience network",children:["instagram","tiktok"].map(v=>e.jsx(G,{type:"button",size:"sm",variant:t===v?"secondary":"ghost",onClick:()=>{n(v),u("overview"),x(null)},children:v==="instagram"?"Instagram":"TikTok"},v))}),e.jsxs(Ue,{value:_,onValueChange:v=>{u(v),x(null)},children:[e.jsx(Pe,{className:"min-w-56 flex-1 sm:flex-none",children:e.jsx(Ie,{})}),e.jsxs(Oe,{children:[t==="instagram"&&f.length>0&&e.jsx(le,{value:"overview",children:"Programme overview"}),(r?.accounts??[]).map(v=>e.jsxs(le,{value:v.social_account_sk,children:[v.account_label,v.sources.length===0?" · no data":""]},v.social_account_sk))]})]}),y&&e.jsxs(Ue,{value:N?.geo_source??"",onValueChange:v=>x(v),children:[e.jsx(Pe,{className:"min-w-52 flex-1 sm:flex-none",children:e.jsx(Ie,{placeholder:"Source basis"})}),e.jsx(Oe,{children:rn(y).map(v=>e.jsx(le,{value:v.geo_source,children:Ve(v.geo_source)},v.geo_source))})]})]})]}),e.jsxs(E,{className:"space-y-5",children:[o&&r&&e.jsx("p",{className:"text-xs text-destructive",children:"The latest refresh failed. Showing the last successful snapshot."}),o&&!r?e.jsx("p",{className:"text-sm text-destructive",children:"Couldn’t load audience geography. Use Refresh to try again."}):T?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No country data has been reported for this account yet."}):K?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No TikTok country data has been reported yet. Connected accounts appear automatically after the data refresh."}):V?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No Instagram country data has been reported yet. Connected accounts appear automatically after the data refresh."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-muted-foreground",children:[e.jsx(je,{variant:"outline",children:M}),w&&e.jsx("span",{children:w})]}),e.jsx(an,{rows:ae}),N&&N.base_count!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Snapshot base: ",be(N.base_count)," ",N.base_kind==="followers"?"followers":N.base_kind.replaceAll("_"," ")," (counted once for this account)."]}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer select-none",children:"See all reported countries"}),e.jsx("div",{className:"mt-2 space-y-1",children:g.map(v=>e.jsxs("div",{className:"flex justify-between gap-3",children:[e.jsx("span",{children:Jt(v.country_code)}),e.jsx("span",{className:"tabular-nums",children:v.audience_count==null?Be(v.audience_share):`${be(v.audience_count)} · ${Be(v.audience_share)}`})]},v.country_code))})]}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer select-none",children:"About these numbers"}),e.jsxs("div",{className:"mt-2 space-y-2",children:[e.jsx("p",{children:"Audience counts and shares come from the latest reported snapshot for each account. Snapshots are not limited by the selected date range or post dates. “Other / not reported” includes countries outside the displayed list or the undisclosed share in a share-only source."}),m&&e.jsxs("p",{children:["The programme overview uses follower demographics only. Countries show covered followers with known country data; uncovered followers are not estimated. ",m.coveredFollowerBase>m.knownCountryFollowers?`${be(m.knownCountryFollowers)} of ${be(m.coveredFollowerBase)} covered followers have a reported country.`:"All covered followers have a reported country."]})]})]})]})]})]})}const ln="https://jxgrmfdufarwmiaiugqu.supabase.co/functions/v1/admin-crm";async function cn(t,s,n,r){const{data:{session:l}}=await dt.auth.getSession();if(!l)throw new Error("audience_geography_missing_session");const a=await fetch(ln,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l.access_token}`,apikey:"sb_publishable_pa3Q_IQij0VmW-foLMM-wA_vhXc_6av"},body:JSON.stringify({action:"audience_geography",network:t,include_legacy:s,...n?{campaign_tag:n}:{}}),signal:r});if(!a.ok)throw new Error(`audience_geography_${a.status}`);const o=Qs(await a.json().catch(()=>null));if(!o)throw new Error("audience_geography_unavailable");return o}function un({network:t,includeLegacy:s,campaignTag:n=null,enabled:r=!0}){const[l,a]=p.useState(null),[o,c]=p.useState(r),[i,u]=p.useState(!1),[h,x]=p.useState(!1),f=p.useRef(0),b=p.useRef(null),_=p.useCallback(async C=>{b.current?.abort();const y=new AbortController;b.current=y;const N=++f.current;C?c(!0):u(!0),x(!1);try{const m=await cn(t,s,n,y.signal);if(N!==f.current)return;a(m),c(!1)}catch(m){if(y.signal.aborted||N!==f.current)return;console.error("useAudienceGeography failed:",m),x(!0),c(!1)}finally{N===f.current&&u(!1)}},[n,s,t]);return p.useEffect(()=>{if(b.current?.abort(),f.current+=1,!r){a(null),c(!1),u(!1),x(!1);return}a(null),_(!0);const C=()=>{document.visibilityState==="visible"&&_(!1)},y=window.setInterval(C,6e4);return window.addEventListener("focus",C),document.addEventListener("visibilitychange",C),()=>{b.current?.abort(),f.current+=1,window.clearInterval(y),window.removeEventListener("focus",C),document.removeEventListener("visibilitychange",C)}},[r,_]),{data:l,loading:o,refreshing:i,error:h,refresh:()=>{_(!1)}}}const dn=["M","T","W","T","F","S","S"];function Xt(t){return t.toISOString().slice(0,10)}function it(t){if(!t)return"—";const s=new Date(`${t}T00:00:00Z`);return Number.isNaN(s.getTime())?t:s.toLocaleDateString("en-GB",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"})}function It(t,s){if(!t||!s)return"—";const n=new Date(`${t}T00:00:00Z`),r=new Date(`${s}T00:00:00Z`);
1if(Number.isNaN(n.getTime())||Number.isNaN(r.getTime()))return`${t} – ${s}`;const l=a=>a.toLocaleDateString("en-GB",{month:"short",day:"numeric",timeZone:"UTC"});return n.getUTCFullYear()===r.getUTCFullYear()?`${l(n)} – ${l(r)}, ${r.getUTCFullYear()}`:`${l(n)}, ${n.getUTCFullYear()} – ${l(r)}, ${r.getUTCFullYear()}`}function Le(t){return{year:t.getUTCFullYear(),month:t.getUTCMonth()}}function at(t,s){const n=new Date(Date.UTC(t.year,t.month+s,1));return Le(n)}function mn(t,s){const r=(new Date(Date.UTC(t,s,1)).getUTCDay()+6)%7,l=new Date(Date.UTC(t,s+1,0)).getUTCDate(),a=Array.from({length:r},()=>null);for(let o=1;o<=l;o++)a.push(Xt(new Date(Date.UTC(t,s,o))));for(;a.length%7!==0;)a.push(null);return a}const pn="h-9 w-36 rounded-md border border-input bg-transparent px-2 text-sm focus-visible:border-ring focus-visible:outline-none";function Me({label:t,value:s,onChange:n,max:r}){return e.jsxs("label",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),e.jsx("input",{type:"date",className:pn,value:s,max:r,onChange:l=>n(l.target.value)})]})}function Ot({month:t,range:s,compare:n,today:r,onPick:l}){const a=p.useMemo(()=>mn(t.year,t.month),[t.year,t.month]),o=new Date(Date.UTC(t.year,t.month,1)).toLocaleDateString("en-GB",{month:"long",year:"numeric",timeZone:"UTC"});return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:o}),e.jsxs("div",{className:"grid grid-cols-7 gap-y-1 text-center",children:[dn.map((c,i)=>e.jsx("span",{className:"text-xs text-muted-foreground",children:c},`${c}-${i}`)),a.map((c,i)=>{if(!c)return e.jsx("span",{},`pad-${i}`);const u=c>=s.from&&c<=s.to&&!!s.from&&!!s.to,h=c===s.from||c===s.to,x=!!n&&c>=n.from&&c<=n.to&&!u,f=c>r,b="h-8 w-8 mx-auto rounded-full text-sm tabular-nums transition-colors",_=h?"bg-primary text-primary-foreground font-medium":u?"bg-primary/15 text-foreground":x?"bg-brand-saffron text-brand-saffron-foreground":f?"text-muted-foreground/50":"hover:bg-muted";return e.jsx("button",{type:"button",className:`${b} ${_}`,"aria-label":it(c),onClick:()=>l(c),children:Number(c.slice(8,10))},c)})]})]})}function hn({value:t,onApply:s,now:n=new Date}){const[r,l]=p.useState(!1),[a,o]=p.useState(t),c=p.useRef("start"),[i,u]=p.useState(()=>Le(new Date(`${t.range.to}T00:00:00Z`))),h=Xt(new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate())));p.useEffect(()=>{r&&(o(t),c.current="start",u(Le(new Date(`${t.range.to||h}T00:00:00Z`))))},[r,t,h]);const x=p.useMemo(()=>a.compare.on?a.compare.mode==="custom"?{from:a.compare.from,to:a.compare.to}:Fe(a.compare.mode,a.range.from,a.range.to):null,[a]),f=Kt(a.range,x),b=!f.range&&!f.compare,_=a.compare.on&&a.compare.mode==="custom",C=(g,w)=>o(M=>({...M,range:{preset:"custom",from:g,to:w}})),y=g=>{const w=mt(g,n);o(M=>({...M,range:{preset:g,from:w.from,to:w.to}})),u(Le(new Date(`${w.to}T00:00:00Z`))),c.current="start"},N=g=>{const w=_?"compare":"range",M=w==="compare"?{from:a.compare.from,to:a.compare.to}:a.range;if(c.current==="start"){c.current="end",w==="compare"?o(V=>({...V,compare:{...V.compare,from:g,to:g}})):C(g,g);return}c.current="start";const T=g<M.from?g:M.from,K=g<M.from?M.from:g;w==="compare"?o(V=>({...V,compare:{...V.compare,from:T,to:K}})):C(T,K)},m=t,W=m.compare.on?m.compare.mode==="custom"?{from:m.compare.from,to:m.compare.to}:Fe(m.compare.mode,m.range.from,m.range.to):null,ae=m.range.preset==="custom"?"Custom":qt(m.range.preset);return e.jsxs(Is,{open:r,onOpenChange:l,children:[e.jsx(Os,{asChild:!0,children:e.jsxs(G,{variant:"outline",className:"h-auto flex-col items-start gap-0.5 py-2",children:[e.jsxs("span",{className:"text-sm",children:[ae," · ",It(m.range.from,m.range.to)]}),W&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["vs ",It(W.from,W.to)]})]})}),e.jsxs(Fs,{align:"end",className:"w-[46rem] max-w-[95vw] p-0",children:[e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsxs("div",{className:"w-full md:w-64 shrink-0 border-b md:border-b-0 md:border-r border-border p-2 max-h-[28rem] overflow-y-auto",children:[e.jsx("button",{type:"button",onClick:()=>o(g=>({...g,range:{...g.range,preset:"custom"}})),className:`w-full rounded-md px-3 py-2 text-left text-sm ${a.range.preset==="custom"?"bg-accent text-accent-foreground font-medium":"hover:bg-muted"}`,children:"Custom"}),e.jsx("div",{className:"my-2 border-t border-border"}),Ds.map(g=>e.jsx("button",{type:"button",onClick:()=>y(g.value),className:`w-full rounded-md px-3 py-2 text-left text-sm ${a.range.preset===g.value?"bg-accent text-accent-foreground font-medium":"hover:bg-muted"}`,children:g.label},g.value)),e.jsx("div",{className:"my-2 border-t border-border"}),e.jsxs("div",{className:"flex items-center justify-between px-3 py-2",children:[e.jsx("label",{htmlFor:"analytics-compare-switch",className:"text-sm",children:"Compare"}),e.jsx(zt,{id:"analytics-compare-switch",checked:a.compare.on,onCheckedChange:g=>o(w=>({...w,compare:{...w.compare,on:g}}))})]}),a.compare.on&&Ms.map(g=>e.jsx("button",{type:"button",onClick:()=>{o(w=>({...w,compare:{...w.compare,mode:g.value}})),c.current="start"},className:`w-full rounded-md px-3 py-2 text-left text-sm ${a.compare.mode===g.value?"bg-accent text-accent-foreground font-medium":"hover:bg-muted"}`,children:g.label},g.value))]}),e.jsxs("div",{className:"flex-1 p-4 space-y-4 max-h-[28rem] overflow-y-auto",children:[e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsx(Me,{label:"Start date",value:a.range.from,max:h,onChange:g=>C(g,a.range.to)}),e.jsx("span",{className:"pb-2 text-muted-foreground",children:"—"}),e.jsx(Me,{label:"End date",value:a.range.to,max:h,onChange:g=>C(a.range.from,g)})]}),f.range&&e.jsx("p",{className:"text-xs text-destructive-primary",children:f.range}),a.compare.on&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Compare"}),a.compare.mode==="custom"?e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsx(Me,{label:"Start date",value:a.compare.from,max:h,onChange:g=>o(w=>({...w,compare:{...w.compare,from:g}}))}),e.jsx("span",{className:"pb-2 text-muted-foreground",children:"—"}),e.jsx(Me,{label:"End date",value:a.compare.to,max:h,onChange:g=>o(w=>({...w,compare:{...w.compare,to:g}}))})]}):e.jsx("p",{className:"text-sm text-muted-foreground tabular-nums",children:x?`${it(x.from)} — ${it(x.to)}`:"—"}),f.compare&&e.jsx("p",{className:"text-xs text-destructive-primary",children:f.compare})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>u(g=>at(g,-1)),"aria-label":"Previous month",children:"←"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_?"Clicking dates sets the comparison range":"Clicking dates sets the selected range"}),e.jsx(G,{variant:"ghost",size:"sm",onClick:()=>u(g=>at(g,1)),"aria-label":"Next month",children:"→"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-6",children:[e.jsx(Ot,{month:at(i,-1),range:a.range,compare:x,today:h,onPick:N}),e.jsx(Ot,{month:i,range:a.range,compare:x,today:h,onPick:N})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 border-t border-border p-3",children:[e.jsx(G,{variant:"ghost",onClick:()=>l(!1),children:"Cancel"}),e.jsx(G,{disabled:!b,onClick:()=>{s(a),l(!1)},children:"Apply"})]})]})]})}function fn(t,s,n){return s?"loading":t&&!n?"unavailable":"ready"}function gn(t){let s=2166136261;for(let n=0;n<t.length;n++)s^=t.charCodeAt(n),s=Math.imul(s,16777619);return s>>>0}function xn(t){let s=t;return()=>{s|=0,s=s+1831565813|0;let n=Math.imul(s^s>>>15,1|s);return n=n+Math.imul(n^n>>>7,61|n)^n,((n^n>>>14)>>>0)/4294967296}}function z(t,s){return xn(gn(`${t}:${s}`))()}const vn=Date.UTC(2020,0,1);function _n(t){return Math.round((new Date(`${t}T00:00:00Z`).getTime()-vn)/864e5)}function bn(t,s){const n=[],r=new Date(`${t}T00:00:00Z`).getTime(),l=new Date(`${s}T00:00:00Z`).getTime();for(let a=r;a<=l;a+=864e5)n.push(new Date(a).toISOString().slice(0,10));return n}const yn={async fetchDailyMetrics({from:t,to:s}){return{rows:bn(t,s).map(r=>{const l=_n(r),a=new Date(`${r}T00:00:00Z`).getUTCDay(),o=a===0||a===6?.72:1,c=1+Math.min(.4,l/3e3),i=8e3*o*c,u=Math.round(i*(.85+.3*z(r,"views"))),h=Math.round(u*(.03+.02*z(r,"likes"))),x=Math.round(u*(.004+.003*z(r,"comments"))),f=Math.round(u*(.006+.004*z(r,"saves"))),b=Math.round(u*(.002+.002*z(r,"
1shares"))),_=Math.round(u*(.008+.004*z(r,"spend"))*100)/100,C=1+Math.round(4*z(r,"posts")),y=1+Math.round(3*z(r,"creators"));return{date:r,views:u,likes:h,comments:x,saves:f,shares:b,spend_usd:_,measurable_spend_usd:_,posts:C,creators:y}}),source:"placeholder",cohort:null}}};function ut(t){return t.reduce((s,n)=>({views:s.views+n.views,likes:s.likes+n.likes,comments:s.comments+n.comments,saves:s.saves+n.saves,shares:s.shares+n.shares,spend_usd:s.spend_usd+n.spend_usd,measurable_spend_usd:s.measurable_spend_usd+n.measurable_spend_usd,posts:s.posts+n.posts,creators:Math.max(s.creators,n.creators)}),{views:0,likes:0,comments:0,saves:0,shares:0,spend_usd:0,measurable_spend_usd:0,posts:0,creators:0})}function es(t){return t.likes+t.comments+t.saves+t.shares}function jn(t){return t.views>0?es(t)/t.views:0}function ye(t){return t.views>0?t.measurable_spend_usd/t.views*1e3:0}function ts(t){return t.views>0?t.measurable_spend_usd/t.views:0}function Ft(t,s){switch(t){case"views":return s.views;case"engagements":return es(s);case"likes":return s.likes;case"comments":return s.comments;case"saves":return s.saves;case"shares":return s.shares;case"engagement_rate":return jn(s);case"cpm":return ye(s);case"cpv":return ts(s)}}function Vt(t){const s=new Map;for(const n of t){const r=new Date(`${n.date}T00:00:00Z`),l=(r.getUTCDay()+6)%7,o=new Date(r.getTime()-l*864e5).toISOString().slice(0,10),c=s.get(o)??[];c.push(n),s.set(o,c)}return[...s.entries()].sort(([n],[r])=>n<r?-1:1).map(([n,r])=>({date:n,...ut(r)}))}function wn(t,s){return s===0?t===0?0:null:(t-s)/s}const Nn="https://jxgrmfdufarwmiaiugqu.supabase.co/functions/v1/admin-crm";function Bt(t){if(!t||typeof t!="object")return null;const s=t,{posts:n,creators:r,views:l,likes:a,comments:o,tracked_spend_usd:c}=s;return typeof n!="number"||typeof r!="number"||typeof l!="number"||typeof a!="number"||typeof o!="number"?null:{posts:n,creators:r,views:l,likes:a,comments:o,tracked_spend_usd:typeof c=="number"?c:0}}function kn(t){if(!t||typeof t!="object")return null;const s=t,n=Bt(s.current);if(!n)return null;const r=s.previous==null?null:Bt(s.previous);return{current:n,previous:r}}async function Cn(t){const{data:{session:s}}=await dt.auth.getSession();return s?fetch(Nn,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s.access_token}`,apikey:"sb_publishable_pa3Q_IQij0VmW-foLMM-wA_vhXc_6av"},body:JSON.stringify(t)}):null}function rt(t=null,s=null,n=null,r=null,l=null,a=null,o=null){return{rows:[],source:"unavailable",link_hits_total:t,link_redemptions_total:s,committed_spend_total_usd:n,committed_spend_live_usd:r,committed_in_range_usd:l,paid_out_in_range_usd:a,cohort:o}}const Gt={async fetchDailyMetrics({from:t,to:s,currentFrom:n,includeLegacy:r,campaignTag:l}){try{const a=await Cn({action:"analytics_series",from:t,to:s,granularity:"day",...n?{current_from:n}:{},include_legacy:r??!1,...l?{campaign_tag:l}:{}});if(!a||!a.ok)return rt();const o=await a.json().catch(()=>null),c=typeof o?.link_hits_total=="number"?o.link_hits_total:null,i=typeof o?.link_redemptions_total=="number"?o.link_redemptions_total:null,u=typeof o?.committed_spend_total_usd=="number"?o.committed_spend_total_usd:null,h=typeof o?.committed_spend_live_usd=="number"?o.committed_spend_live_usd:null,x=typeof o?.committed_in_range_usd=="number"?o.committed_in_range_usd:null,f=typeof o?.paid_out_in_range_usd=="number"?o.paid_out_in_range_usd:null,b=kn(o?.cohort);if(!o||o.source==="unavailable"||!Array.isArray(o.rows))return rt(c,i,u,h,x,f,b);const _=o.rows.map(y=>({date:y.period_start,views:y.views,likes:y.likes,comments:y.comments,saves:0,shares:0,spend_usd:y.spend_usd,measurable_spend_usd:typeof y.measurable_spend_usd=="number"?y.measurable_spend_usd:y.spend_usd,posts:y.posts,creators:y.creators})),C=o.source==="analytics_daily"?"analytics_daily":"mirrors_interim";return{rows:_,source:C,link_hits_total:c,link_redemptions_total:i,committed_spend_total_usd:u,committed_spend_live_usd:h,committed_in_range_usd:x,paid_out_in_range_usd:f,cohort:b}}catch(a){return console.error("BigQueryAnalyticsProvider.fetchDailyMetrics failed:",a),rt()}}},Yt=500;function Sn(t){if(!t)return{redemptions:null,signups:null,conversionsToPaid:null,conversionRate:null,blendedSacUsd:null,totalRevenueUsd:null,totalNetMarginUsd:null,redemptionsUnavailable:!0,paidMetricsUnavailable:!0,sacUnavailable:!0,revenueUnavailable:!0,netMarginUnavailable:!0,summaryUnavailable:!1};const s=t.summary,n=s!==void 0,r=s?.source==="marts",l=n?!r||s.redemptions===null:t.source==="unavailable"||t.codes.length>=Yt,a=n?!r||s.signups===null||s.subscribers===null:t.source==="unavailable"||t.links.length>=Yt,o=l?null:n?s.redemptions:t.codes.reduce((b,_)=>b+_.redeemers,0),c=a?null:n?s.signups:t.links.reduce((b,_)=>b+_.signups,0),i=a?null:n?s.subscribers:t.links.reduce((b,_)=>b+_.subscribers,0),u=n&&r?s.creator_spend_usd:null,h=n&&s?.revenue_source==="warehouse"?s.revenue_usd:null,x=u!==null&&i!==null&&i>0?u/i:null,f=h!==null&&u!==null?h-u:null;return{redemptions:o,signups:c,conversionsToPaid:i,conversionRate:a||c===null||c===0?null:i/c,blendedSacUsd:x,totalRevenueUsd:h,totalNetMarginUsd:f,redemptionsUnavailable:l,paidMetricsUnavailable:a,sacUnavailable:x===null,revenueUnavailable:h===null,netMarginUnavailable:f===null,summaryUnavailable:n&&!r}}
1function j(t){return Math.round(t).toLocaleString()}function Ge(t){return`${(t*100).toFixed(1)}%`}function $(t){return t.toLocaleString(void 0,{style:"currency",currency:"USD",maximumFractionDigits:2})}const $e=[{value:"views",label:"Views",format:j},{value:"engagements",label:"Engagements",format:j},{value:"likes",label:"Likes",format:j},{value:"comments",label:"Comments",format:j},{value:"saves",label:"Saves",format:j},{value:"shares",label:"Shares",format:j},{value:"engagement_rate",label:"Engagement rate",format:Ge},{value:"cpm",label:"CPM",format:$},{value:"cpv",label:"CPV",format:$}],ot="__all_campaigns__",Tn={value:{label:"Value",theme:{light:"hsl(251 60% 51%)",dark:"hsl(251 60% 66%)"}},compare:{label:"Comparison",theme:{light:"hsl(251 12% 55%)",dark:"hsl(251 12% 62%)"}}};function An({delta:t,goodDirection:s="up"}){if(t==null)return null;const n=Math.abs(t)<.001,r=n?null:s==="up"?t>0:t<0,l=n?"bg-muted text-muted-foreground":r?"bg-success text-success-foreground":"bg-destructive text-destructive-foreground",a=t>0?"+":"";return e.jsxs("span",{className:`rounded-full px-1.5 py-0.5 text-xs font-medium tabular-nums whitespace-nowrap ${l}`,children:[a,(t*100).toFixed(1),"%"]})}function F({value:t,delta:s,goodDirection:n="up"}){return e.jsxs("span",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["vs ",t]}),e.jsx(An,{delta:s,goodDirection:n})]})}const Rn="grid grid-cols-3 gap-y-4 gap-x-2",Dn="grid grid-cols-2 gap-y-4 gap-x-2";function se({label:t,value:s,loading:n,compare:r,footer:l}){return e.jsxs("div",{className:"flex flex-col gap-1 px-4",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),n?e.jsx(R,{className:"h-8 w-20"}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-2xl font-semibold tabular-nums",children:s}),r,l]})]})}function lt({label:t,value:s,secondary:n,muted:r,compare:l,loading:a}){return e.jsx(L,{className:"h-full border-accent bg-accent/40",children:e.jsxs(E,{className:"pt-6 flex flex-col gap-1.5 h-full",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:t}),a?e.jsxs(e.Fragment,{children:[e.jsx(R,{className:"h-10 w-32"}),e.jsx(R,{className:"h-3 w-36"})]}):e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-4xl font-semibold tabular-nums",children:s}),n&&e.jsx("p",{className:"text-sm tabular-nums",children:n}),r&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r}),l]})]})})}function oe({label:t,value:s,loading:n,compare:r}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:t}),n?e.jsx(R,{className:"h-5 w-14"}):e.jsx("span",{className:"text-sm font-medium tabular-nums",children:s}),!n&&r]})}const Wt=6,Zt="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4";function Mn(t){return[...t].sort((s,n)=>s.metric_views==null&&n.metric_views==null?0:s.metric_views==null?1:n.metric_views==null?-1:n.metric_views-s.metric_views)}function $n({rows:t,loading:s,error:n}){const{campaignTagLabel:r,loading:l}=Ht(),a=p.useMemo(()=>t?Mn(t).slice(0,Wt):[],[t]),c=s||l?e.jsx("div",{className:Zt,children:Array.from({length:Wt},(i,u)=>e.jsx(As,{},u))}):n?e.jsx("p",{className:"text-destructive text-sm py-8 text-center",children:"Couldn't load top content. Reload to retry."}):a.length===0?e.jsx("p",{className:"text-muted-foreground text-sm py-8 text-center",children:"No published content in this period."}):e.jsx("div",{className:Zt,children:a.map((i,u)=>e.jsx(Rs,{rank:u+1,platform:i.platform??"other",liveUrl:i.live_url,publishDate:i.publication_date,dateSource:i.date_source,campaignTag:i.campaign_tag?r(i.campaign_tag):null,creatorName:i.creator_name,creatorHandle:i.creator_handle,metrics:{views:i.metric_views,likes:i.metric_likes,comments:i.metric_comments},isLegacy:i.source_system==="railblocks"},i.id))});return e.jsxs(L,{children:[e.jsx(Y,{children:e.jsx(ne,{children:"Top content"})}),e.jsxs(E,{className:"space-y-4",children:[c,e.jsx("div",{className:"text-right",children:e.jsx(G,{asChild:!0,variant:"outline",children:e.jsx(ys,{to:"/platform/admin/content",children:"View all content →"})})})]})]})}function Ln({data:t,loading:s,onShowLinks:n}){const r=t?.links??[],l=t?.source==="unavailable",a=Sn(t),o=!t||l?void 0:s?"All links":`All ${r.length} link${r.length===1?"":"s"}`;return e.jsxs(L,{children:[e.jsxs(Y,{className:"flex flex-row flex-wrap items-start justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Links"}),e.jsx(Ee,{children:"Lovlink tracking links"})]}),o&&e.jsxs(G,{variant:"text",onClick:n,children:[o," →"]})]}),e.jsx(E,{className:"space-y-3",children:s?e.jsx(R,{className:"h-24 w-full"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-3 lg:grid-cols-6",children:[e.jsx(oe,{label:"Link signups",value:a.signups===null?"—":j(a.signups),loading:!1}),e.jsx(oe,{label:"Conversions to paid",value:a.conversionsToPaid===null?"—":j(a.conversionsToPaid),loading:!1}),e.jsx(oe,{label:"Conversion rate",value:a.conversionRate===null?"—":Ge(
1a.conversionRate),loading:!1}),e.jsx(oe,{label:"Blended SAC",value:a.blendedSacUsd===null?"—":$(a.blendedSacUsd),loading:!1}),e.jsx(oe,{label:"Total revenue",value:a.totalRevenueUsd===null?"—":$(a.totalRevenueUsd),loading:!1}),e.jsx(oe,{label:"Total net margin",value:a.totalNetMarginUsd===null?"—":$(a.totalNetMarginUsd),loading:!1})]}),(a.paidMetricsUnavailable||a.revenueUnavailable||a.netMarginUnavailable)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a.summaryUnavailable?"Summary metrics unavailable right now.":!t||l?"Link data isn't available right now.":a.revenueUnavailable?"Revenue unavailable right now.":"Some link metrics are unavailable for this period; detail rows are capped."}),e.jsxs("details",{className:"text-xs text-muted-foreground",children:[e.jsx("summary",{className:"cursor-pointer select-none",children:"How these are calculated"}),e.jsxs("ul",{className:"mt-2 space-y-1 pl-4 list-disc",children:[e.jsx("li",{children:"Link signups = accounts attributed to Lovlink tracking links in the selected period."}),e.jsx("li",{children:"Paid conversions = subscribers from the selected first-touch click cohort."}),e.jsx("li",{children:"Conversion rate = paid conversions ÷ link signups; payments may happen later."}),e.jsx("li",{children:"Blended SAC = creator committed spend in the selected period ÷ paid conversions; blank at zero."}),e.jsx("li",{children:"Net revenue = collected cash excluding tax, after refunds and disputes, from click day through the latest available data."}),e.jsx("li",{children:"Net margin = revenue − creator committed spend; other costs are excluded."})]})]})]})})]})}const ss="cp-admin-analytics-range",ns="cp-admin-analytics-compare",En=["today","yesterday","this_week","7d","last_week","28d","30d","90d","mtd","ytd"],Un=["previous_dow","previous","previous_year","previous_year_dow","custom"];function Pn(t){const s=mt(Lt,t),n=Fe($t,s.from,s.to);return{range:{preset:Lt,from:s.from,to:s.to},compare:{on:!1,mode:$t,from:n.from,to:n.to}}}function In(t){const s=Pn(t);if(typeof window>"u")return s;const n={...s};try{const r=window.localStorage.getItem(ss);if(r){const a=JSON.parse(r);if(a.preset==="custom"&&typeof a.from=="string"&&typeof a.to=="string")n.range={preset:"custom",from:a.from,to:a.to};else if(typeof a.preset=="string"&&En.includes(a.preset)){const o=mt(a.preset,t);n.range={preset:a.preset,from:o.from,to:o.to}}}const l=window.localStorage.getItem(ns);if(l){const a=JSON.parse(l),o=Un.includes(a.mode)?a.mode:s.compare.mode;n.compare={on:a.on===!0,mode:o,from:typeof a.from=="string"?a.from:s.compare.from,to:typeof a.to=="string"?a.to:s.compare.to}}}catch{}return n}function On(t){if(!(typeof window>"u"))try{window.localStorage.setItem(ss,JSON.stringify(t.range)),window.localStorage.setItem(ns,JSON.stringify(t.compare))}catch{}}function ia(){const{user:t,loading:s}=vs(),{canView:n,loading:r}=_s(),[l,a]=p.useState(null),[o]=p.useState(()=>new Date),[c,i]=p.useState(()=>In(new Date));p.useEffect(()=>{On(c)},[c]);const u=c.compare.on,[h,x]=p.useState("views"),[f,b]=p.useState("weekly"),[_,C]=p.useState(!1),{campaignTags:y,loading:N}=Ht(),[m,W]=p.useState(null),[ae,g]=p.useState("instagram"),[w,M]=p.useState(null),[T,K]=p.useState(!0),[V,v]=p.useState(null),[q,we]=p.useState(null),[ce,ht]=p.useState(null),[Ne,ft]=p.useState(null),[as,gt]=p.useState(null),[ie,xt]=p.useState(null),A=p.useMemo(()=>({from:c.range.from,to:c.range.to}),[c.range]),Z=A.from,{data:vt,loading:rs}=Es({from:Z,to:A.to,includeLegacy:_,enabled:n&&m===null}),U=Mt({from:A.from,to:A.to,includeLegacy:_,campaignTag:m,enabled:n}),{data:os,loading:ls,error:cs}=qs({from:A.from,to:A.to,includeLegacy:_,campaignTag:m,enabled:n}),ue=un({network:ae,includeLegacy:_,campaignTag:m,enabled:n&&!s&&!!t});p.useEffect(()=>{m&&a(null)},[m]);const H=p.useMemo(()=>{if(!u)return null;const d=c.compare.mode==="custom"?{from:c.compare.from,to:c.compare.to}:Fe(c.compare.mode,A.from,A.to);if(!d)return null;const k=Kt(A,d,400);return k.range||k.compare?null:$s(d.from,d.to)<=400?d:null},[u,c.compare,A]),ke=Mt({from:H?.from,to:H?.to,includeLegacy:_,campaignTag:m,enabled:n&&H!==null}),de=U.report?.source==="warehouse"&&U.report.complete?U.report:null,is=ke.report?.source==="warehouse"&&ke.report.complete?ke.report:null,S=de?.summary??null,Q=is?.summary??null,us=de?.rows??null,ds=U.error||U.forbidden||!!U.report&&!U.report.complete;p.useEffect(()=>{if(!n)return;let d=!1;return K(!0),v(null),M(null),we(null),ht(null),ft(null),gt(null),(async()=>{const k=await Gt.fetchDailyMetrics({from:Z,to:A.to,currentFrom:Z,includeLegacy:_,campaignTag:m});if(!d){if(we(k.committed_spend_total_usd??null),ht(k.committed_in_range_usd??null),ft(k.paid_out_in_range_usd??null),gt(k.cohort??null),k.source==="unavailable"){if(m)M(k.rows);else{const te=await yn.fetchDailyMetrics({from:Z,to:A.to});if(d)return;M(te.rows)}v("unavailable")}else M(k.rows),v(k.source);K(!1)}})(),()=>{d=!0}},[n,A.to,Z,_,m]);const Ce=H?.from??null,Ye=H?.to??null;p.useEffect(()=>{if(xt(null),!n||!Ce||!Ye)return;let d=!1;return(async()=>{const k=await Gt.fetchDailyMetrics({from:Ce,to:Ye,currentFrom:Ce,includeLegacy:_,campaignTag:m});if(d)return;const te=k.cohort?.current??null;k.source==="unavailable"&&!(m&&te)||xt({rows:k.rows,cohort:te,committedInRange:k.committed_in_range_usd??null,paidOutInRange:k.paid_out_in_range_usd??null})})(),()=>{d=!0}},[n,Ce,Ye,_,m]);const me=p.useMemo(()=>(w??[]).filter(d=>d.date>=Z&&d.date<=A.to),[w,Z,A.to]),J=ie?.rows??null,X=p.useMemo(()=>ut(me),[me]),B=p.useMemo(()=>J?ut(J):null,[J]),pe=as?.current??null,We=u?ie?.cohort??null:null,Se=fn(m,T,pe)==="unavailable",_t=pe?pe.tracked_spend_usd:X.measurable_spend_usd,bt=u?pe?We?We.tracked_spend_usd:null:B?B.measurable_spend_usd:null:null,yt=ce??X.spend_usd,jt=yt>0?_t/yt:null,Ze={views:pe?.views??X.views,measurable_spend_usd:_t},wt=We?.views??B?.views??null,ze=wt===null||bt===null?null:{views:wt,measurable_spend_usd:bt},Nt=p.useMemo(()=>f==="weekly"?Vt(me):me,[me,f]),Te=p.useMemo(()=>J?f==="weekly"?Vt(J):J:null,[J,f]),D=T?null:V,Ke=h!=="saves"&&h!=="shares"||D==="placeholder",he=Ke?h:"views",ms=D==="placeholder"?$e:$e.filter(d=>d.value!=="saves"&&d.value!=="shares");p.useEffect(()=>{D&&D!=="placeholder"&&!Ke&&x("views")},[Ke,D]);const Ae=$e.find(d=>d.value===he)??$e[0],qe=p.useMemo(()=>Nt.map((d,k)=>{const te=Te?.[k];return{date:d.date,value:Ft(he,d),compare:te?Ft(he,te):void 0}}),[Nt,Te,he]);if(s||r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(bs,{})});if(!t||!n)return e.jsx(Rt,{children:e.jsx("main",{className:"p-6 max-w-2xl mx-auto",children:e.jsx(L,{children:e.jsxs(Y,{children:[e.jsx(ne,{children:t?"No access":"Sign in required"}),t&&e.jsx(Ee,{children:"You don't have access to this page."})]})})})});const P=(d,k)=>k==null?null:wn(d,k),ps=c.range.preset==="custom"?`Custom: ${A.from} → ${A.to}`:qt(c.range.preset),kt=m?y.find(d=>d.value===m)?.label??m:null,fe=u&&!T&&ie!==null,ge=u&&H!==null&&!U.loading&&!ke.loading&&S!==null&&Q!==null,hs=u&&H==null,Ct=de?.rows.filter(d=>d.metrics_source==="warehouse"&&d.metrics_as_of!==null&&[d.metric_views,d.metric_likes,d.metric_comments].some(k=>k!==null)).length??null,xe=U.loading,ee=S?.metrics.views.total??null,I=S?.metrics.likes.total??null,O=S?.metrics.comments.total??null,He=Q?.metrics.views.total??null,ve=Q?.metrics.likes.total??null,_e=Q?.metrics.comments.total??null,Re=I===null||O===null?null:I+O,Qe=ve===null||_e===null?null:ve+_e,St=de?Ls(de.rows,{views:ee,likes:I,comments:O}):null,fs=S&&ee!==null&&ee>0&&I!==null&&O!==null?"Rate unavailable: metrics cover different posts.":"Coverage unavailable.",gs=D==="analytics_daily"?ce===null?"n/a":$(ce):"n/a",xs=D===null||D==="unavailable"||Ne===null?"n/a":$(Ne),Je=u?ie?.committedInRange??null:null,Xe=u?ie?.paidOutInRange??null:null;return e.jsx(Rt,{children:e.jsxs("main",{className:"p-6 max-w-7xl mx-auto 
1space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold",children:"Analytics"}),kt&&e.jsxs("p",{className:"text-muted-foreground",children:["Performance for ",kt,"."]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[!m&&D==="placeholder"&&e.jsx(je,{variant:"brand-saffron",children:"Sample data — analytics not connected yet"}),!m&&D==="mirrors_interim"&&e.jsx(je,{variant:"brand-saffron",children:"Interim data — full analytics unavailable right now"}),!m&&D==="unavailable"&&e.jsx(je,{variant:"destructive",children:"Analytics unavailable — the data request failed"}),e.jsx(hn,{value:c,onApply:i,now:o}),e.jsxs(Ue,{value:m??ot,onValueChange:d=>W(d===ot?null:d),disabled:N,children:[e.jsx(Pe,{className:"w-48",children:e.jsx(Ie,{placeholder:"All campaigns"})}),e.jsxs(Oe,{children:[e.jsx(le,{value:ot,children:"All campaigns"}),y.map(d=>e.jsx(le,{value:d.value,children:d.label},d.value))]})]}),hs&&e.jsx("p",{className:"text-xs text-muted-foreground text-right",children:"Comparison unavailable for this range"})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-semibold mb-3",children:"Key metrics"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Automatic metrics cover tracked Instagram and TikTok posts."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 items-stretch",children:[e.jsx(lt,{label:"Views / impressions",loading:T||xe,value:ee===null?"—":j(ee),secondary:S?`${j(S.metrics.views.measured_count)} of ${j(S.total_published)} with measured views`:void 0,compare:ee!==null&&He!==null&&ge?e.jsx(F,{value:j(He),delta:P(ee,He)}):null}),e.jsx(lt,{label:"CPM / cost per view",loading:T,value:Se?"—":`${$(ye(Ze))} CPM`,secondary:Se?void 0:`${$(ts(Ze))} per view`,muted:Se?"Campaign metrics unavailable.":jt==null?"coverage n/a":`based on ${Ge(jt)} of spend`,compare:!Se&&fe&&ze?e.jsx(F,{value:`${$(ye(ze))} CPM`,delta:P(ye(Ze),ye(ze)),goodDirection:"down"}):null}),e.jsx(lt,{label:"Engagement",loading:T||xe,value:Re===null?"—":j(Re),secondary:I===null||O===null?void 0:`Likes ${j(I)} · Comments ${j(O)}`,muted:St===null?fs:`${Ge(St)} of views`,compare:Re!==null&&Qe!==null&&ge?e.jsx(F,{value:j(Qe),delta:P(Re,Qe)}):null})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(L,{children:[e.jsxs(Y,{className:"flex flex-row flex-wrap items-center justify-between gap-3 space-y-0",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Trend"}),e.jsx(Ee,{children:m?"Daily trend unavailable for campaign filters.":`${ps} · daily growth`})]}),!m&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ue,{value:he,onValueChange:d=>x(d),children:[e.jsx(Pe,{className:"w-40",children:e.jsx(Ie,{})}),e.jsx(Oe,{children:ms.map(d=>e.jsx(le,{value:d.value,children:d.label},d.value))})]}),e.jsxs(Ts,{type:"single",value:f,onValueChange:d=>d&&b(d),children:[e.jsx(At,{value:"weekly",children:"Weekly"}),e.jsx(At,{value:"daily",children:"Daily"})]})]})]}),e.jsx(E,{children:m?e.jsx("p",{className:"text-muted-foreground text-sm py-12 text-center",children:"Not available when filtering by campaign."}):T?e.jsx(R,{className:"h-72 w-full"}):qe.length===0?e.jsx("p",{className:"text-muted-foreground text-sm py-12 text-center",children:"No data in this period."}):e.jsxs(e.Fragment,{children:[Te&&e.jsxs("div",{className:"flex items-center gap-4 mb-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-0.5 w-5",style:{background:"var(--color-value)"},"aria-hidden":"true"}),"Selected range"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-0.5 w-5",style:{backgroundImage:"repeating-linear-gradient(90deg, var(--color-compare) 0, var(--color-compare) 3px, transparent 3px, transparent 6px)"},"aria-hidden":"true"}),"Comparison"]})]}),e.jsx(js,{config:Tn,className:"aspect-auto h-72",children:e.jsxs(ws,{data:qe,margin:{top:8,right:8,bottom:8,left:0},children:[e.jsx(Ns,{vertical:!1,stroke:"hsl(var(--border))"}),e.jsx(ks,{dataKey:"date",tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"},tickFormatter:d=>et(String(d)),minTickGap:24}),e.jsx(Cs,{tick:{fontSize:11,fill:"hsl(var(--muted-foreground))"},tickFormatter:d=>Ae.format(d),width:64}),e.jsx(Ss,{contentStyle:{background:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"var(--radius)",fontSize:"0.75rem",color:"hsl(var(--popover-foreground))"},formatter:(d,k)=>[Ae.format(d),k==="compare"?`${Ae.label} (comparison)`:Ae.label],labelFormatter:d=>f==="weekly"?`Week of ${et(String(d))}`:et(String(d))}),e.jsx(Tt,{type:"monotone",dataKey:"value",stroke:"var(--color-value)",strokeWidth:2,dot:qe.length<=14,connectNulls:!0}),Te&&e.jsx(Tt,{type:"monotone",dataKey:"compare",stroke:"var(--color-compare)",strokeWidth:2,strokeDasharray:"4 4",dot:!1,connectNulls:!0})]})})]})})]})}),e.jsxs("div",{className:"flex flex-col gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2",children:"Breakdown"}),e.jsx(L,{children:e.jsx(E,{children:e.jsxs("div",{className:Rn,children:[e.jsx(se,{label:"Published content",value:S?j(S.total_published):"—",loading:T||xe,compare:S&&Q&&ge?e.jsx(F,{value:j(Q.total_published),delta:P(S.total_published,Q.total_published)}
1):null,footer:S?e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[j(S.tracked)," tracked · ",Ct===null?"—":j(Ct)," with metrics"]}):e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Publication coverage unavailable."})}),e.jsx(se,{label:"Likes",value:I===null?"—":j(I),loading:T||xe,compare:I!==null&&ve!==null&&ge?e.jsx(F,{value:j(ve),delta:P(I,ve)}):null,footer:S?e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[j(S.metrics.likes.measured_count)," of ",j(S.total_published)," measured"]}):void 0}),e.jsx(se,{label:"Comments",value:O===null?"—":j(O),loading:T||xe,compare:O!==null&&_e!==null&&ge?e.jsx(F,{value:j(_e),delta:P(O,_e)}):null,footer:S?e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[j(S.metrics.comments.measured_count)," of ",j(S.total_published)," measured"]}):void 0}),e.jsx(se,{label:"Saves / favorites",value:D==="placeholder"?j(X.saves):"—",loading:T,compare:D==="placeholder"&&B&&fe?e.jsx(F,{value:j(B.saves),delta:P(X.saves,B.saves)}):null}),e.jsx(se,{label:"Shares",value:D==="placeholder"?j(X.shares):"—",loading:T,compare:D==="placeholder"&&B&&fe?e.jsx(F,{value:j(B.shares),delta:P(X.shares,B.shares)}):null})]})})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground mb-2",children:"Spend"}),e.jsx(L,{children:e.jsx(E,{children:m?e.jsx("p",{className:"text-muted-foreground text-sm py-8 text-center",children:"Spend is unavailable for campaign filters."}):e.jsxs("div",{className:Dn,children:[e.jsx(se,{label:"Committed spend",value:gs,loading:T,compare:fe&&Je!==null?e.jsx(F,{value:$(Je),delta:ce===null?null:P(ce,Je)}):null,footer:e.jsxs("span",{className:"block text-xs text-muted-foreground",children:["All time: ",q===null?"—":$(q)]})}),e.jsx(se,{label:"Paid out",value:xs,loading:T,compare:fe&&Xe!==null?e.jsx(F,{value:$(Xe),delta:Ne===null?null:P(Ne,Xe)}):null})]})})})]})]})]}),m?e.jsx(L,{children:e.jsxs(E,{className:"pt-6",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Programme metrics"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-3",children:"Links and payouts are unavailable for campaign filters."})]})}):e.jsx(Ln,{data:vt,loading:rs,onShowLinks:()=>a("links")}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 xl:grid-cols-2",children:[e.jsx(Zs,{data:os,loading:ls,error:cs}),e.jsx(on,{network:ae,scopeKey:m,onNetworkChange:g,data:ue.data,loading:ue.loading,refreshing:ue.refreshing,error:ue.error,onRefresh:ue.refresh})]}),e.jsx($n,{rows:us,loading:U.loading,error:ds})]}),!m&&e.jsx(e.Fragment,{children:e.jsx(Us,{open:l==="links",onOpenChange:d=>
1a(d?"links":null),rows:vt?.links??[],from:Z,to:A.to})}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 border-t border-border pt-4 text-xs text-muted-foreground",children:[!m&&e.jsxs("span",{children:[D==="analytics_daily"?"Refreshed daily around 11:15 UTC. ":"","Paid out covers the app programme only."]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{htmlFor:"include-legacy-toggle",children:"Include legacy (RailBlocks)"}),e.jsx(zt,{id:"include-legacy-toggle",checked:_,onCheckedChange:C})]})]})]})})}export{ia as component};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.