1import{j as e}from"./query-DsCa_Pyl.js";import{r as d,u as Q}from"./react-vendor-BCqHlMf_.js";import{s as E,a4 as A,d as p,a7 as Z,a8 as ee,a9 as se,B as L,ab as _,g,U as te,V as O,e as D,h as R,v as ae,f as I,P as re,p as le,c as oe,r as ie}from"./index-DTOh3Yy2.js";import{C as ne}from"./calendar-HlI-CIFJ.js";import{S as ce,a as de,b as me,c as xe,d as he}from"./select-B3rz7HZT.js";import{U as fe}from"./user-plus-D8pDd7vr.js";import{H as P}from"./heart-BTJtOWdp.js";import{f as C}from"./format-BQsj1U_8.js";import{E as H}from"./eye-m3IWzlod.js";import{M as $}from"./message-circle-DqLSYI6L.js";import{S as B}from"./share-2-CO_GceLn.js";import{T as ue}from"./trending-up-B_bEwCNK.js";import{C as W}from"./ChartDownloadButton-OMBoKQYU.js";import{R as q,h as je,C as z,X as G,Y as F,T as X,L as Y,e as pe,g as V,f as ge}from"./recharts-g6Jqsn6E.js";import{T as Ne,a as ye,b as U,c as v,d as ke,e as T}from"./table-Cn7t2wwj.js";import{P as we}from"./percent-ClBWzQ16.js";import{E as be}from"./external-link-CYVeZVId.js";import{A as ve}from"./arrow-up-down-Dz_V4VRr.js";import{M as Te}from"./music-2-DWEvjj3Q.js";import{s as Ce}from"./subDays-DKewYeiZ.js";import"./supabase-Bj-H2d61.js";import"./framer-yhwvsixF.js";import"./tiptap-B6mHXrL0.js";import"./startOfMonth-INsbJR6W.js";import"./isAfter-5-6TXG8s.js";import"./chevron-left-Kw6hBpoU.js";import"./download-Czzde3bo.js";function Se(){const[l,a]=d.useState(null),[t,r]=d.useState(!1),[i,x]=d.useState(!1),[S,y]=d.useState(!1),[u,s]=d.use
1State(null),[h,m]=d.useState(!1),j=d.useCallback(async(k,n,c)=>{r(!0),s(null),m(!1);try{const{data:N,error:w}=await E.functions.invoke("get-tiktok-analytics",{body:{accountId:k,startDate:n,endDate:c}});if(w)throw w;if(N.error){if(N.code==="TOKEN_INVALID")m(!0),s("Unable to load TikTok analytics right now.");else throw new Error(N.error);return null}return a(N),N}catch(N){const w=N.message||"Failed to fetch analytics";return s(w),console.error("Failed to fetch TikTok analytics:",N),null}finally{r(!1)}},[]),f=d.useCallback(async k=>{x(!0);try{const{data:n,error:c}=await E.functions.invoke("get-tiktok-analytics",{body:{accountId:k}});if(c)throw c;if(n.error){if(n.code==="TOKEN_INVALID")m(!0),A.error("Unable to load TikTok analytics right now.");else throw new Error(n.error);return null}return a(n),A.success("Profile stats refreshed"),n}catch(n){const c=n.message||"Failed to refresh stats";return A.error(c),console.error("Failed to refresh TikTok stats:",n),null}finally{x(!1)}},[]),M=d.useCallback(async k=>{y(!0),s(null);try{const{data:n,error:c}=await E.functions.invoke("import-tiktok-posts",{body:{socialAccountId:k}});if(c)throw c;if(n.error){if(n.code==="TOKEN_INVALID")m(!0),A.error("Unable to load TikTok analytics right now.");else throw new Error(n.error);return null}return A.success(`Imported ${n.imported} videos`),n}catch(n){const c=n.message||"Failed to import videos";return A.error(c),console.error("Failed to import TikTok videos:",n),null}finally{y(!1)}},[]);return{analytics:l,isLoading:t,isRefreshing:i,isImporting:S,error:u,tokenExpired:h,fetchAnalytics:j,refreshProfileStats:f,importVideos:M}}function Ae({account:l,isRefreshing:a,onRefresh:t}){var i;const r=x=>x>=1e6?(x/1e6).toFixed(1)+"M":x>=1e3?(x/1e3).toFixed(1)+"K":x.toLocaleString();return e.jsxs(p,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-[#00f2ea] via-[#ff0050] to-[#00f2ea] px-6 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(Z,{className:"h-16 w-16 border-2 border-white",children:[e.jsx(ee,{src:l.avatarUrl,alt:l.name}),e.jsx(se,{className:"bg-white text-black text-xl font-bold",children:((i=l.name)==null?void 0:i.charAt(0))||"T"})]}),e.jsxs("div",{className:"text-white",children:[e.jsx("h2",{className:"text-xl font-bold drop-shadow-md",children:l.name}),e.jsx("p",{className:"text-sm text-white/90 drop-shadow-sm",children:l.handle||"TikTok Account"}),e.jsxs("p",{className:"text-xs text-white/80 drop-shadow-sm",children:["Connected ",C(new Date(l.connectedAt),"MMM d, yyyy")]})]})]}),e.jsxs(L,{variant:"secondary",size:"sm",onClick:t,disabled:a,className:"bg-white/20 text-white hover:bg-white/30 backdrop-blur-sm",children:[e.jsx(_,{className:`mr-2 h-4 w-4 ${a?"animate-spin":""}`}),"Refresh"]})]})}),e.jsxs(g,{className:"p-6",children:[e.jsxs("div",{className:"grid gap-6 sm:grid-cols-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-pink-500/10 p-3",children:e.jsx(te,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Followers"}),e.jsx("p",{className:"text-2xl font-bold",children:r(l.followers)})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-cyan-500/10 p-3",children:e.jsx(fe,{className:"h-5 w-5 text-cyan-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Following"}),e.jsx("p",{className:"text-2xl font-bold",children:r(l.following)})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-red-500/10 p-3",children:e.jsx(P,{className:"h-5 w-5 text-red-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Likes"}),e.jsx("p",{className:"text-2xl font-bold",children:r(l.totalLikes)})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-purple-500/10 p-3",children:e.jsx(O,{className:"h-5 w-5 text-purple-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Videos"}),e.jsx("p",{className:"text-2xl font-bold",children:r(l.videoCount)})]})]})]}),l.lastFetched&&e.jsxs("p",{className:"mt-4 text-xs text-muted-foreground",children:["Last updated: ",C(new Date(l.lastFetched),"MMM d, yyyy h:mm a")]})]})]})}function Ie({analytics:l}){const{summary:a}=l,t=i=>i>=1e6?(i/1e6).toFixed(1)+"M":i>
1=1e3?(i/1e3).toFixed(1)+"K":i.toLocaleString(),r=[{title:"Videos in Period",value:t(a.videosInPeriod),icon:O,color:"text-purple-500",bgColor:"bg-purple-500/10"},{title:"Total Views",value:t(a.totalViews),icon:H,color:"text-blue-500",bgColor:"bg-blue-500/10"},{title:"Total Likes",value:t(a.totalLikes),icon:P,color:"text-red-500",bgColor:"bg-red-500/10"},{title:"Total Comments",value:t(a.totalComments),icon:$,color:"text-green-500",bgColor:"bg-green-500/10"},{title:"Total Shares",value:t(a.totalShares),icon:B,color:"text-cyan-500",bgColor:"bg-cyan-500/10"},{title:"Avg. Engagements per Video",value:a.avgEngagement,icon:ue,color:"text-pink-500",bgColor:"bg-pink-500/10"}];return e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-6",children:r.map(i=>e.jsx(p,{children:e.jsxs(g,{className:"flex flex-col items-center text-center p-4",children:[e.jsx("div",{className:`rounded-full p-2.5 mb-2 ${i.bgColor}`,children:e.jsx(i.icon,{className:`h-5 w-5 ${i.color}`})}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-nowrap",children:i.title}),e.jsx("p",{className:"text-xl font-bold",children:i.value})]})},i.title))})}function De({data:l}){const a=d.useRef(null),t=l.map(r=>({date:C(new Date(r.date),"MMM d"),videos:r.videos,views:r.views}));return t.length===0?e.jsxs(p,{children:[e.jsx(D,{children:e.jsx(R,{className:"text-lg",children:"Daily Activity"})}),e.jsx(g,{className:"flex h-[300px] items-center justify-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No Data Available"})})]}):e.jsxs(p,{className:"relative",children:[e.jsx(W,{targetRef:a,filename:"tik-tok-daily-activity-chart"}),e.jsx(D,{children:e.jsx(R,{className:"text-lg",children:"Daily Activity"})}),e.jsx(g,{ref:a,children:e.jsx("div",{className:"h-[300px]",children:e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(je,{data:t,margin:{top:5,right:30,left:20,bottom:5},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorViews",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#00f2ea",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#00f2ea",stopOpacity:0})]})}),e.jsx(z,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(G,{dataKey:"date",className:"text-xs"}),e.jsx(F,{yAxisId:"views",className:"text-xs"}),e.jsx(F,{yAxisId:"videos",orientation:"right",className:"text-xs",allowDecimals:!1,width:32}),e.jsx(X,{contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:r=>r.toLocaleString()}),e.jsx(Y,{}),e.jsx(pe,{yAxisId:"views",type:"monotone",dataKey:"views",name:"Views",stroke:"#00f2ea",fillOpacity:1,fill:"url(#colorViews)"}),e.jsx(V,{yAxisId:"videos",type:"monotone",dataKey:"videos",name:"Videos posted",stroke:"#ff0050",strokeWidth:2,dot:{r:3}})]})})})})]})}function Re({data:l}){const a=d.useRef(null),t=l.map(r=>({date:C(new Date(r.date),"MMM d"),likes:r.likes,comments:r.comments,shares:r.shares}));return t.length===0?e.jsxs(p,{children:[e.jsx(D,{children:e.jsx(R,{className:"text-lg",children:"Engagement Trend"})}),e.jsx(g,{className:"flex h-[300px] items-center justify-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No Data Available"})})]}):e.jsxs(p,{className:"relative",children:[e.jsx(W,{targetRef:a,filename:"tik-tok-engagement-trend-chart"}),e.jsx(D,{children:e.jsx(R,{className:"text-lg",children:"Engagement Trend"})}),e.jsx(g,{ref:a,children:e.jsx("div",{className:"h-[300px]",children:e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(ge,{data:t,margin:{top:5,right:30,left:20,bottom:5},children:[e.jsx(z,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(G,{dataKey:"date",className:"text-xs"}),e.jsx(F,{className:"text-xs"}),e.jsx(X,{contentStyle:{backgroundColor:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:r=>r.toLocaleString()}),e.jsx(Y,{}),e.jsx(V,{type:"monotone",dataKey:"likes",name:"Likes",stroke:"#ff0050",strokeWidth:2,dot:{fill:"#ff0050",r:4}}),e.jsx(V,{type:"monotone",dataKey:"comments",name:"Comments",stroke:"#00f2ea",strokeWidth:2,dot:{fill:"#00f2ea",r:4}}),e.jsx(V,{type:"monotone",dataKey:"shares",name:"Shares",stroke:"#9333ea",strokeWidth:2,dot:{fill:"#9333ea",r:4}})]})})})})]})}function Me({data:l}
1){const[a,t]=d.useState("views"),[r,i]=d.useState("desc"),x=s=>{a===s?i(r==="asc"?"desc":"asc"):(t(s),i("desc"))},S=[...l].sort((s,h)=>{let m,j;switch(a){case"views":m=s.views,j=h.views;break;case"likes":m=s.likes,j=h.likes;break;case"comments":m=s.comments,j=h.comments;break;case"shares":m=s.shares,j=h.shares;break;case"engagementRate":m=s.engagementRate===null?-1:parseFloat(s.engagementRate),j=h.engagementRate===null?-1:parseFloat(h.engagementRate);break;case"publishedAt":m=new Date(s.publishedAt).getTime(),j=new Date(h.publishedAt).getTime();break;default:return 0}return r==="asc"?m-j:j-m}),y=s=>s>=1e6?(s/1e6).toFixed(1)+"M":s>=1e3?(s/1e3).toFixed(1)+"K":s.toLocaleString(),u=({column:s,label:h})=>e.jsxs(L,{variant:"ghost",size:"sm",onClick:()=>x(s),className:"-ml-3 h-8 data-[state=open]:bg-accent",children:[h,e.jsx(ve,{className:"ml-2 h-4 w-4"})]});return l.length===0?e.jsxs(p,{children:[e.jsx(D,{children:e.jsx(R,{className:"text-lg",children:"Video Performance"})}),e.jsx(g,{className:"flex h-[200px] items-center justify-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No videos found in this date range."})})]}):e.jsxs(p,{children:[e.jsx(D,{children:e.jsx(R,{className:"text-lg",children:"Video Performance"})}),e.jsx(g,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Ne,{children:[e.jsx(ye,{children:e.jsxs(U,{children:[e.jsx(v,{className:"w-[350px]",children:"Video"}),e.jsx(v,{children:e.jsx(u,{column:"views",label:"Views"})}),e.jsx(v,{children:e.jsx(u,{column:"likes",label:"Likes"})}),e.jsx(v,{children:e.jsx(u,{column:"comments",label:"Comments"})}),e.jsx(v,{children:e.jsx(u,{column:"shares",label:"Shares"})}),e.jsx(v,{children:e.jsx(u,{column:"engagementRate",label:"Eng. Rate"})}),e.jsx(v,{className:"w-[50px]"})]})}),e.jsx(ke,{children:S.map(s=>e.jsxs(U,{children:[e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[s.thumbnail&&e.jsx("img",{src:s.thumbnail,alt:s.title,loading:"lazy",decoding:"async",className:"h-12 w-12 rounded object-cover"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate font-medium",title:s.title,children:s.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:s.publishedAt?C(new Date(s.publishedAt),"MMM d, yyyy"):"Unknown date"})]})]})}),e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(H,{className:"h-4 w-4 text-muted-foreground"}),y(s.views)]})}),e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(P,{className:"h-4 w-4 text-red-500"}),y(s.likes)]})}),e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{className:"h-4 w-4 text-cyan-500"}),y(s.comments)]})}),e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{className:"h-4 w-4 text-purple-500"}),y(s.shares)]})}),e.jsx(T,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(we,{className:"h-4 w-4 text-pink-500"}),s.engagementRate===null?"â":`${s.engagementRate}%`]})}),e.jsx(T,{children:e.jsx("a",{href:s.permalinkUrl,target:"_blank",rel:"noopener noreferrer",className:"inline-flex h-8 w-8 items-center justify-center rounded-md hover:bg-muted",children:e.jsx(be,{className:"h-4 w-4"})})})]},s.id))})]})})})]})}function os(){const l=Q(),{user:a}=ae(),{analytics:t,isLoading:r,isRefreshing:i,isImporting:x,error:S,tokenExpired:y,fetchAnalytics:u,refreshProfileStats:s,importVideos:h}
1=Se(),[m,j]=d.useState([]),[f,M]=d.useState(""),[k,n]=d.useState(!0),[c,N]=d.useState({from:Ce(new Date,180),to:new Date});d.useEffect(()=>{async function o(){if(!a)return;n(!0);const{data:b,error:K}=await E.from("social_accounts").select("id, account_name, account_id, avatar_url, account_handle").eq("user_id",a.id).eq("platform","tiktok").eq("is_active",!0);K?console.error("Failed to fetch TikTok accounts:",K):b&&b.length>0&&(j(b),M(b[0].id)),n(!1)}o()},[a]);const w=d.useRef(new Set);d.useEffect(()=>{f&&u(f,c.from.toISOString(),c.to.toISOString())},[f,c,u]),d.useEffect(()=>{t&&t.summary.videosInPeriod===0&&f&&a&&!x&&!w.current.has(f)&&(w.current.add(f),h(f).then(o=>{o!=null&&o.success&&o.imported>0&&u(f,c.from.toISOString(),c.to.toISOString())}))},[t,f,a,x,h,u,c]);const J=()=>{f&&s(f)};return k?e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(I,{className:"h-10 w-48"}),e.jsx(I,{className:"h-32 w-full"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[1,2,3,4].map(o=>e.jsx(I,{className:"h-24"},o))})]}):m.length===0?e.jsxs("div",{className:"space-y-5xl max-w-5xl mx-auto",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"TikTok Analytics"}),e.jsx(p,{children:e.jsxs(g,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Te,{className:"mb-4 h-12 w-12 text-[#ff0050]"}),e.jsx("h2",{className:"mb-2 text-xl font-semibold",children:"No TikTok Accounts Connected"}),e.jsx("p",{className:"mb-6 text-center text-muted-foreground",children:"Connect your TikTok account to view detailed analytics about your videos and engagement."}),e.jsx(L,{onClick:()=>l("/accounts"),children:"Connect TikTok Account"})]})})]}):e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"TikTok Analytics"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[m.length>1&&e.jsxs(ce,{value:f,onValueChange:M,children:[e.jsx(de,{className:"w-[200px]",children:e.jsx(me,{placeholder:"Select account"})}),e.jsx(xe,{children:m.map(o=>e.jsx(he,{value:o.id,children:o.account_name||o.account_handle||"TikTok Account"},o.id))})]}),e.jsxs(re,{children:[e.jsx(le,{asChild:!0,children:e.jsxs(L,{variant:"outline",className:"justify-start text-left font-normal",children:[e.jsx(oe,{className:"mr-2 h-4 w-4"}),C(c.from,"MMM d")," - ",C(c.to,"MMM d, yyyy")]})}),e.jsx(ie,{className:"w-auto p-0",align:"end",children:e.jsx(ne,{mode:"range",selected:{from:c.from,to:c.to},onSelect:o=>{if(o!=null&&o.from&&(o!=null&&o.to)){const b=new Date(o.to);b.setHours(23,59,59,999),N({from:o.from,to:b})}},numberOfMonths:2})})]})]})]}),S&&!y&&e.jsx(p,{className:"border-destructive",children:e.jsx(g,{className:"py-4 text-center text-destructive",children:S})}),r?e.jsxs("div",{className:"space-y-6",children:[e.jsx(I,{className:"h-40 w-full"}),e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[1,2,3,4].map(o=>e.jsx(I,{className:"h-24"},o))}),e.jsx(I,{className:"h-80 w-full"})]}):t?e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ae,{account:t.account,isRefreshing:i,onRefresh:J}),t.summary.videosInPeriod===0&&e.jsx(p,{children:e.jsx(g,{className:"flex flex-col items-center justify-center py-8",children:x?e.jsxs(e.Fragment,{children:[e.jsx(_,{className:"mb-3 h-8 w-8 animate-spin text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground",children:"Importing videos..."})]}):e.jsx("p",{className:"text-muted-foreground",children:"No videos found in this date range."})})}),t.summary.videosInPeriod>0&&e.jsxs(e.Fragment,{children:[e.jsx(Ie,{analytics:t}),e.jsx(De,{data:t.dailyActivity}),e.jsx(Re,{data:t.engagementTrend}),e.jsx(Me,{data:t.topVideos})]})]}):null]})}export{os as default};
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.