1import{D as $e,r as x,aE as xs,b as O,W as ve,j as e,am as us,a2 as Z,C as B,g as K,h as Y,U as Te,k as Q,l as U,S as ee,cd as We,c as q,a6 as pe,ak as oe,o as ie,cl as Ke,aO as Ge,aP as qe,aQ as Ye,a as Pe,aM as _e,n as Ae,A as ps,T as fs,M as bs,ai as Re,af as vs,ag as js,B as ys,E as Ns,G as ws,c8 as ks,d as Cs}from"./main-DX7XzkoU.js";import{B as Je}from"./badge-BOGaWzi1.js";import{S as W}from"./skeleton-DN2cjZOe.js";import{T as Ss,a as $s,b as Ts}from"./tabs-BuRg9jtd.js";import{T as Ps,a as _s,b as Le,c as de,d as As,e as me}from"./table-CyYSUJFs.js";import{D as Es,a as Rs,b as Ls,c as De}from"./dropdown-menu-D6liHcXh.js";import{f as Xe}from"./format-number-CwMs0Eao.js";import{a as Ds,b as Ze,d as Qe,e as Is,f as Ms,g as es,h as ss,u as Os}from"./useInstagramInsights-Cc00saZ4.js";import{A as ts}from"./arrow-up-right-BkEMUkZ0.js";import{U as is}from"./user-plus-CFqzcP75.js";import{A as Fs,D as zs,a4 as Bs,bg as Us,bh as Hs,aV as Vs,bi as Ws,E as he,bj as Ks,bk as Gs,bl as Ie,bm as qs,at as Ys,Z as Js,L as Xs,bn as Zs,bo as Qs,aD as re,bp as Me,bq as et,ac as je,ad as ye,af as Ne,ae as Oe}from"./CartesianChart-BKz7V1QD.js";import{B as st}from"./BarChart-CQgXll9F.js";import{C as we}from"./CartesianGrid-DLUwfaYT.js";import{B as Fe}from"./Bar-DADY3n14.js";import{M as tt}from"./mouse-pointer-click-DA8rXXNz.js";import{E as be}from"./eye-DTdVPMB0.js";import{L as ke}from"./link-2-CASnJw5r.js";import{B as ns}from"./bookmark-SFraFE19.js";import{S as it}from"./share-2-DpYr0PID.js";import{F as nt}from"./flame-O0ay5Qs9.js";import{H as Ce}from"./hash-CLBVfWhm.js";import{T as at}from"./type-BrJDeCW1.js";import{C as rt}from"./circle-help-CV3y08qY.js";import{C as ue}from"./chart-column-Dsbf4ZZ1.js";import{D as lt}from"./download-DFu9GkQ8.js";import{F as ot}from"./file-text-BdeBL2Mt.js";import{H as as}from"./heart-C_GZQqCm.js";import{G as ct}from"./globe-BBWCCznd.js";import{A as ze,a as le}from"./AreaChart-Db65sLGO.js";import{I as se}from"./info-DnQ7E39o.js";import{C as Se}from"./clock-DZY59rpR.js";import{T as dt}from"./trending-down-D6wPF7rt.js";import{E as mt}from"./external-link-Bhm5X9sQ.js";import{A as ht}from"./AppHeader-CzkMBh75.js";import{P as gt}from"./PageShell-Bd7x8hXC.js";import{P as xt}from"./PageHeader-CM5sf6Dy.js";import{S as ut,b as pt,c as ft,d as bt}from"./sheet-D4yLKOxB.js";import{S as vt}from"./scroll-area-D4uBgFjC.js";import{M as jt}from"./index-CskwZ_5e.js";import{C as yt}from"./chevron-right-D27HfhtL.js";import{L as Nt}from"./lightbulb-UJa6zn96.js";import{R as wt}from"./rotate-ccw-xkyd1NAq.js";import{M as kt}from"./MobileBottomNav-B6c1hPKj.js";import{M as Ct}from"./message-square-DvfVWKh3.js";import"./index-D6Z5KIMn.js";import"./circle-BXmX70XD.js";import"./AppInstallBanner-CAnCi_kO.js";import"./CreateContentModal-eREkTihJ.js";import"./referral-code-CAIXjQN4.js";import"./megaphone-B0K-HV7w.js";import"./image-BBUOngQh.js";import"./smartphone-WGY3uvd5.js";import"./video-BvJDFQSG.js";import"./image-play-FzvV3P2U.js";import"./palette-OTKsHiwO.js";import"./wand-sparkles-CwRAYUwy.js";import"./clapperboard-BoJYuZop.js";import"./layers-UGj9VXD5.js";import"./ThemeToggle-C5kzRcph.js";import"./monitor-MvsPdGOU.js";import"./routes-Dh-CjbFu.js";import"./history-BQ1iBcZd.js";import"./user-check-BR60HPjZ.js";import"./chart-no-axes-column-CL-SWzid.js";import"./link-D6mXMmG7.js";import"./settings-N25lzdMz.js";import"./user-x-BOA8xi05.js";import"./useInstagramProfiles-D_KQvT_K.js";import"./instagram-uOX4SJX4.js";import"./plus-C6FQ2-b-.js";import"./arrow-left-Cf41rOjY.js";import"./gem-DGeoeC5P.js";import"./menu-B6sRxHFL.js";import"./house-C4ToeB93.js";/** 2 * @license lucide-react v0.462.0 - ISC 3 * 4 * This source code is licensed under the ISC license. 5 * See the LICENSE file in the root directory of this source tree. 6 */const St=$e("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/** 7 * @license lucide-react v0.462.0 - ISC 8 * 9 * This source code is licensed under the ISC license. 10 * See the LICENSE file in the root directory of this source tree. 11 */const $t=$e("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** 12 * @license lucide-react v0.462.0 - ISC 13 * 14 * This source code is licensed under the ISC license. 15 * See the LICENSE file in the root directory of this source tree. 16 */const Tt=$e("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);class Pt{constructor(i){var{x:n,y:r}=i;this.xAxisScale=n,this.yAxisScale=r}
16map(i,n){var r,t,{position:a}=n;return{x:(r=this.xAxisScale.map(i.x,{position:a}))!==null&&r!==void 0?r:0,y:(t=this.yAxisScale.map(i.y,{position:a}))!==null&&t!==void 0?t:0}}mapWithFallback(i,n){var r,t,{position:a,fallback:h}=n,l,o;return h==="rangeMin"?l=this.yAxisScale.rangeMin():h==="rangeMax"?l=this.yAxisScale.rangeMax():l=0,h==="rangeMin"?o=this.xAxisScale.rangeMin():h==="rangeMax"?o=this.xAxisScale.rangeMax():o=0,{x:(r=this.xAxisScale.map(i.x,{position:a}))!==null&&r!==void 0?r:o,y:(t=this.yAxisScale.map(i.y,{position:a}))!==null&&t!==void 0?t:l}}isInRange(i){var{x:n,y:r}=i,t=n==null||this.xAxisScale.isInRange(n),a=r==null||this.yAxisScale.isInRange(r);return t&&a}}function Be(s,i){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);i&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(s,t).enumerable})),n.push.apply(n,r)}return n}function Ue(s){for(var i=1;i<arguments.length;i++){var n=arguments[i]!=null?arguments[i]:{};i%2?Be(Object(n),!0).forEach(function(r){_t(s,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(n)):Be(Object(n)).forEach(function(r){Object.defineProperty(s,r,Object.getOwnPropertyDescriptor(n,r))})}return s}function _t(s,i,n){return(i=At(i))in s?Object.defineProperty(s,i,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[i]=n,s}function At(s){var i=Et(s,"string");return typeof i=="symbol"?i:i+""}function Et(s,i){if(typeof s!="object"||!s)return s;var n=s[Symbol.toPrimitive];if(n!==void 0){var r=n.call(s,i);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(i==="string"?String:Number)(s)}function fe(){return fe=Object.assign?Object.assign.bind():function(s){for(var i=1;i<arguments.length;i++){var n=arguments[i];for(var r in n)({}).hasOwnProperty.call(n,r)&&(s[r]=n[r])}return s},fe.apply(null,arguments)}var Rt=(s,i)=>{var n;if(x.isValidElement(s))n=x.cloneElement(s,i);else if(typeof s=="function")n=s(i);else{if(!re(i.x1)||!re(i.y1)||!re(i.x2)||!re(i.y2))return null;n=x.createElement("line",fe({},i,{className:"recharts-reference-line-line"}))}return n},Lt=(s,i,n,r,t,a)=>{var{x:h,width:l}=a,o=t.map(s,{position:n});if(!re(o)||i==="discard"&&!t.isInRange(o))return null;var g=[{x:h+l,y:o},{x:h,y:o}];return r==="left"?g.reverse():g},Dt=(s,i,n,r,t,a)=>{var{y:h,height:l}=a,o=t.map(s,{position:n});if(!re(o)||i==="discard"&&!t.isInRange(o))return null;var g=[{x:o,y:h+l},{x:o,y:h}];return r==="top"?g.reverse():g},It=(s,i,n,r)=>{var t=[r.mapWithFallback(s[0],{position:n,fallback:"rangeMin"}),r.mapWithFallback(s[1],{position:n,fallback:"rangeMax"})];return i==="discard"&&t.some(a=>!r.isInRange(a))?null:t},Mt=(s,i,n,r,t,a,h)=>{var{x:l,y:o,segment:g,ifOverflow:p}=h,j=Me(l),b=Me(o);return b?Lt(o,p,r,a,i,n):j?Dt(l,p,r,t,s,n):g!=null&&g.length===2?It(g,p,r,new Pt({x:s,y:i})):null};function Ot(s){var i=Bs();return x.useEffect(()=>(i(Us(s)),()=>{i(Hs(s))})),null}function Ft(s){var{xAxisId:i,yAxisId:n,shape:r,className:t,ifOverflow:a}=s,h=Vs(),l=Ws(),o=he(T=>Ks(T,i)),g=he(T=>Gs(T,n)),p=he(T=>Ie(T,"xAxis",i,h)),j=he(T=>Ie(T,"yAxis",n,h)),b=qs();if(!l||!b||o==null||g==null||p==null||j==null)return null;var $=Mt(p,j,b,s.position,o.orientation,g.orientation,s);if(!$)return null;var y=$[0],E=$[1];if(y==null||E==null)return null;var{x:C,y:c}=y,{x:R,y:_}=E,S=a==="hidden"?"url(#".concat(l,")"):void 0,D=Ue(Ue({clipPath:S},Ys(s)),{},{x1:C,y1:c,x2:R,y2:_}),I=et({x1:C,y1:c,x2:R,y2:_});return x.createElement(Js,{zIndex:s.zIndex},x.createElement(Xs,{className:xs("recharts-reference-line",t)},Rt(r,D),x.createElement(Zs,fe({},I,{lowerWidth:I.width,upperWidth:I.width}),x.createElement(Qs,{label:s.label}),s.children)))}var zt={ifOverflow:"discard",xAxisId:0,yAxisId:0,fill:"none",label:!1,stroke:"#ccc",fillOpacity:1,strokeWidth:1,position:"middle",zIndex:zs.line};function rs(s){var i=Fs(s,zt);return x.createElement(x.Fragment,null,x.createElement(Ot,{yAxisId:i.yAxisId,xAxisId:i.xAxisId,ifOverflow:i.ifOverflow,x:i.x,y:i.y,segment:i.segment}),x.createElement(Ft,i))}rs.displayName="ReferenceLine";
16function Bt(s,i){const[n,r]=x.useState(null),[t,a]=x.useState(!1),[h,l]=x.useState(null),[o,g]=x.useState(!1),{i18n:p}=O(),j=x.useRef(null),b=async y=>{var R;const E=(R=p.language)!=null&&R.startsWith("pt")?"pt":"en",{data:C,error:c}=await ve.functions.invoke("generate-insights-summary",{body:{instagram_profile_id:y,period_days:i,language:E}});if(c)throw new Error(c.message);if(!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||"Failed to generate summary");return{summary:C.summary,highlights:C.highlights,generated_at:C.generated_at,from_cache:C.from_cache??!0}};return x.useEffect(()=>{if(!s)return;const y=`${s}-${i}`;j.current!==y&&(j.current=y,r(null),l(null),g(!1),a(!0),b(s).then(E=>{r(E),g(!1)}).catch(E=>l(E instanceof Error?E.message:"Unknown error")).finally(()=>{a(!1),j.current=null}))},[s,i]),{data:n,loading:t,error:h,regenerate:async()=>{if(s){a(!0),l(null);try{const y=await b(s);r(y),g(!1)}catch(y){l(y instanceof Error?y.message:"Unknown error")}finally{a(!1)}}},isStale:o}}function Ee(){const{i18n:s}=O();return s.language.startsWith("pt")?"pt-BR":"en-US"}function ce(s,i){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString(i)}function ls({post:s,rank:i,metricLabel:n,metricValue:r,metricClass:t}){const{t:a}=O();return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx("div",{className:"w-11 h-11 rounded-lg overflow-hidden bg-muted",children:s.thumbnailUrl||s.mediaUrl?e.jsx("img",{src:s.thumbnailUrl||s.mediaUrl,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(be,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("div",{className:"absolute -top-1 -left-1 w-4 h-4 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-[9px] font-bold",children:i})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-0.5",children:e.jsx(Je,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4",children:a(`publishing.insights.mediaTypes.${s.mediaType}`,{defaultValue:s.mediaType})})}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:s.caption||a("publishing.insights.topPosts.noCaption")})]}),e.jsxs("div",{className:"flex flex-col items-end flex-shrink-0",children:[e.jsx("span",{className:Z("text-sm font-bold",t),children:r}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:n})]})]})}function Ut({accountInsights:s,selectedPeriod:i,loading:n}){const{t:r}=O(),t=x.useMemo(()=>n?[]:Ds(s,i),[s,i,n]);return t.length===0?null:e.jsx("div",{className:"space-y-2",children:t.map(a=>{const h=a.tone==="positive",l=Math.abs(a.changePct);return e.jsxs("div",{className:Z("flex items-center gap-3 rounded-lg border px-4 py-3",h?"border-emerald-500/20 bg-emerald-500/5":"border-amber-500/20 bg-amber-500/5"),children:[h?e.jsx(ts,{className:"h-4 w-4 shrink-0 text-emerald-500"}):e.jsx(us,{className:"h-4 w-4 shrink-0 text-amber-500"}),e.jsx("p",{className:"text-sm text-foreground/90",children:r(`publishing.insights.analytics.anomalies.${a.kind}`,{pct:l})})]},a.kind)})})}function Ht({accountInsights:s,selectedPeriod:i,loading:n}){const{t:r}=O(),t=Ee(),a=x.useMemo(()=>Ze(s,i),[s,i]);if(n||!a.hasData)return null;const h=r("publishing.insights.netGrowth.follows"),l=r("publishing.insights.netGrowth.unfollows"),o=a.daily.map(p=>({date:p.label,[h]:p.follows,[l]:-p.unfollows})),g=a.net>=0;return e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Te,{className:"h-4 w-4 text-violet-500"}),r("publishing.insights.analytics.followerFlow.title")]}),e.jsx(Q,{className:"text-xs",children:r("publishing.insights.analytics.followerFlow.subtitle")})]}),e.jsxs(U,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"rounded-lg border bg-emerald-500/5 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1 text-emerald-600 dark:text-emerald-400",children:[e.jsx(is,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"text-lg font-bold",children:["+",ce(a.gained,t)]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:h})]}),e.jsxs("div",{className:"rounded-lg border bg-red-500/5 px-3 py-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1 text-red-600 dark:text-red-400",children:[e.jsx(Tt,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"text-lg font-bold",children:["â",ce(a.lost,t)]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:l})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 px-3 py-2.5",children:[e.jsxs("div",{className:Z("flex items-center gap-1",g?"text-emerald-600 dark:text-emerald-400":"text-red-600 dark:text-red-400"),children:[g?e.jsx(ts,{className:"h-3.5 w-3.5"}):e.jsx(St,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"text-lg font-bold",children:[g?"+":"â",ce(Math.abs(a.net),t)]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground",children:r("publishing.insights.netGrowth.net")})]})]}),a.retentionRate!==null&&e.jsx("p",{className:"text-xs text-muted-foreground",children:r("publishing.insights.analytics.followerFlow.retention",{rate:a.retentionRate})}),o.length>1&&e.jsx(je,{width:"100%",height:120,children:e.jsxs(st,{data:o,margin:{top:4,right:4,left:-28,bottom:0},stackOffset:"sign",children:[e.jsx(we,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.4,vertical:!1}),e.jsx(ye,{dataKey:"date",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"}
16,tickLine:!1,axisLine:!1,interval:"preserveStartEnd"}),e.jsx(rs,{y:0,stroke:"hsl(var(--border))"}),e.jsx(Ne,{cursor:{fill:"hsl(var(--muted))",opacity:.3},contentStyle:{fontSize:12,borderRadius:8,border:"1px solid hsl(var(--border))",background:"hsl(var(--background))"},formatter:(p,j)=>[Math.abs(p).toLocaleString(t),j]}),e.jsx(Fe,{dataKey:h,stackId:"flow",fill:"#10b981",radius:[2,2,0,0]}),e.jsx(Fe,{dataKey:l,stackId:"flow",fill:"#ef4444",radius:[0,0,2,2]})]})})]})]})}function ge({icon:s,label:i,value:n,locale:r}){return e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border bg-muted/30 px-3 py-2.5",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-background ring-1 ring-border",children:e.jsx(s,{className:"h-4 w-4 text-violet-500"})}),e.jsx("span",{className:"text-sm text-muted-foreground flex-1",children:i}),e.jsx("span",{className:"text-sm font-bold",children:ce(n,r)})]})}function Vt({accountInsights:s,selectedPeriod:i,loading:n}){const{t:r}=O(),t=Ee(),a=x.useMemo(()=>Qe(s,i),[s,i]);return n||!a.hasData?null:e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(tt,{className:"h-4 w-4 text-violet-500"}),r("publishing.insights.analytics.funnel.title")]}),e.jsx(Q,{className:"text-xs",children:r("publishing.insights.analytics.funnel.subtitle")})]}),e.jsxs(U,{className:"space-y-1.5",children:[e.jsx(ge,{icon:be,label:r("publishing.insights.metrics.reach"),value:a.reach,locale:t}),a.reachToEngaged!==null&&e.jsxs("p",{className:"text-center text-[11px] text-muted-foreground",children:["â ",r("publishing.insights.analytics.funnel.reachToEngaged",{rate:a.reachToEngaged})]}),e.jsx(ge,{icon:Te,label:r("publishing.insights.metrics.accountsEngaged"),value:a.accountsEngaged,locale:t}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-x-4 gap-y-1 pt-1",children:[a.engagedToFollow!==null&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:r("publishing.insights.analytics.funnel.engagedToFollow",{rate:a.engagedToFollow})}),a.engagedToClick!==null&&e.jsx("span",{className:"text-[11px] text-muted-foreground",children:r("publishing.insights.analytics.funnel.engagedToClick",{rate:a.engagedToClick})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 pt-1",children:[e.jsx(ge,{icon:is,label:r("publishing.insights.netGrowth.follows"),value:a.follows,locale:t}),e.jsx(ge,{icon:ke,label:r("publishing.insights.metrics.websiteClicks"),value:a.websiteClicks,locale:t})]})]})]})}function He({items:s,metricLabel:i,metricClass:n,emptyLabel:r}){return s.length===0?e.jsx("p",{className:"py-6 text-center text-xs text-muted-foreground",children:r}):e.jsx("div",{className:"space-y-3",children:s.map((t,a)=>e.jsx(ls,{post:t.post,rank:a+1,metricLabel:i,metricValue:`${t.rate.toFixed(1)}%`,metricClass:n},t.post.mediaId))})}function Wt({mediaInsights:s,loading:i}){const{t:n}=O(),r=x.useMemo(()=>Is(s),[s]);return i||!r.hasData?null:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(ns,{className:"h-4 w-4 text-blue-500"}),n("publishing.insights.analytics.saveable.title")]}),e.jsx(Q,{className:"text-xs",children:n("publishing.insights.analytics.saveable.subtitle")})]}),e.jsx(U,{children:e.jsx(He,{items:r.topSaved,metricLabel:n("publishing.insights.analytics.saveable.metric"),metricClass:"text-blue-600 dark:text-blue-400",emptyLabel:n("publishing.insights.analytics.saveable.empty")})})]}),e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(it,{className:"h-4 w-4 text-fuchsia-500"}),n("publishing.insights.analytics.viral.title")]}),e.jsx(Q,{className:"text-xs",children:n("publishing.insights.analytics.viral.subt
16itle")})]}),e.jsx(U,{children:e.jsx(He,{items:r.topShared,metricLabel:n("publishing.insights.analytics.viral.metric"),metricClass:"text-fuchsia-600 dark:text-fuchsia-400",emptyLabel:n("publishing.insights.analytics.viral.empty")})})]})]})}function Kt({mediaInsights:s,mediaSnapshots:i,loading:n}){const{t:r}=O(),t=x.useMemo(()=>Ms(s,i),[s,i]);return n||!t.hasData?null:e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(nt,{className:"h-4 w-4 text-orange-500"}),r("publishing.insights.analytics.momentum.title")]}),e.jsx(Q,{className:"text-xs",children:r("publishing.insights.analytics.momentum.subtitle")})]}),e.jsx(U,{className:"space-y-3",children:t.stillGrowing.map((a,h)=>e.jsx(ls,{post:a.post,rank:h+1,metricLabel:r("publishing.insights.analytics.momentum.metric"),metricValue:`+${a.reachDeltaPct.toFixed(0)}%`,metricClass:"text-orange-600 dark:text-orange-400"},a.post.mediaId))})]})}function Gt({contentTypeBreakdown:s,loading:i}
16){var o;const{t:n}=O(),r=Ee(),t=x.useMemo(()=>es(s),[s]);if(i||!t.hasData||!t.best||!t.baseline)return null;const a=((o=t.rows[0])==null?void 0:o.avgReach)||1,h=n(`publishing.insights.mediaTypes.${t.best.mediaType}`,{defaultValue:t.best.mediaType}),l=n(`publishing.insights.mediaTypes.${t.baseline.mediaType}`,{defaultValue:t.baseline.mediaType});return e.jsxs(B,{children:[e.jsx(K,{className:"pb-3",children:e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(ee,{className:"h-4 w-4 text-violet-500"}),n("publishing.insights.analytics.formatLift.title")]})}),e.jsxs(U,{className:"space-y-4",children:[t.reachLift!==null&&t.reachLift>1&&e.jsxs("div",{className:"rounded-lg border border-violet-500/20 bg-violet-500/5 px-3 py-2.5",children:[e.jsx("p",{className:"text-sm text-foreground/90",children:n("publishing.insights.analytics.formatLift.headline",{best:h,lift:t.reachLift,baseline:l})}),t.best.mix<=33&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:n("publishing.insights.analytics.formatLift.mixHint",{type:h,mix:t.best.mix})})]}),e.jsx("div",{className:"space-y-2.5",children:t.rows.map(g=>{const p=n(`publishing.insights.mediaTypes.${g.mediaType}`,{defaultValue:g.mediaType});return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1 text-xs",children:[e.jsx("span",{className:"font-medium",children:p}),e.jsxs("span",{className:"text-muted-foreground",children:[ce(g.avgReach,r)," · ",n("publishing.insights.analytics.formatLift.mixLabel",{mix:g.mix})]})]}),e.jsx(We,{value:g.avgReach/a*100,className:"h-1.5"})]},g.mediaType)})})]})]})}const qt={hashtags:Ce,question:rt,length:at};function Yt({mediaInsights:s,loading:i}){const{t:n}=O(),r=x.useMemo(()=>ss(s),[s]);return i||!r.hasData?null:e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Ce,{className:"h-4 w-4 text-violet-500"}),n("publishing.insights.analytics.caption.title")]}),e.jsx(Q,{className:"text-xs",children:n("publishing.insights.analytics.caption.subtitle")})]}),e.jsx(U,{className:"space-y-2.5",children:r.findings.map(t=>{const a=qt[t.dimension]??Ce,h=n(`publishing.insights.analytics.caption.buckets.${t.dimension}.${t.bucketKey}`),l=n(`publishing.insights.analytics.caption.dimensions.${t.dimension}`);return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 bg-muted/40 px-3 py-2.5",children:[e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-background ring-1 ring-border mt-0.5",children:e.jsx(a,{className:"h-3 w-3 text-violet-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-xs text-foreground/90",children:[e.jsxs("span",{className:"text-muted-foreground",children:[l,": "]}),e.jsx("span",{className:"font-semibold",children:h})]}),e.jsx("p",{className:"text-[11px] text-emerald-600 dark:text-emerald-400 mt-0.5",children:n("publishing.insights.analytics.caption.lift",{lift:t.lift,posts:t.sampleSize})})]})]},t.dimension)})})]})}const Jt=[{labelKey:"publishing.insights.periods.7days",value:7},{labelKey:"publishing.insights.periods.30days",value:30},{labelKey:"publishing.insights.periods.90days",value:90}];function Ve({active:s,payload:i,label:n}){return!s||!(i!=null&&i.length)?null:e.jsxs("div",{className:"rounded-lg border bg-background px-3 py-2 shadow-lg text-xs",children:[e.jsx("p",{className:"text-muted-foreground mb-1 font-medium",children:n}),i.map((r,t)=>e.jsxs("p",{style:{color:r.color},className:"font-semibold",children:[r.name,": ",Number(r.value).toLocaleString()]},t))]})}function ne({title:s,value:i,change:n,isRawChange:r,icon:t,iconBg:a,loading:h}){const{i18n:l}=O(),o=l.language.startsWith("pt")?"pt-BR":"en-US";if(h)return e.jsx(B,{children:e.jsxs(U,{className:"p-5",children:[e.jsx(W,{className:"h-4 w-24 mb-3"}),e.jsx(W,{className:"h-8 w-20 mb-2"}),e.jsx(W,{className:"h-3 w-16"})]})});const g=n!==void 0&&n>=0,p=r?`${g?"+":""}${(n==null?void 0:n.toLocaleString(o))??""}`:`${g?"+":""}${n??""}%`;return e.jsx(B,{children:e.jsxs(U,{className:"p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium leading-tight",children:s}),e.jsx("div",{className:Z("p-2 rounded-lg flex-shrink-0",a),children:e.jsx(t,{className:"h-3.5 w-3.5 text-white"})})]}),e.jsx("div",{className:"text-2xl font-bold tracking-tight mb-1",children:i===null?"â":Xe(i,o)}),n!==void 0&&n!==0&&e.jsxs("div",{className:"flex items-center gap-1",children:[g?e.jsx(fs,{className:"h-3 w-3 text-green-500"}):e.jsx(dt,{className:"h-3 w-3 text-red-500"}),e.jsx("span",{className:Z("text-xs font-medium",g?"text-green-500":"text-red-500"),children:p})]})]})})}function Xt({post:s,rank:i}){const{t:n,i18n:r}
16=O(),t=r.language.startsWith("pt")?"pt-BR":"en-US";return e.jsxs("div",{className:"flex gap-3 items-start",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx("div",{className:"w-14 h-14 rounded-lg overflow-hidden bg-muted",children:s.thumbnailUrl||s.mediaUrl?e.jsx("img",{src:s.thumbnailUrl||s.mediaUrl,alt:"",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ue,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx("div",{className:"absolute -top-1 -left-1 w-4 h-4 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-[9px] font-bold",children:i})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-1",children:[e.jsx(Je,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4",children:n(`publishing.insights.mediaTypes.${s.mediaType}`,{defaultValue:s.mediaType})}),e.jsxs("span",{className:"text-xs font-semibold text-green-600",children:[s.engagementRate,"%"]}),s.permalink&&e.jsx("a",{href:s.permalink,target:"_blank",rel:"noopener noreferrer",className:"ml-auto text-muted-foreground hover:text-primary",children:e.jsx(mt,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1 mb-1.5",children:s.caption||n("publishing.insights.topPosts.noCaption")}),e.jsxs("div",{className:"flex gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(as,{className:"h-3 w-3"}),s.likeCount.toLocaleString(t)]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(bs,{className:"h-3 w-3"}),s.commentsCount.toLocaleString(t)]}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ns,{className:"h-3 w-3"}),s.savedCount.toLocaleString(t)]}),e.jsxs("span",{className:"flex items-center gap-0.5 ml-auto",children:[e.jsx(be,{className:"h-3 w-3"}),s.reach.toLocaleString(t)]})]})]})]})}function xe({label:s,percentage:i}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsxs("span",{className:"text-xs font-semibold",children:[i.toFixed(1),"%"]})]}),e.jsx(We,{value:i,className:"h-1.5"})]})}function os(){return e.jsx("span",{className:"ml-auto rounded-full bg-violet-600 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white",children:"PRO"})}function cs(){const{t:s}=O(),{openPricingModal:i}=_e();return e.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-background/60 p-4 text-center backdrop-blur-[2px]",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-violet-100 ring-4 ring-violet-100/50 dark:bg-violet-900/40 dark:ring-violet-900/20",children:e.jsx(Ae,{className:"h-[18px] w-[18px] text-violet-600 dark:text-violet-400"})}),e.jsx("p",{className:"text-sm font-semibold",children:s("publishing.insights.premium.subscriberOnly")}),e.jsxs(q,{size:"sm",className:"gap-2 bg-violet-600 text-white shadow-lg shadow-violet-500/20 hover:bg-violet-700",onClick:()=>i(),children:[e.jsx(ee,{className:"h-3.5 w-3.5"}),s("publishing.insights.premium.unlock")]})]})}function Zt({profileId:s,periodDays:i,loading:n,isSubscribed:r}){const{t}=O(),a=Pe(),{openPricingModal:h}=_e(),{data:l,loading:o,error:g,regenerate:p,isStale:j}=Bt(n||!r?null:s,i);return!s||n?null:r?e.jsxs(B,{className:"overflow-hidden border border-border bg-card",children:[e.jsx("div",{className:"h-0.5 bg-gradient-to-r from-violet-500 via-purple-500 to-fuchsia-400"}),e.jsx(K,{className:"pb-3 border-b border-border",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5 min-w-0",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-violet-100 dark:bg-violet-900/40",children:e.jsx(ee,{className:"h-4 w-4 text-violet-600 dark:text-violet-400"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold leading-none",children:t("publishing.insights.aiSummary.title")}),l&&!o&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5 truncate",children:t("publishing.insights.aiSummary.poweredBy",{days:i})})]})]}),j&&!o&&e.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-[11px] text-amber-600 dar
16k:text-amber-400 font-medium",children:[e.jsx(Se,{className:"h-3 w-3"}),t("publishing.insights.aiSummary.stale")]})]})}),e.jsxs(U,{className:"pt-4 pb-5",children:[o&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ie,{className:"h-3.5 w-3.5 animate-spin text-violet-500 shrink-0"}),t("publishing.insights.aiSummary.generating")]}),e.jsxs("div",{className:"space-y-2 pl-4 border-l-2 border-violet-200 dark:border-violet-800",children:[e.jsx(W,{className:"h-3 w-full"}),e.jsx(W,{className:"h-3 w-11/12"}),e.jsx(W,{className:"h-3 w-5/6"}),e.jsx(W,{className:"h-3 w-3/4"})]}),e.jsx("div",{className:"space-y-2 pt-1",children:[1,2,3].map(b=>e.jsx(W,{className:"h-11 w-full rounded-lg"},b))})]}),!o&&g&&e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-3",children:[e.jsx(pe,{className:"h-4 w-4 text-destructive shrink-0"}),e.jsx("p",{className:"text-xs text-muted-foreground flex-1",children:t("publishing.insights.aiSummary.errorTitle")}),e.jsxs(q,{variant:"outline",size:"sm",onClick:p,className:"h-7 text-xs gap-1 shrink-0",children:[e.jsx(oe,{className:"h-3 w-3"}),t("publishing.insights.aiSummary.retry")]})]}),!o&&l&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"pl-3 border-l-2 border-violet-300 dark:border-violet-700",children:e.jsx("p",{className:"text-sm text-foreground/90 leading-relaxed",children:l.summary})}),l.highlights.length>0&&e.jsx("div",{className:"space-y-2",children:l.highlights.map((b,$)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 bg-muted/40 px-3 py-2.5 hover:bg-muted/70 transition-colors",children:[e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-background ring-1 ring-border mt-0.5",children:e.jsx("span",{className:"text-[13px] leading-none",children:b.icon})}),e.jsx("span",{className:"text-xs text-foreground/80 leading-relaxed",children:b.text})]},$))}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t border-border",children:[l.generated_at&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Se,{className:"h-3 w-3 text-muted-foreground/60"}),e.jsx("span",{className:"text-[10px] text-muted-foreground/60",children:new Date(l.generated_at).toLocaleString()})]}),e.jsxs("button",{onClick:()=>a("/dashboard/insights"),className:"flex items-center gap-1 text-xs text-violet-600 dark:text-violet-400 hover:underline font-medium ml-auto",children:[t("publishing.insights.aiSummary.viewMore"),e.jsx(ps,{className:"h-3 w-3"})]})]})]})]})]}):e.jsx(e.Fragment,{children:e.jsxs(B,{className:"overflow-hidden border border-border bg-card",children:[e.jsx("div",{className:"h-0.5 bg-gradient-to-r from-violet-500 via-purple-500 to-fuchsia-400"}),e.jsx(K,{className:"pb-3 border-b border-border",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-violet-100 dark:bg-violet-900/40",children:e.jsx(ee,{className:"h-4 w-4 text-violet-600 dark:text-violet-400"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold leading-none",children:t("publishing.insights.aiSummary.title")}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-0.5",children:t("publishing.insights.aiSummary.poweredBy",{days:i})})]}),e.jsx("span",{className:"ml-auto rounded-full bg-violet-600 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide text-white",children:"PRO"})]})}),e.jsxs(U,{className:"relative pt-4 pb-5 overflow-hidden",children:[e.jsxs("div",{className:"blur-sm pointer-events-none select-none space-y-4","aria-hidden":!0,children:[e.jsxs("div",{className:"pl-3 border-l-2 border-violet-300 dark:border-violet-700 space-y-1.5",children:[e.jsx("div",{className:"h-3.5 w-full rounded bg-muted"}),e.jsx("div",{className:"h-3.5 w-11/12 rounded bg-muted"}),e.jsx("div",{className:"h-3.5 w-5/6 rounded bg-muted"}),e.jsx("div",{className:"h-3.5 w-4/6 rounded bg-muted"})]}
16),e.jsx("div",{className:"space-y-2",children:["ð","ð¡","ð¯"].map((b,$)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 bg-muted/40 px-3 py-2.5",children:[e.jsx("div",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-background ring-1 ring-border mt-0.5",children:e.jsx("span",{className:"text-[13px] leading-none",children:b})}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-3 w-full rounded bg-muted"}),e.jsx("div",{className:"h-3 w-4/5 rounded bg-muted"})]})]},$))})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background/60 backdrop-blur-[2px]",children:[e.jsxs("div",{className:"flex flex-col items-center gap-2 text-center px-6",children:[e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-violet-100 dark:bg-violet-900/40 ring-4 ring-violet-100/50 dark:ring-violet-900/20",children:e.jsx(Ae,{className:"h-4.5 w-4.5 text-violet-600 dark:text-violet-400"})}),e.jsx("p",{className:"text-sm font-semibold",children:t("publishing.insights.aiSummary.subscriberOnly")})]}),e.jsxs(q,{className:"bg-violet-600 hover:bg-violet-700 text-white shadow-lg shadow-violet-500/20 gap-2",onClick:()=>h(),children:[e.jsx(ee,{className:"h-3.5 w-3.5"}),t("publishing.insights.aiSummary.viewAnalysis")]})]})]})]})})}function Qt({overview:s,chartData:i,mediaInsights:n,mediaSnapshots:r=[],accountInsights:t,loading:a,syncing:h,error:l,lastSyncAt:o,selectedPeriod:g,profileId:p,isSubscribed:j=!1,onPeriodChange:b,onSync:$,onConnect:y,onExportCsv:E,onExportPdf:C}){var w,k,F;const{t:c}=O(),R=c("publishing.insights.charts.reach"),_=c("publishing.insights.charts.impressions"),S=c("publishing.insights.charts.followers"),D=x.useMemo(()=>i?i.reach.map((m,L)=>{var M;return{date:m.label??m.date,[R]:m.value,[_]:((M=i.impressions[L])==null?void 0:M.value)??0}}):[],[i,R,_]),I=x.useMemo(()=>i?i.followers.map(m=>({date:m.label??m.date,[S]:m.value})):[],[i,S]),T=c("publishing.insights.comparison.previousPeriod"),H=x.useMemo(()=>{var d;if(!t.length||!((d=i==null?void 0:i.reach)!=null&&d.length))return D;const m=[...t].sort((P,J)=>new Date(P.date).getTime()-new Date(J.date).getTime()),L=i.reach.length,M=m.slice(0,Math.max(0,m.length-L)).slice(-L);return M.length===0?D:D.map((P,J)=>{var z;return{...P,[`${R} (${T})`]:((z=M[J])==null?void 0:z.reach)??0}})},[D,t,i,R,T]),G=x.useMemo(()=>{var d;if(!t.length||!((d=i==null?void 0:i.followers)!=null&&d.length))return I;const m=[...t].sort((P,J)=>new Date(P.date).getTime()-new Date(J.date).getTime()),L=i.followers.length,M=m.slice(0,Math.max(0,m.length-L)).slice(-L);return M.length===0?I:I.map((P,J)=>{var z;return{...P,[`${S} (${T})`]:((z=M[J])==null?void 0:z.followerCount)??0}})},[I,t,i,S,T]),V=x.useMemo(()=>{if(!o)return null;const m=Date.now()-o.getTime(),L=Math.floor(m/6e4),M=Math.floor(m/36e5),d=Math.floor(m/864e5);return L<1?c("publishing.insights.timeAgo.now"):L<60?c("publishing.insights.timeAgo.minutes",{count:L}):M<24?c("publishing.insights.timeAgo.hours",{count:M}):c("publishing.insights.timeAgo.days",{count:d})},[o,c]);if(!a&&s&&!s.isConnected)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center gap-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-gradient-to-br from-violet-500 to-pink-500 flex items-center justify-center",children:e.jsx(ue,{className:"h-8 w-8 text-white"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:c("publishing.insights.connectTitle")}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:c("publishing.insights.connectDesc")})]}),y&&e.jsxs(q,{onClick:y,className:"bg-gradient-to-r from-violet-600 to-pink-600 text-white border-0",children:[e.jsx(ke,{className:"h-4 w-4 mr-2"}),c("publishing.insights.connectAccount")]})]});if(!a&&s&&!s.hasInsightsPermission)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center gap-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-amber-100 dar
16k:bg-amber-900/30 flex items-center justify-center",children:e.jsx(pe,{className:"h-8 w-8 text-amber-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:c("publishing.insights.permissionTitle")}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:c("publishing.insights.permissionDesc")})]}),y&&e.jsxs(q,{onClick:y,variant:"outline",children:[e.jsx(oe,{className:"h-4 w-4 mr-2"}),c("publishing.insights.reconnectAccount")]})]});if(l&&!a)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center gap-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-destructive/10 flex items-center justify-center",children:e.jsx(pe,{className:"h-8 w-8 text-destructive"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:c("publishing.insights.errorTitle")}),e.jsx("p",{className:"text-muted-foreground text-sm",children:l})]}),e.jsxs(q,{onClick:$,variant:"outline",disabled:h,children:[h?e.jsx(ie,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(oe,{className:"h-4 w-4 mr-2"}),c("publishing.insights.tryAgain")]})]});if(!a&&(s!=null&&s.isConnected)&&(s!=null&&s.hasInsightsPermission)&&!o)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center gap-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-violet-100 dark:bg-violet-900/30 flex items-center justify-center",children:e.jsx(ue,{className:"h-8 w-8 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:c("publishing.insights.readyToSync")}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:c("publishing.insights.readyToSyncDesc")})]}),e.jsx(q,{onClick:$,disabled:h,className:"bg-gradient-to-r from-violet-600 to-pink-600 text-white border-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(ie,{className:"h-4 w-4 mr-2 animate-spin"}),c("publishing.insights.syncing")]}):e.jsxs(e.Fragment,{children:[e.jsx(oe,{className:"h-4 w-4 mr-2"}),c("publishing.insights.syncNow")]})})]});const{summary:f,mediaPerformance:v,demographics:N}=s||{},u=!a&&(Ze(t,g).hasData||Qe(t,g).hasData),A=!a&&(es(v==null?void 0:v.contentTypeBreakdown).hasData||ss(n).hasData);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsx(Ss,{value:String(g),onValueChange:m=>b(Number(m)),children:e.jsx($s,{children:Jt.map(m=>e.jsx(Ts,{value:String(m.value),children:c(m.labelKey)},m.value))})}),e.jsxs("div",{className:"flex items-center gap-3",children:[V&&e.jsx("span",{className:"text-xs text-muted-foreground hidden sm:block",children:c("publishing.insights.lastUpdated",{time:V})}),(E||C)&&e.jsxs(Es,{children:[e.jsx(Rs,{asChild:!0,children:e.jsxs(q,{variant:"outline",size:"sm",disabled:a||!(s!=null&&s.summary),children:[e.jsx(lt,{className:"h-3.5 w-3.5 mr-1.5"}),c("publishing.insights.export.button")]})}),e.jsxs(Ls,{align:"end",children:[E&&e.jsxs(De,{onClick:E,children:[e.jsx($t,{className:"h-4 w-4 mr-2"}),c("publishing.insights.export.csv")]}),C&&e.jsxs(De,{onClick:C,children:[e.jsx(ot,{className:"h-4 w-4 mr-2"}),c("publishing.insights.export.pdf")]})]})]}),e.jsxs(q,{variant:"outline",size:"sm",onClick:$,disabled:h||a,children:[h?e.jsx(ie,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(oe,{className:"h-3.5 w-3.5 mr-1.5"}),c("publishing.insights.sync")]})]})]}),e.jsx(Ut,{accountInsights:t,selectedPeriod:g,loading:a}),e.jsx(Zt,{profileId:p,periodDays:g,loading:a,isSubscribed:j}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-3 gap-4",children:[e.jsx(ne,{title:c("publishing.insights.metrics.followers"),value:(f==null?void 0:f.followerCount)??0,change:f==null?void 0:f.followerChange,isRawChange:!0,icon:Te,iconBg:"bg-gradient-to-br from-violet-500 to-violet-700",loading:a}),e.jsx(ne,{title:c("publishing.insights.metrics.reach"),value:(f==null?void 0:f.reach)??0,change:f==null?void 0:f.reachChange,icon:be,iconBg:"bg-gradient-to-br from-pink-500 to-rose-600",loading:a}),e.jsx(ne,{title:c("publishing.insights.metrics.impressions"),value:(f==null?void 0:f.impressions)??0,change:f==null?void 0:f.impressionsChange,icon:ue,iconBg:"bg-gradient-to-br from-blue-500 to-blue-700",loading:a}),e.jsx(ne,{title:c("publishing.insights.metrics.interactions"),value:(f==null?void 0:f.totalInteractions)??0,change:f==null?void 0:f.interactionsChange,icon:as,iconBg:"bg-gradient-to-br from-orange-500 to-red-500",loading:a}),e.jsx(ne,{title:c("publishing.insights.metrics.accountsEngaged"),value:(f==null?void 0:f.accountsEngaged)??null,change:f==null?void 0:f.accountsEngagedChange,icon:ct,iconBg:"bg-gradient-to-br from-teal-500 to-emerald-600",loading:a}),e.jsx(ne,{title:c("publishing.insights.metrics.websiteClicks"),value:(f==null?void 0:f.websiteClicks)??0,change:f==null?void 0:f.websiteClicksChange,icon:ke,iconBg:"bg-gradient-to-br from-indigo-500 to-purple-600",loading:a})]}),u&&e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(Ht,{accountInsights:t,selectedPeriod:g,loading:a}),e.jsx(Vt,{accountInsights:t,selectedPeriod:g,loading:a})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(B,{children:[e.jsxs(K,{className:"pb-2",children:[e.jsx(Y,{className:"text-sm font-semibold",children:c("publishing.insights.charts.followerGrowth")}),e.jsx(Q,{className:"text-xs",children:c("publishing.insights.subtitle",{days:g})})]}),e.jsx(U,{children:a?e.jsx(W,{className:"h-48 w-full"}):I.length>0?e.jsx(je,{width:"100%",height:180,children:e.jsxs(ze,{data:G,margin:{top:4,right:4,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"gradFollowers",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",
16stopColor:"#8b5cf6",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#8b5cf6",stopOpacity:0})]})}),e.jsx(we,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.5}),e.jsx(ye,{dataKey:"date",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,interval:"preserveStartEnd"}),e.jsx(Oe,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,tickFormatter:m=>m>=1e3?`${(m/1e3).toFixed(0)}K`:m}),e.jsx(Ne,{content:e.jsx(Ve,{})}),e.jsx(le,{type:"monotone",dataKey:`${S} (${T})`,stroke:"#8b5cf6",strokeWidth:1,strokeDasharray:"4 4",strokeOpacity:.4,fill:"none",dot:!1}),e.jsx(le,{type:"monotone",dataKey:S,stroke:"#8b5cf6",strokeWidth:2,fill:"url(#gradFollowers)",dot:!1})]})}):e.jsxs("div",{className:"h-48 flex flex-col items-center justify-center text-center",children:[e.jsx(se,{className:"h-8 w-8 mb-2 text-muted-foreground/40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("publishing.insights.trends.noData")})]})})]}),e.jsxs(B,{children:[e.jsxs(K,{className:"pb-2",children:[e.jsx(Y,{className:"text-sm font-semibold",children:c("publishing.insights.charts.reachImpressions")}),e.jsx(Q,{className:"text-xs",children:c("publishing.insights.subtitle",{days:g})})]}),e.jsx(U,{children:a?e.jsx(W,{className:"h-48 w-full"}):D.length>0?e.jsx(je,{width:"100%",height:180,children:e.jsxs(ze,{data:H,margin:{top:4,right:4,left:-20,bottom:0},children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"gradReach",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#ec4899",stopOpacity:.3}),e.jsx("stop",{offset:"95%",stopColor:"#ec4899",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"gradImpressions",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:"#3b82f6",stopOpacity:.2}),e.jsx("stop",{offset:"95%",stopColor:"#3b82f6",stopOpacity:0})]})]}),e.jsx(we,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",strokeOpacity:.5}),e.jsx(ye,{dataKey:"date",tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,interval:"preserveStartEnd"}),e.jsx(Oe,{tick:{fontSize:10,fill:"hsl(var(--muted-foreground))"},tickLine:!1,axisLine:!1,tickFormatter:m=>m>=1e3?`${(m/1e3).toFixed(0)}K`:m}),e.jsx(Ne,{content:e.jsx(Ve,{})}),e.jsx(le,{type:"monotone",dataKey:`${R} (${T})`,stroke:"#ec4899",strokeWidth:1,strokeDasharray:"4 4",strokeOpacity:.4,fill:"none",dot:!1}),e.jsx(le,{type:"monotone",dataKey:R,stroke:"#ec4899",strokeWidth:2,fill:"url(#gradReach)",dot:!1}),e.jsx(le,{type:"monotone",dataKey:_,stroke:"#3b82f6",strokeWidth:2,fill:"url(#gradImpressions)",dot:!1})]})}):e.jsxs("div",{className:"h-48 flex flex-col items-center justify-center text-center",children:[e.jsx(se,{className:"h-8 w-8 mb-2 text-muted-foreground/40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("publishing.insights.trends.noData")})]})})]})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-1.5",children:[c("publishing.insights.topPosts.title"),e.jsx(Ke,{children:e.jsxs(Ge,{children:[e.jsx(qe,{asChild:!0,children:e.jsx(se,{className:"h-3.5 w-3.5 text-muted-foreground/60 cursor-help"})}),e.jsx(Ye,{side:"top",className:"max-w-[260px] text-xs",children:c("publishing.insights.topPosts.organicOnly")})]})})]}),e.jsxs(Q,{className:"text-xs",children:[c("publishing.insights.topPosts.avgEngagement"),": ",(v==null?void 0:v.averageEngagementRate)??0,"%",((v==null?void 0:v.totalPosts)??0)>0&&` · ${c("publishing.insights.topPosts.postsAnalyzed",{count:v.totalPosts})}`]})]}),e.jsx(U,{className:"space-y-4",children:a?e.jsx(e.Fragment,{children:[1,2,3].map(m=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx(W,{className:"w-14 h-14 rounded-lg flex-shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(W,{className:"h-3 w-24"}),e.jsx(W,{className:"h-3 w-full"}),e.jsx(W,{className:"h-3 w-32"})]})]},m))}):v!=null&&v.topPosts&&v.topPosts.length>0?v.topPosts.slice(0,5).map((m,L)=>e.jsx(Xt,{post:m,rank:L+1},m.mediaId)):e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(se,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground
16/40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("publishing.insights.topPosts.noPosts")})]})})]}),e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsx(Y,{className:"text-sm font-semibold",children:c("publishing.insights.demographics.title")}),e.jsx(Q,{className:"text-xs",children:c("publishing.insights.demographics.subtitle")})]}),e.jsx(U,{children:a?e.jsx("div",{className:"space-y-4",children:[1,2,3,4].map(m=>e.jsx(W,{className:"h-6 w-full"},m))}):e.jsxs("div",{className:"space-y-6",children:[(N==null?void 0:N.ageDistribution)&&N.ageDistribution.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold mb-2",children:c("publishing.insights.demographics.ageRange")}),e.jsx("div",{className:"space-y-2",children:N.ageDistribution.slice(0,4).map(m=>e.jsx(xe,{label:m.value,percentage:m.percentage},m.value))})]}),(N==null?void 0:N.genderDistribution)&&N.genderDistribution.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold mb-2",children:c("publishing.insights.demographics.gender")}),e.jsx("div",{className:"space-y-2",children:N.genderDistribution.map(m=>e.jsx(xe,{label:m.value==="F"?c("publishing.insights.demographics.female"):m.value==="M"?c("publishing.insights.demographics.male"):m.value,percentage:m.percentage},m.value))})]}),(N==null?void 0:N.topCities)&&N.topCities.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold mb-2",children:c("publishing.insights.demographics.topCities")}),e.jsx("div",{className:"space-y-2",children:N.topCities.slice(0,5).map(m=>e.jsx(xe,{label:m.value,percentage:m.percentage},m.value))})]}),(N==null?void 0:N.topCountries)&&N.topCountries.length>0&&e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold mb-2",children:c("publishing.insights.demographics.topCountries")}),e.jsx("div",{className:"space-y-2",children:N.topCountries.slice(0,5).map(m=>e.jsx(xe,{label:m.value,percentage:m.percentage},m.value))})]}),!((w=N==null?void 0:N.ageDistribution)!=null&&w.length)&&!((k=N==null?void 0:N.genderDistribution)!=null&&k.length)&&!((F=N==null?void 0:N.topCities)!=null&&F.length)&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(se,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("publishing.insights.demographics.noData")}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:c("publishing.insights.demographics.noDataDesc")})]})]})})]})]}),e.jsx(Wt,{mediaInsights:n,loading:a}),e.jsx(Kt,{mediaInsights:n,mediaSnapshots:r,loading:a}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(B,{className:Z(!j&&"overflow-hidden"),children:[e.jsx(K,{className:"pb-3",children:e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[e.jsx(Se,{className:"h-4 w-4 text-amber-500"}),c("publishing.insights.bestTime.title"),!j&&e.jsx(os,{})]})}),e.jsx(U,{className:Z(!j&&"relative"),children:j?a?e.jsxs("div",{className:"space-y-3",children:[e.jsx(W,{className:"h-6 w-full"}),e.jsx(W,{className:"h-6 w-3/4"})]}):v!=null&&v.bestPostingTime||v!=null&&v.bestPostingDay?e.jsxs("div",{className:"space-y-3",children:[v.bestPostingDay&&e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/40",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:c("publishing.insights.bestTime.bestDay")}),e.jsx("span",{className:"text-sm font-bold text-foreground",children:c(`publishing.insights.bestTime.days.${v.bestPostingDay}`,{defaultValue:v.bestPostingDay})})]}),v.bestPostingTime&&e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/40",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:c("publishing.insights.bestTime.bestHour")}),e.jsx("span",{className:"text-sm font-bold text-foreground",children:v.bestPostingTime})]})]}):e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(se,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("publishing.insights.bestTime.notEnoughData")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"blur-sm pointer-events-none select-none space-y-3","aria-hidden":!0,
16children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/40",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:c("publishing.insights.bestTime.bestDay")}),e.jsx("div",{className:"h-4 w-24 rounded bg-muted"})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/40",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:c("publishing.insights.bestTime.bestHour")}),e.jsx("div",{className:"h-4 w-14 rounded bg-muted"})]})]}),e.jsx(cs,{})]})})]}),e.jsxs(B,{children:[e.jsx(K,{className:"pb-3",children:e.jsx(Y,{className:"text-sm font-semibold",children:c("publishing.insights.contentPerformance.title")})}),e.jsx(U,{children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(m=>e.jsx(W,{className:"h-8 w-full"},m))}):v!=null&&v.contentTypeBreakdown&&v.contentTypeBreakdown.length>0?e.jsxs(Ps,{children:[e.jsx(_s,{children:e.jsxs(Le,{children:[e.jsx(de,{className:"text-xs h-8",children:c("publishing.insights.contentPerformance.type")}),e.jsx(de,{className:"text-xs h-8 text-right",children:c("publishing.insights.contentPerformance.posts")}),e.jsx(de,{className:"text-xs h-8 text-right",children:c("publishing.insights.contentPerformance.avgReach")}),e.jsx(de,{className:"text-xs h-8 text-right",children:c("publishing.insights.contentPerformance.avgEngagement")})]})}),e.jsx(As,{children:v.contentTypeBreakdown.map(m=>e.jsxs(Le,{children:[e.jsx(me,{className:"text-xs font-medium py-2",children:c(`publishing.insights.mediaTypes.${m.mediaType}`,{defaultValue:m.mediaType})}),e.jsx(me,{className:"text-xs text-right py-2",children:m.count}),e.jsx(me,{className:"text-xs text-right py-2",children:m.avgReach>0?Xe(m.avgReach,"en"):"â"}),e.jsx(me,{className:"text-xs text-right py-2",children:m.avgReach>0?`${m.avgEngagement}%`:"â"})]},m.mediaType))})]}):e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(se,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/40"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c("publishing.insights.topPosts.noPosts")})]})})]})]}),A&&e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(Gt,{contentTypeBreakdown:v==null?void 0:v.contentTypeBreakdown,loading:a}),e.jsx(Yt,{mediaInsights:n,loading:a})]}),e.jsx(ei,{mediaInsights:n,loading:a,isSubscribed:j})]})}function ei({mediaInsights:s,loading:i,isSubscribed:n}){const{t:r}=O(),t=x.useMemo(()=>{if(!n)return null;const o=Array.from({length:7},()=>Array(24).fill(0)),g=Array.from({length:7},()=>Array(24).fill(0)),p=s.filter(b=>b.publishedAt&&b.reach>0);if(p.length<5)return null;for(const b of p){const $=new Date(b.publishedAt),y=$.getDay(),E=$.getHours();o[y][E]+=b.engagementRate,g[y][E]++}for(let b=0;b<7;b++)for(let $=0;$<24;$++)g[b][$]>0&&(o[b][$]=o[b][$]/g[b][$]);let j=0;for(const b of o)for(const $ of b)$>j&&(j=$);return{matrix:o,max:j}},[s,n]),a=["sun","mon","tue","wed","thu","fri","sat"],h=[1,2,3,4,5,6,0],l=[6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23];return i?e.jsxs(B,{children:[e.jsx(K,{className:"pb-3",children:e.jsx(Y,{className:"text-sm font-semibold",children:r("publishing.insights.heatmap.title")})}),e.jsx(U,{children:e.jsx(W,{className:"h-48 w-full"})})]}):n?t?e.jsxs(B,{children:[e.jsxs(K,{className:"pb-3",children:[e.jsx(Y,{className:"text-sm font-semibold",children:r("publishing.insights.heatmap.title")}),e.jsx(Q,{className:"text-xs",children:r("publishing.insights.heatmap.subtitle")})]}),e.jsx(U,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsx(Ke,{children:e.jsxs("div",{className:"min-w-[600px]",children:[e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-10 flex-shrink-0"}),l.map(o=>e.jsxs("div",{className:"flex-1 text-center text-[10px] text-muted-foreground pb-1",children:[o,"h"]},o))]}),h.map(o=>e.jsxs("div",{className:"flex items-center gap-0.5 mb-0.5",children:[e.jsx("div",{className:"w-10 flex-shrink-0 text-[10px] text-muted-foreground text-right pr-2",children:r(`publishing.insights.heatmap.dayNames.${a[o]}`)}),l.map(g=>{const p=t.matrix[o][g],j=t.max>0?p/t.max:0;return e.jsxs(Ge,{children:[e.jsx(qe,{asChild:!0,children:e.jsx("div",{className:"flex-1 h-6 rounded-sm cursor-pointer transition-colors",style:{backgroundColor:j>0?`rgba(139, 92, 246, ${.1+j*.8})`:"hsl(var(--muted))"}})}),e.jsxs(Ye,{className:"text-xs",children:[r(`publishing.insights.heatmap.dayNames.${a[o]}`)," ",g,":00 â ",p.toFixed(1),"%"]})]},g)})]},o))]})})})})]}):null:e.jsxs(B,{className:"overflow-hidden",children:[e.jsxs(K,{className:"pb-3",children:[e.jsxs(Y,{className:"text-sm font-semibold flex items-center gap-2",children:[r("publishing.insights.heatmap.title"),e.jsx(os,{})]}),e.jsx(Q,{className:"text-xs",children:r("publishing.insights.heatmap.subtitle")})]}),e.jsxs(U,{className:"relative",children:[e.jsx("div",{className:"blur-sm pointer-events-none select-none space-y-1","aria-hidden":!0,
16children:Array.from({length:7}).map((o,g)=>e.jsx("div",{className:"flex gap-1",children:Array.from({length:18}).map((p,j)=>{const b=((g+1)*5+(j+1)*3)%11/11;return e.jsx("div",{className:"h-6 flex-1 rounded-sm",style:{backgroundColor:`rgba(139, 92, 246, ${.12+b*.7})`}},j)})},g))}),e.jsx(cs,{})]})]})}const ds=["carousel","post","story","story_sequence"];function ms(s){const i=s.content_type,n=s.idea,r=s.title,t=s.caption_hint,a=s.image_description;return typeof i!="string"||!ds.includes(i)||typeof n!="string"||n.trim().length===0||typeof r!="string"||r.trim().length===0||t!==void 0&&typeof t!="string"||a!==void 0&&typeof a!="string"?null:{content_type:i,idea:n.trim(),title:r.trim(),...typeof t=="string"&&t.trim().length>0?{caption_hint:t.trim()}:{},...typeof a=="string"&&a.trim().length>0?{image_description:a.trim()}:{}}}function si(s){const i=s.recommended_title,n=s.recommended_angle,r=s.content_type_hint,t=s.why_recommended;return typeof i!="string"||i.trim().length===0||typeof n!="string"||n.trim().length===0||r!==void 0&&(typeof r!="string"||!ds.includes(r))||t!==void 0&&typeof t!="string"?null:{recommended_title:i.trim(),recommended_angle:n.trim(),...typeof r=="string"?{content_type_hint:r}:{},...typeof t=="string"&&t.trim().length>0?{why_recommended:t.trim()}:{}}}function ti(){const{i18n:s}=O(),[i,n]=x.useState([]),[r,t]=x.useState(!1),[a,h]=x.useState(!1),[l,o]=x.useState(null),g=x.useRef(null),p=x.useRef(null),j=x.useCallback((C,c)=>{n(R=>R.map(_=>{if(_.id!==C)return _;const S=_.toolCalls||[];return S.some(I=>I.name===c.name&&JSON.stringify(I.args)===JSON.stringify(c.args))?_:{..._,toolCalls:[...S,c]}}))},[]),b=x.useCallback(()=>{var C;(C=p.current)==null||C.abort(),p.current=null,g.current=null,n([]),o(null),t(!1)},[]),$=x.useCallback(()=>{var C;(C=p.current)==null||C.abort(),p.current=null,t(!1)},[]),y=x.useCallback(async({profileId:C,message:c,periodDays:R=30})=>{var v,N;if(!C)throw new Error("profileId is required");const _=c.trim();if(!_)return;o(null),t(!0);const S={id:crypto.randomUUID(),role:"user",content:_,ts:new Date().toISOString()},D=crypto.randomUUID(),I={id:D,role:"assistant",content:"",ts:new Date().toISOString()};n(u=>[...u,S,I]);const T=u=>{n(A=>A.map(w=>w.id===D?{...w,content:w.content+u}:w))},H=u=>{n(A=>A.map(w=>w.id===D?{...w,toolCalls:[...w.toolCalls||[],u]}:w))},{data:G}=await ve.auth.getSession(),V=(v=G.session)==null?void 0:v.access_token;if(!V){t(!1),o({code:"unauthorized",message:"Not authenticated"});return}const f=new AbortController;p.current=f;try{const u=(N=s.language)!=null&&N.startsWith("pt")?"pt":"en",A=await fetch(`${Re}/functions/v1/insights-chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${V}`},signal:f.signal,body:JSON.stringify({conversation_id:g.current,instagram_profile_id:C,message:_,language:u,period_days:R})});if(!A.ok){let m={};try{m=await A.json()}catch{}A.status===429&&m.error==="daily_limit_reached"?o({code:"daily_limit",message:"daily_limit_reached"}):A.status===403?o({code:"paywall",message:m.error||"Subscription required"}):A.status===401?o({code:"unauthorized",message:"Unauthorized"}):o({code:"unknown",message:m.error||`HTTP ${A.status}`}),n(L=>L.filter(M=>M.id!==D)),t(!1);return}if(!A.body){o({code:"network",message:"No response body"}),t(!1);return}const w=A.body.getReader(),k=new TextDecoder;let F="";for(;;){const{value:m,done:L}=await w.read();if(L)break;F+=k.decode(m,{stream:!0});const M=F.split(` 17 18`);F=M.pop()||"";for(const d of M){const P=d.trim();if(!P.startsWith("data:"))continue;const J=P.slice(5).trim();if(J)try{const z=JSON.parse(J);z.type==="text"&&typeof z.content=="string"?T(z.content):z.type==="tool"&&z.name?H({name:z.name,args:z.args||{}}):z.type==="done"?z.conversation_id&&(g.current=z.conversation_id):z.type==="error"&&o({code:"unknown",message:z.message||"stream error"})}catch{}}}}catch(u){if((u==null?void 0:u.name)==="AbortError"){t(!1);return}o({code:"network",message:u instanceof Error?u.message:"Network error"}),n(A=>A.filter(w=>w.id!==D||w.content.length>0))}finally{t(!1),p.current=null}},[s.language]),E=x.useCallback(async({profileId:C,assistantMessageId:c,periodDays:R=30})=>{var D,I;if(!C)throw new Error("profileId is required");if(!c)throw new Error("assistantMessageId is required");if(!g.current)return o({code:"unknown",message:"Conversation not ready"}),null;o(null),h(!0);const{data:_}=await ve.auth.getSession(),S=(D=_.session)==null?void 0:D.access_token;if(!S)return h(!1),o({code:"unauthorized",message:"Not authenticated"}),null;try{const T=(I=s.language)!=null&&I.startsWith("pt")?"pt":"en",H=await fetch(`${Re}/functions/v1/insights-chat`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${S}`},body:JSON.stringify({action:"generate_suggest_post",conversation_id:g.current,instagram_profile_id:C,language:T,period_days:R})});let G={};try{G=await H.json()}catch{}if(!H.ok)return H.status===403?o({code:"paywall",message:G.error||"Subscription required"}):H.status===401?o({code:"unauthorized",message:G.error||"Unauthorized"}):o({code:"unknown",message:G.error||`HTTP ${H.status}`}),null;
18const V=ms(G.suggest_post||{});return V?(j(c,{name:"suggest_post",args:V}),V):(o({code:"unknown",message:"Invalid suggest_post payload"}),null)}catch(T){return o({code:"network",message:T instanceof Error?T.message:"Network error"}),null}finally{h(!1)}},[j,s.language]);return{messages:i,isStreaming:r,isGeneratingSuggestion:a,error:l,sendMessage:y,generateSuggestPost:E,reset:b,stop:$}}function ii({args:s,onClick:i}){const{t:n}=O(),r=s.content_type,t=s.idea,a=s.title,h=s.caption_hint,l=s.image_description,o=n(`publishing.insights.chat.contentType.${r}`);return e.jsxs("div",{className:"mt-3 rounded-xl border border-violet-300/60 bg-gradient-to-br from-violet-50 to-fuchsia-50 p-3 shadow-sm dark:border-violet-700/60 dark:from-violet-950/60 dark:to-fuchsia-950/40",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-violet-700 dark:text-violet-300",children:[e.jsx(Nt,{className:"h-3 w-3"}),n("publishing.insights.chat.suggestPost.label")]}),e.jsx("div",{className:"mt-1.5 text-[11px] font-medium text-violet-900 dark:text-violet-200",children:o}),a&&e.jsx("p",{className:"mt-2 text-sm font-semibold text-slate-900 dark:text-slate-100",children:a}),e.jsx("p",{className:"mt-1.5 text-sm text-slate-800 dark:text-slate-200",children:t}),h&&e.jsx("p",{className:"mt-2 rounded-md bg-white/80 px-2.5 py-2 text-xs italic text-slate-700 dark:bg-slate-900/60 dark:text-slate-300",children:h}),l&&e.jsxs("p",{className:"mt-2 rounded-md border border-violet-200/60 bg-white/60 px-2.5 py-2 text-xs text-slate-700 dark:border-violet-800/60 dark:bg-slate-900/40 dark:text-slate-300",children:[e.jsxs("span",{className:"font-semibold text-violet-700 dark:text-violet-300",children:[n("publishing.insights.chat.suggestPost.image"),":"]})," ",l]}),e.jsxs(q,{size:"sm",className:"mt-3 w-full gap-1.5 bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white hover:from-violet-700 hover:to-fuchsia-700",onClick:()=>i(s),children:[e.jsx(ee,{className:"h-3.5 w-3.5"}),n("publishing.insights.chat.suggestPost.create")]})]})}function ni(){const{t:s}=O(),{openPricingModal:i}=_e();return e.jsxs("div",{className:"mt-3 rounded-xl border border-amber-300/60 bg-gradient-to-br from-amber-50 to-orange-50 p-3 shadow-sm dark:border-amber-700/60 dark:from-amber-950/40 dark:to-orange-950/30",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300",children:[e.jsx(Ae,{className:"h-3 w-3"}),s("publishing.insights.chat.paywall.label")]}),e.jsx("p",{className:"mt-2 text-sm font-semibold text-slate-900 dark:text-slate-100",children:s("publishing.insights.chat.paywall.title")}),e.jsx("p",{className:"mt-1.5 text-sm text-slate-800 dark:text-slate-200",children:s("publishing.insights.chat.paywall.description")}),e.jsxs(q,{size:"sm",className:"mt-3 w-full gap-1.5 bg-gradient-to-r from-amber-500 to-orange-500 text-white hover:from-amber-600 hover:to-orange-600",onClick:()=>i(),children:[e.jsx(ee,{className:"h-3.5 w-3.5"}),s("publishing.insights.chat.paywall.cta")]})]})}function ai({message:s,isStreaming:i}){const n=s.role==="user",r=(s.toolCalls||[]).filter(a=>a.name==="open_paywall"),t=!n&&i&&s.content.length===0&&r.length===0;return!n&&!t&&s.content.length===0&&r.length===0?null:e.jsx("div",{className:Z("flex",n?"justify-end":"justify-start"),children:e.jsx("div",{className:Z("max-w-[85%] rounded-2xl px-3.5 py-2.5 text-sm leading-relaxed",n?"bg-violet-600 text-white":"bg-muted text-foreground"),children:t?e.jsx(ie,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"}):e.jsxs(e.Fragment,{children:[s.content&&e.jsx("div",{className:Z("prose prose-sm max-w-none","dark:prose-invert","[&_p]:my-1 [&_ul]:my-1 [&_ol]:my-1 [&_li]:my-0","[&_p]:text-foreground [&_li]:text-foreground","[&_h1]:text-foreground [&_h2]:text-foreground [&_h3]:text-foreground [&_h4]:text-foreground [&_h5]:text-foreground [&_h6]:text-foreground","[&_h1]:font-semibold [&_h2]:font-semibold [&_h3]:font-semibold [&_h4]:font-semibold [&_h5]:font-semibold [&_h6]:font-semibold","[&_strong]:text-foreground [&_strong]:font-semibold","[&_em]:text-foreground","[&_a]:text-foreground [&_a]:underline","[&_hr]:border-border/70","[&_code]:text-foreground [&_code]:bg-background/60 [&_code]:px-1 [&_code]:py-0.5 [&_code]:rounded",n&&"[&_p]:text-white [&_li]:text-white [&_h1]:text-white [&_h2]:text-white [&_h3]:text-white [&_h4]:text-white [&_h5]:text-white [&_h6]:text-white [&_strong]:text-white [&_em]:text-white [&_a]:text-white [&_code]:text-white [&_code]:bg-white/10"),children:e.jsx(jt,{children:s.content})}),r.map((a,h)=>e.jsx(ni,{},`${s.id}-pw-${h}`))]})})})}function ri({offer:s,suggestion:i,isOpen:n,isGenerating:r,onReveal:t,onClose:a,onSuggestPostClick:h}){const{t:l}=O(),o=!!i,g=s!=null&&s.content_type_hint?l(`publishing.insights.chat.contentType.${s.content_type_hint}`):null,p=l(r?"publishing.insights.chat.suggestPost.generatingCreative":o?"publishing.insights.chat.suggestPost.view":"publishing.insights.chat.suggestPost.generateCreative");return e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx("div",{className:"w-full max-w-[85%]",children:n&&i?e.jsx("div",{className:"rounded-xl border border-border/70 bg-card/70 shadow-sm",children:e.jsxs("div",{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground",children:l("publishing.insights.chat.suggestPost.followUpTitle")}),s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:s.recommended_title}),g&&e.jsx("span",{className:"rounded-full bg-violet-100 px-2 py-0.5 text-[10px] font-medium text-violet-700 dark:bg-violet-950/60 dark:text-violet-300",children:g})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:s.recommended_angle})]}):e.jsx("p",{className:"mt-1 text-sm font-medium text-foreground",children:l("publishing.insights.chat.suggestPost.ready")})]}),e.jsx(q,{variant:"ghost",size:"sm",className:"h-7 px-2 text-[11px] text-muted-foreground",onClick:a,children:l("common.close")})]}),(s==null?void 0:s.why_recommended)&&e.jsx("p",{className:"mt-2 rounded-md bg-muted/60 px-2.5 py-2 text-xs text-muted-foreground",children:s.why_recommended}),e.jsx(ii,{args:i,onClick:h})]})}):e.jsxs("div",{className:"border-t border-border/70 pt-3",children:[e.jsx("p",{className:"px-1 text-[11px] font-medium text-muted-foreground",children:l("publishing.insights.chat.suggestPost.followUpActionTitle")}),e.jsxs("button",{type:"button",onClick:t,disabled:r,className:Z("mt-1 flex w-full items-center gap-3 rounded-xl px-1 py-2.5 text-left transition-colors","hover:bg-muted/40","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-500 focus-visible:ring-inset","disabled:pointer-events-none disabled:opacity-70"),children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-full border border-violet-200/80 bg-violet-50/80 text-violet-700 dark:border-violet-900 dark:bg-violet-950/40 dark:text-violet-200",children:r?e.jsx(ie,{className:"h-4 w-4 animate-spin"}):e.jsx(ee,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:p}),s?e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 truncate font-medium text-foreground
18/90",children:s.recommended_title}),g&&e.jsx("span",{className:"rounded-full bg-violet-100 px-2 py-0.5 text-[10px] font-medium text-violet-700 dark:bg-violet-950/60 dark:text-violet-300",children:g})]}):e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:l("publishing.insights.chat.suggestPost.ready")})]}),!r&&e.jsx(yt,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})]})})})}function li(s){for(let i=s.length-1;i>=0;i-=1){const n=s[i].toolCalls||[];let r=null,t=null,a=!1;for(let h=n.length-1;h>=0;h-=1){const l=n[h];!r&&l.name==="offer_generate_creative"&&(r=si(l.args)),!t&&l.name==="suggest_post"&&(t=ms(l.args)),l.name==="offer_generate_creative"&&(a=!0)}if(t||a)return{messageId:s[i].id,offer:r,suggestion:t,hasOffer:a}}return null}function oi({messages:s,isStreaming:i,activeCreativeOffer:n,activeSuggestion:r,activeCreativeMessageId:t,isSuggestionOpen:a,isGeneratingSuggestion:h,onRevealSuggestion:l,onCloseSuggestion:o,onSuggestPostClick:g}){return e.jsx(e.Fragment,{children:s.map((p,j)=>{const b=!i&&!!t&&t===p.id;return e.jsxs("div",{children:[e.jsx(ai,{message:p,isStreaming:i&&j===s.length-1&&p.role==="assistant"}),b&&e.jsx(ri,{offer:n,suggestion:r,isOpen:a,isGenerating:h,onReveal:l,onClose:o,onSuggestPostClick:g})]},p.id)})})}const ci=x.memo(oi),di=3e3;function mi({open:s,onOpenChange:i,profileId:n,periodDays:r}){const{t}=O(),a=Pe(),{messages:h,isStreaming:l,isGeneratingSuggestion:o,error:g,sendMessage:p,generateSuggestPost:j,reset:b,stop:$}=ti(),[y,E]=x.useState(""),[C,c]=x.useState(!1),R=x.useRef(0),_=x.useRef(null),S=li(h),D=(S==null?void 0:S.offer)??null,I=(S==null?void 0:S.suggestion)??null,T=(S==null?void 0:S.messageId)??null,H=x.useCallback(k=>{_.current&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{var F;(F=_.current)==null||F.scrollIntoView({behavior:k,block:"end"})})})},[]);x.useEffect(()=>{H(l||o?"auto":"smooth")},[o,l,C,h,H]),x.useEffect(()=>{c(!1)},[T]);const G=!!n&&!l&&y.trim().length>0,V=x.useCallback(async k=>{if(!n)return;const F=(k??y).trim();if(!F)return;const m=Date.now();m-R.current<di||(R.current=m,k||E(""),await p({profileId:n,message:F,periodDays:r}))},[n,y,p,r]),f=x.useCallback(k=>{k.key==="Enter"&&!k.shiftKey&&(k.preventDefault(),V())},[V]),v=x.useCallback(k=>{const F=k.caption_hint?`${k.idea} 19 20${k.caption_hint}`:k.idea;i(!1),a(`/dashboard/create/${k.content_type}`,{state:{initialBriefing:F,initialTitle:k.title,initialImageDescription:k.image_description??""}})},[a,i]),N=x.useCallback(async()=>{if(!n||!S)return;if(S.suggestion){c(!0);return}await j({profileId:n,assistantMessageId:S.messageId,periodDays:r})&&c(!0)},[S,j,r,n]),u=x.useCallback(k=>{V(k)},[V]),A=[t("publishing.insights.chat.suggestions.engagement"),t("publishing.insights.chat.suggestions.bestPost"),t("publishing.insights.chat.suggestions.ideas"),t("publishing.insights.chat.suggestions.grow")],w=()=>
20{if(!g)return null;let k=t("publishing.insights.chat.error.generic");return g.code==="daily_limit"?k=t("publishing.insights.chat.error.dailyLimit"):g.code==="paywall"?k=t("publishing.insights.chat.error.paywall"):g.code==="unauthorized"&&(k=t("publishing.insights.chat.error.unauthorized")),e.jsxs("div",{className:"mx-4 mb-2 flex items-start gap-2 rounded-lg border border-destructive/20 bg-destructive/5 px-3 py-2 text-xs text-destructive",children:[e.jsx(pe,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"flex-1",children:k})]})};return e.jsx(ut,{open:s,onOpenChange:i,children:e.jsxs(pt,{side:"right",className:"flex w-full flex-col gap-0 p-0 sm:max-w-md",children:[e.jsx(ft,{className:"border-b bg-gradient-to-r from-violet-600/10 via-fuchsia-600/5 to-transparent px-4 py-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-violet-500 to-fuchsia-500 shadow-sm",children:e.jsx(ee,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{className:"min-w-0 flex-1 text-left",children:[e.jsx(bt,{className:"text-sm font-semibold leading-none",children:t("publishing.insights.chat.title")}),e.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground",children:t("publishing.insights.chat.subtitle")})]}),h.length>0&&e.jsxs(q,{variant:"ghost",size:"sm",className:"h-7 gap-1 text-[11px] text-muted-foreground",onClick:b,disabled:l,children:[e.jsx(wt,{className:"h-3 w-3"}),t("publishing.insights.chat.reset")]})]})}),e.jsx(vt,{className:"flex-1",children:e.jsxs("div",{className:"flex flex-col gap-4 px-4 py-4",children:[h.length===0&&!l&&e.jsxs("div",{className:"flex flex-col gap-3 pt-2",children:[e.jsx("div",{className:"rounded-xl bg-muted/50 p-4 text-sm",children:e.jsx("p",{className:"text-foreground/90",children:t("publishing.insights.chat.greeting")})}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:t("publishing.insights.chat.tryAsking")}),A.map((k,F)=>e.jsx("button",{type:"button",onClick:()=>u(k),disabled:!n||l,className:Z("rounded-lg border border-border bg-card px-3 py-2 text-left text-xs text-foreground transition-colors","hover:border-violet-400 hover:bg-violet-50 hover:text-violet-900","dark:hover:border-violet-500 dark:hover:bg-violet-950/40 dark:hover:text-violet-100","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-violet-500","active:bg-violet-100 dark:active:bg-violet-900/60","disabled:pointer-events-none disabled:opacity-50"),children:k},F))]})]}),e.jsx(ci,{messages:h,isStreaming:l,activeCreativeOffer:D,activeSuggestion:I,activeCreativeMessageId:T,isSuggestionOpen:C,isGeneratingSuggestion:o,onRevealSuggestion:N,onCloseSuggestion:()=>c(!1),onSuggestPostClick:v}),e.jsx("div",{ref:_})]})}),e.jsxs("div",{className:"border-t bg-background",children:[w(),e.jsx("div",{className:"p-3",children:e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsx(vs,{value:y,onChange:k=>E(k.target.value),onKeyDown:f,placeholder:t("publishing.insights.chat.placeholder"),disabled:!n||l,className:Z("max-h-32 min-h-[44px] flex-1 resize-none text-sm"),rows:1}),l?e.jsx(q,{variant:"outline",size:"icon",onClick:$,className:"h-11 w-11 shrink-0",children:e.jsx(ie,{className:"h-4 w-4 animate-spin"})}):e.jsx(q,{size:"icon",onClick:()=>V(),disabled:!G,className:"h-11 w-11 shrink-0 bg-violet-600 hover:bg-violet-700",children:e.jsx(js,{className:"h-4 w-4"})})]})}),e.jsx("p",{className:"mt-1.5 text-[10px] text-muted-foreground",children:t("publishing.insights.chat.disclaimer")})]})]})})}function X(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function ae(s,i=!1){if(s==null)return"â";const n=s>=0?"+":"";return i?`${n}${s.toLocaleString()}`:`${n}${s}%`}function hi(s){return s==null?"#6b7280":s>=0?"#16a34a":"#dc2626"}function te(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}const gi={sunday:"Domingo",monday:"Segunda",tuesday:"Terça",wednesday:"Quarta",thursday:"Quinta",friday:"Sexta",saturday:"Sábado"},xi={sunday:"Sunday",monday:"Monday",tuesday:"Tuesday",wednesday:"Wednesday",thursday:"Thursday",friday:"Friday",saturday:"Saturday"},ui={IMAGE:"Imagem",VIDEO:"VÃdeo",CAROUSEL_ALBUM:"Carrossel",REELS:"Reels",STORY:"Story"},pi={IMAGE:"Image",VIDEO:"Video",CAROUSEL_ALBUM:"Carousel",REELS:"Reels",STORY:"Story"};function fi({overview:s,username:i,selectedPeriod:n,language:r="pt"}){var A,w,k,F,m,L,M;const{summary:t,mediaPerformance:a,demographics:h}=s,l=r.startsWith("pt"),o=l?gi:xi,g=l?ui:pi,p=new Date().toLocaleDateString(l?"pt-BR":"en-US",{day:"2-digit",month:"long",year:"numeric"}),j=new Date(t.periodStart).toLocaleDateString(l?"pt-BR":"en-US",{day:"2-digit",month:"short",year:"numeric"}),b=new Date(t.periodEnd).toLocaleDateString(l?"pt-BR":"en-US",{day:"2-digit",month:"short",year:"numeric"}),y=[{label:l?"Seguidores":"Followers",value:X(t.followerCount),change:ae(t.followerChange,!0),changeVal:t.followerChange},{label:l?"Alcance":"Reach",value:X(t.reach),change:ae(t.reachChange),changeVal:t.reachChange},{label:l?"Impressões":"Impressions",value:X(t.impressions),change:ae(t.impressionsChange),changeVal:t.impressionsChange},{label:l?"Interações":"Interactions",value:X(t.totalInteractions),change:ae(t.interactionsChange),changeVal:t.interactionsChange},{label:l?"Contas que Interagiram":"Accounts Engaged",value:t.accountsEngaged===null?"â":X(t.accountsEngaged),change:ae(t.accountsEngagedChange),changeVal:t.accountsEngagedChange},{label:l?"Cliques no Link":"Website Clicks",value:X(t.websiteClicks),change:ae(t.websiteClicksChange),changeVal:t.websiteClicksChange}].map(d=>` 21 <div class="kpi-card"> 22 <div class="kpi-label">${d.label}</div> 23 <div class="kpi-value">${d.value}</div> 24 <div class="kpi-change" style="color:${hi(d.changeVal)}">${d.change}</div> 25 </div> 26 `).join(""),E=a.totalReach>0?(a.totalImpressions/a.totalReach).toFixed(2):"â",C=` 27 <div class="section"> 28 <div class="section-title">${l?"Visão Geral dos Posts":"Posts Overview"}</div> 29 <div class="stats-row"> 30 <div class="stat-item"> 31 <div class="stat-label">${l?"Posts Analisados":"Posts Analyzed"}</div> 32 <div class="stat-value">${a.totalPosts}</div> 33 </div> 34 <div class="stat-item"> 35 <div class="stat-label">${l?"Alcance Total":"Total Reach"}</div> 36 <div class="stat-value">${X(a.totalReach)}</div> 37 </div> 38 <div class="stat-item"> 39 <div class="stat-label">${l?"Impressões Totais":"Total Impressions"}</div> 40 <div class="stat-value">${X(a.totalImpressions)}</div> 41 </div> 42 <div class="stat-item"> 43 <div class="stat-label">${l?"Eng. Médio":"Avg Engagement"}</div> 44 <div class="stat-value">${a.averageEngagementRate.toFixed(1)}%</div> 45 </div> 46 <div class="stat-item"> 47 <div class="stat-label">${l?"Taxa de Viralidade":"Virality Ratio"}</div> 48 <div class="stat-value">${E}x</div> 49 </div> 50 </div> 51 </div>`,c=(a.topPosts||[]).map((d,P)=>{const J=d.caption?te(d.caption.substring(0,55))+(d.caption.length>55?"â¦":""):"â",z=g[d.mediaType]||d.mediaType,hs=P%2===0?"row-even":"row-odd",gs=d.publishedAt?new Date(d.publishedAt).toLocaleDateString(l?"pt-BR":"en-US",{day:"2-digit",month:"short"}):"â";return` 52 <tr class="${hs}"> 53 <td class="text-center rank">${P+1}</td> 54 <td class="text-center muted">${gs}</td> 55 <td><span class="badge">${z}</span></td> 56 <td class="text-right">${X(d.likeCount)}</td> 57 <td class="text-right">${X(d.commentsCount)}</td> 58 <td class="text-right">${X(d.savedCount)}</td> 59 <td class="text-right">${X(d.sharesCount)}</td> 60 <td class="text-right">${X(d.reach)}</td> 61 <td class="text-right">${d.reach>0?d.engagementRate.toFixed(1)+"%":"â"}</td> 62 <td class="caption-cell">${J}</td> 63 </tr>`}).join(""),R=(A=a.topPosts)!=null&&A.length?` 64 <div class="section"> 65 <div class="section-title">${l?"Top Posts do PerÃodo":"Top Posts"}</div> 66 <table> 67 <thead> 68 <tr> 69 <th class="text-center">#</th> 70 <th class="text-center">${l?"Data":"Date"}</th> 71 <th>${l?"Tipo":"Type"}</th> 72 <th class="text-right">${l?"Curtidas":"Likes"}</th> 73 <th class="text-right">
73${l?"Coments.":"Comments"}</th> 74 <th class="text-right">Saves</th> 75 <th class="text-right">Shares</th> 76 <th class="text-right">${l?"Alcance":"Reach"}</th> 77 <th class="text-right">Eng.</th> 78 <th>${l?"Legenda":"Caption"}</th> 79 </tr> 80 </thead> 81 <tbody>${c}</tbody> 82 </table> 83 </div>`:"",_=(a.contentTypeBreakdown||[]).map((d,P)=>{const J=g[d.mediaType]||d.mediaType;return` 84 <tr class="${P%2===0?"row-even":"row-odd"}"> 85 <td><span class="badge">${J}</span></td> 86 <td class="text-right">${d.count}</td> 87 <td class="text-right">${X(d.avgReach)}</td> 88 <td class="text-right">${d.avgReach>0?d.avgEngagement.toFixed(1)+"%":"â"}</td> 89 </tr>`}).join(""),S=(w=a.contentTypeBreakdown)!=null&&w.length?` 90 <div class="section"> 91 <div class="section-title">${l?"Performance por Tipo de Conteúdo":"Performance by Content Type"}</div> 92 <table> 93 <thead> 94 <tr> 95 <th>${l?"Tipo":"Type"}</th> 96 <th class="text-right">Posts</th> 97 <th class="text-right">${l?"Alcance Médio":"Avg Reach"}</th> 98 <th class="text-right">${l?"Eng. Médio":"Avg Eng."}</th> 99 </tr> 100 </thead> 101 <tbody>${_}</tbody> 102 </table> 103 </div>`:"",D=a.bestPostingTime||a.bestPostingDay?` 104 <div class="section"> 105 <div class="section-title">${l?"Melhor Horário para Postar":"Best Time to Post"}</div> 106 <div class="best-time-grid"> 107 ${a.bestPostingDay?` 108 <div class="best-time-item"> 109 <div class="best-time-label">${l?"Melhor Dia":"Best Day"}</div> 110 <div class="best-time-value">${o[a.bestPostingDay]||a.bestPostingDay}</div> 111 </div>`:""} 112 ${a.bestPostingTime?` 113 <div class="best-time-item"> 114 <div class="best-time-label">${l?"Melhor Horário":"Best Hour"}</div> 115 <div class="best-time-value">${a.bestPostingTime}</div> 116 </div>`:""} 117 <div class="best-time-item"> 118 <div class="best-time-label">${l?"Eng. Médio":"Avg Eng."}</div> 119 <div class="best-time-value">${a.averageEngagementRate.toFixed(1)}%</div> 120 </div> 121 <div class="best-time-item"> 122 <div class="best-time-label">${l?"Posts Analisados":"Posts Analyzed"}</div> 123 <div class="best-time-value">${a.totalPosts}</div> 124 </div> 125 </div> 126 </div>`:"",I=(k=h.topCountries)!=null&&k.length?` 127 <div class="section"> 128 <div class="section-title">${l?"Principais PaÃses":"Top Countries"}</div> 129 <div class="countries-grid"> 130 ${h.topCountries.slice(0,5).map(d=>` 131 <div class="country-row"> 132 <span class="country-name">${te(d.value)}</span> 133 <div class="country-bar-wrap"> 134 <div class="country-bar" style="width:${Math.max(d.percentage,2)}%"></div> 135 </div> 136 <span class="country-pct">${d.percentage.toFixed(1)}%</span> 137 </div>`).join("")} 138 </div> 139 </div>`:"",T=(F=h.topCities)!=null&&F.length?` 140 <div class="section"> 141 <div class="section-title">${l?"Principais Cidades":"Top Cities"}</div> 142 <div class="countries-grid"> 143 ${h.topCities.slice(0,5).map(d=>` 144 <div class="country-row"> 145 <span class="country-name">${te(d.value)}</span> 146 <div class="country-bar-wrap"> 147 <div class="country-bar" style="width:${Math.max(d.percentage,2)}%"></div> 148 </div> 149 <span class="country-pct">${d.percentage.toFixed(1)}%</span> 150 </div>`).join("")} 151 </div> 152 </div>`:"",H=(m=h.ageDistribution)!=null&&m.length?h.ageDistribution.sort((d,P)=>P.percentage-d.percentage).slice(0,6).map(d=>` 153 <div class="country-row"> 154 <span class="country-name">${te(d.value)}</span> 155 <div class="country-bar-wrap"> 156 <div class="country-bar" style="width:${Math.max(d.percentage,2)}%"></div> 157 </div> 158 <span class="country-pct">${d.percentage.toFixed(1)}%</span> 159 </div>`).join(""):"",G=(L=h.genderDistribution)!=null&&L.length?h.genderDistribution.map(d=>` 160 <div class="gender-item"> 161 <div class="gender-label">${l?d.value==="M"?"Masculino":d.value==="F"?"Feminino":d.value:d.value==="M"?"Male":d.value==="F"?"Female":d.value}</div> 162 <div class="gender-value">${d.percentage.toFixed(1)}%</div> 163 <div class="country-bar-wrap" style="margin-top:4px"> 164 <div class="country-bar" style="width:${Math.max(d.percentage,2)}%"></div> 165 </div> 166 </div>`).join(""):"",V=H||G?` 167 <div class="section"> 168 <div class="section-title">${l?"Audiência â Demografias":"Audience Demographics"}</div> 169 <div class="demo-grid"> 170 ${H?` 171 <div class="demo-col"> 172 <div class="demo-col-title">${l?"Faixa Etária":"Age Range"}</div> 173 <div class="countries-grid">${H}</div> 174 </div>`:""} 175 ${G?` 176 <div class="demo-col"> 177 <div class="demo-col-title">${l?"Gênero":"Gender"}</div> 178 <div class="gender-grid">${G}</div> 179 </div>`:""} 180 </div> 181 </div>`:"",f=[];if(t.reachChange!==void 0&&(t.reachChange>0?f.push(l?`ð Seu alcance cresceu <strong>${t.reachChange}%</strong> em relação ao perÃodo anterior.`:`ð Your reach grew <strong>${t.reachChange}%</strong> compared to the previous period.`):t.reachChange<0&&f.push(l?`ð Seu alcance caiu <strong>${Math.abs(t.reachChange)}%</strong> em relação ao perÃodo anterior.`:`ð Your reach dropped <strong>${Math.abs(t.reachChange)}%</strong> compared to the previous period.`)),(M=a.contentTypeBreakdown)!=null&&M.length){const d=a.contentTypeBreakdown[0];if(d.avgReach>0){const P=g[d.mediaType]||d.mediaType;f.push(l?`ð <strong>${P}</strong> é o formato com melhor engajamento médio: <strong>${d.avgEngagement.toFixed(1)}%</strong>.`:`ð <strong>${P}</strong> is your best-performing format with avg engagement of <strong>${d.avgEngagement.toFixed(1)}%</strong>.`)}}if(a.bestPostingDay&&a.bestPostingTime){const d=o[a.bestPostingDay]||a.bestPostingDay;f.push(l?`â° Melhor momento para postar: <strong>${d}</strong> à s <strong>${a.bestPostingTime}</strong>.`:`â° Best time to post: <strong>${d}</strong> at <strong>${a.bestPostingTime}</strong>.`)}if(t.followerChange!==void 0&&t.followerChange>0&&f.push(l?`ð¥ Você ganhou <strong>
181${t.followerChange.toLocaleString()}</strong> seguidores neste perÃodo.`:`ð¥ You gained <strong>${t.followerChange.toLocaleString()}</strong> followers this period.`),a.postsInPeriod>0){const d=(a.postsInPeriod/(t.daysInPeriod/7)).toFixed(1),P=a.postsInPeriodTruncated;f.push(l?P?`ð Frequência de postagem: pelo menos <strong>${d}</strong> posts por semana (com base nos ${a.totalPosts} posts mais recentes).`:`ð Frequência de postagem: <strong>${d}</strong> posts por semana.`:P?`ð Posting frequency: at least <strong>${d}</strong> posts per week (based on the ${a.totalPosts} most recent posts).`:`ð Posting frequency: <strong>${d}</strong> posts per week.`)}const v=f.length?` 182 <div class="section insights-section"> 183 <div class="section-title">${l?"Destaques Automáticos":"Key Insights"}</div> 184 <ul class="insights-list"> 185 ${f.map(d=>`<li>${d}</li>`).join("")} 186 </ul> 187 </div>`:"",N=`<!DOCTYPE html> 188<html lang="${l?"pt-BR":"en"}"> 189<head> 190 <meta charset="UTF-8" /> 191 <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 192 <title>Instagram Insights â @${te(i)}</title> 193 <link rel="preconnect" href="https://fonts.googleapis.com" /> 194 <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet" /> 195 <style> 196 *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; } 197 198 body { 199 font-family: 'Inter', Arial, Helvetica, sans-serif; 200 background: #fff; 201 color: #111827; 202 font-size: 11px; 203 line-height: 1.5; 204 -webkit-print-color-adjust: exact; 205 print-color-adjust: exact; 206 } 207 208 .page { 209 width: 210mm; 210 min-height: 297mm; 211 margin: 0 auto; 212 padding: 12mm 14mm 10mm; 213 } 214 215 /* ââ HEADER âââââââââââââââââââââââââââââââââââââ */ 216 .report-header { 217 display: flex; 218 align-items: flex-start; 219 justify-content: space-between; 220 padding-bottom: 10px; 221 border-bottom: 3px solid #7c3aed; 222 margin-bottom: 18px; 223 } 224 .header-left { display: flex; align-items: center; gap: 10px; } 225 .logo-circle { 226 width: 36px; height: 36px; border-radius: 10px; 227 background: linear-gradient(135deg, #7c3aed, #db2777); 228 display: flex; align-items: center; justify-content: center; 229 font-size: 16px; font-weight: 800; color: #fff; flex-shrink: 0; 230 } 231 .header-title { font-size: 15px; font-weight: 700; color: #111827; } 232 .header-username { font-size: 11px; color: #7c3aed; font-weight: 600; } 233 .header-right { text-align: right; } 234 .header-period { font-size: 11px; color: #374151; font-weight: 600; } 235 .header-period-label { font-size: 9.5px; color: #9ca3af; } 236 237 /* ââ SECTION ââââââââââââââââââââââââââââââââââââ */ 238 .section { margin-bottom: 20px; page-break-inside: avoid; } 239 .section-title { 240 font-size: 10.5px; font-weight: 700; text-transform: uppercase; 241 letter-spacing: 0.06em; color: #6b7280; 242 border-bottom: 1px solid #e5e7eb; 243 padding-bottom: 5px; margin-bottom: 10px; 244 } 245 246 /* ââ STATS ROW ââââââââââââââââââââââââââââââââââ */ 247 .stats-row { 248 display: flex; gap: 8px; flex-wrap: wrap; 249 } 250 .stat-item { 251 flex: 1; min-width: 80px; 252 border: 1px solid #e5e7eb; border-radius: 8px; padding: 8px 10px; 253 background: #f0fdf4; 254 } 255 .stat-label { font-size: 8.5px; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 3px; } 256 .stat-value { font-size: 15px; font-weight: 800; color: #15803d; line-height: 1.1; } 257 258 /* ââ KPI GRID âââââââââââââââââââââââââââââââââââ */ 259 .kpi-grid { 260 display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; 261 margin-bottom: 20px; 262 } 263 .kpi-card { 264 border: 1px solid #e5e7eb; border-radius: 8px; padding: 10px 12px; 265 background: #fafafa; 266 } 267 .kpi-label { font-size: 9px; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 4px; } 268 .kpi-value { font-size: 20px; font-weight: 800; color: #111827; line-height: 1.1; margin-bottom: 3px; } 269 .kpi-change { font-size: 9.5px; font-weight: 600; } 270 271 /* ââ TABLES âââââââââââââââââââââââââââââââââââââ */ 272 table { width: 100%; border-collapse: collapse; font-size: 10px; } 273 th { 274 font-size: 9px; font-weight: 700; text-transform: uppercase; 275 letter-spacing: 0.04em; color: #6b7280; 276 padding: 6px 8px; background: #f9fafb; text-align: left; 277 border-bottom: 1px solid #e5e7eb; 278 } 279 td { padding: 6px 8px; color: #374151; } 280 .row-even { background: #fff; } 281 .row-odd { background: #f9fafb; } 282 .text-right { text-align: right; } 283 .text-center { text-align: center; } 284 .rank { font-weight: 700; color: #7c3aed; } 285 .caption-cell { max-width: 120px; color: #6b7280; font-style: italic; } 286 .badge { 287 display: inline-block; 288 background: #ede9fe; color: #5b21b6; 289 font-size: 8.5px; font-weight: 600; border-radius: 4px; 290 padding: 1px 5px; text-transform: uppercase; letter-spacing: 0.04em; 291 } 292 293 /* ââ BEST TIME ââââââââââââââââââââââââââââââââââ */ 294 .best-time-grid { 295 display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; 296 } 297 .best-time-item { 298 border: 1px solid #e5e7eb; border-radius: 8px; padding: 10px 12px; 299 background: #fdf4ff; 300 } 301 .best-time-label { font-size: 9px; font-weight: 600; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 4px; } 302 .best-time-value { font-size: 16px; font-weight: 800; color: #7c3aed; } 303 304 /* ââ COUNTRIES ââââââââââââââââââââââââââââââââââ */ 305 .countries-grid { display: flex; flex-direction: column; gap: 6px; } 306 .country-row { display: flex; align-items: center; gap: 8px; } 307 .country-name { width: 80px; flex-shrink: 0; font-weight: 500; color: #374151; font-size: 10px; } 308 .country-bar-wrap { flex: 1; background: #f3f4f6; border-radius: 4px; height: 8px; overflow: hidden; } 309 .country-bar { height: 100%; background: linear-gradient(90deg, #7c3aed, #a855f7); border-radius: 4px; } 310 .country-pct { width: 36px; text-align: right; font-weight: 600; color: #7c3aed; font-size: 10px; } 311 312 /* ââ DEMOGRAPHICS ââââââââââââââââââââââââââââââââ */ 313 .demo-grid { display: flex; gap: 16px; } 314 .demo-col { flex: 1; } 315 .demo-col-title { font-size: 9px; font-weight: 700; color: #374151; text-transform: uppercase; letter-spacing: 0.04em; margin-bottom: 6px; } 316 .gender-grid { display: flex; gap: 8px; } 317 .gender-item { flex: 1; border: 1px solid #e5e7eb; border-radius: 8px; padding: 8px 10px; background: #fafafa; } 318 .gender-label { font-size: 9px; font-weight: 600; color: #6b7280; text-transform: uppercase; letter-spacing: 0.04em; } 319 .gender-value { font-size: 18px; font-weight: 800; color: #7c3aed; margin: 2px 0; } 320 321 /* ââ AUTO INSIGHTS ââââââââââââââââââââââââââââââ */ 322 .insights-section { background: #fffbeb; border: 1px solid #fde68a; border-radius: 8px; padding: 12px 14px; } 323 .insights-section .section-title { border-color: #fde68a; color: #92400e; } 324 .insights-list { list-style: none; display: flex; flex-direction: column; gap: 5px; } 325 .insights-list li { font-size: 10.5px; color: #374151; padding-left: 4px; } 326 .muted { color: #9ca3af; } 327 328 /* ââ FOOTER âââââââââââââââââââââââââââââââââââââ */ 329 .report-footer { 330 margin-top: 24px; padding-top: 10px; 331 border-top: 1px solid #e5e7eb; 332 display: flex; justify-content: space-between; align-items: center; 333 color: #9ca3af; font-size: 9px; 334 } 335 .footer-brand { font-weight: 700; color: #7c3aed; } 336 337 /* ââ PRINT RULES ââââââââââââââââââââââââââââââââ */ 338 @media print { 339 body { font-size: 11px; } 340 .page { padding: 10mm 12mm 8mm; } 341 .no-print { display: none !important; } 342 .section { page-break-inside: avoid; } 343 @page { size: A4; margin: 0; } 344 } 345 346 /* ââ PRINT BUTTON (screen only) âââââââââââââââââ */ 347 .print-bar { 348 position: fixed; top: 0; left: 0; right: 0; z-index: 100; 349 background: #7c3aed; padding: 10px 20px; 350 display: flex; align-items: center; justify-content: space-between; 351 } 352 .print-bar span { color: #fff; font-size: 12px; font-weight: 600; } 353 .btn-print { 354 background: #fff; color: #7c3aed; border: none; border-radius: 6px; 355 padding: 6px 16px; font-size: 12px; font-weight: 700; cursor: pointer; 356 } 357 .btn-print:hover { background: #ede9fe; } 358 @media print { .print-bar { display: none; } } 359 .page { margin-top: 48px; } 360 @media print { .page { margin-top: 0; } } 361 </style> 362</head> 363<body> 364 365 <!-- Print bar (visible on screen, hidden on print) --> 366 <div class="print-bar no-print"> 367 <span>Instagram Insights â @${te(i)}</span> 368 <button class="btn-print" onclick="window.print()">⬠${l?"Baixar PDF":"Save PDF"}</button> 369 </div> 370 371 <div class="page"> 372 373 <!-- Report Header --> 374 <div class="report-header"> 375 <div class="header-left"> 376 <div class="logo-circle">I</div> 377 <div> 378 <div class="header-title">Instagram Insights Report</div> 379 <div class="header-username">@${te(i)}</div> 380 </div> 381 </div> 382 <div class="header-right"> 383 <div class="header-period">${j} â ${b}</div> 384 <div class="header-period-label">${l?`Ãltimos ${t.daysInPeriod}
384 dias`:`Last ${t.daysInPeriod} days`}</div> 385 </div> 386 </div> 387 388 <!-- KPIs Section --> 389 <div class="section"> 390 <div class="section-title">${l?"Resumo do PerÃodo":"Period Summary"}</div> 391 <div class="kpi-grid">${y}</div> 392 </div> 393 394 <!-- Auto Insights --> 395 ${v} 396 397 <!-- Posts Overview --> 398 ${C} 399 400 <!-- Top Posts --> 401 ${R} 402 403 <!-- Content Type Performance --> 404 ${S} 405 406 <!-- Best Time --> 407 ${D} 408 409 <!-- Demographics --> 410 ${V} 411 412 <!-- Countries + Cities --> 413 ${I} 414 ${T} 415 416 <!-- Footer --> 417 <div class="report-footer"> 418 <div><span class="footer-brand">${ys.name}</span> â ${l?"Relatório gerado em":"Report generated on"} ${p}</div> 419 <div>${l?`PerÃodo de ${t.daysInPeriod} dias`:`${t.daysInPeriod}-day period`}</div> 420 </div> 421 422 </div> 423 424 <script> 425 // Auto-trigger print after fonts load 426 window.onload = function() { 427 // Small delay to ensure Google Fonts loaded 428 setTimeout(function() { 429 // Don't auto-print â let user review first and click the button 430 }, 500); 431 }; 432 <\/script> 433</body> 434</html>`,u=window.open("","_blank","width=900,height=700,scrollbars=yes");if(!u){const d=new Blob([N],{type:"text/html;charset=utf-8"}),P=URL.createObjectURL(d);window.open(P,"_blank");return}u.document.write(N),u.document.close()}const Fn=()=>{const{t:s,i18n:i}=O(),n=Pe(),{toast:r}=Ns(),{selectedProfile:t}=ws(),{isSubscribed:a,subscription:h}=ks(),l=a&&(h==null?void 0:h.plan_slug)!=="free",[o]=Cs(),g=x.useMemo(()=>{const u=Number(o.get("period"));return[7,30,90].includes(u)?u:30},[o]),[p,j]=x.useState(g),[b,$]=x.useState(!1),{overview:y,chartData:E,accountInsights:C,mediaInsights:c,mediaSnapshots:R,loading:_,syncing:S,error:D,lastSyncAt:I,syncInsights:T,fetchInsights:H}=Os((t==null?void 0:t.id)||null,{initialPeriod:g}),G=u=>{j(u),H(u)},V=()=>{if(!t){r({title:s("publishing.insights.selectProfileTitle"),description:s("publishing.insights.selectProfileDesc"),variant:"destructive"});return}n(`/connect-instagram?profileId=${t.id}`)},f=async()=>{const u=await T("full");u!=null&&u.success?(p!==30&&await H(p),r({title:s("publishing.insights.syncSuccess"),description:s("publishing.insights.syncSuccessDesc")})):u!=null&&u.error&&r({title:s("publishing.insights.syncError"),description:u.error,variant:"destructive"})},v=x.useCallback(()=>{var M;if(!(y!=null&&y.summary)||!t)return;const{summary:u,mediaPerformance:A}=y,w=[];w.push(["Instagram Insights Export"]),w.push([`Profile: ${t.username}`]),w.push([`Period: ${u.periodStart} to ${u.periodEnd}`]),w.push([]),w.push(["KPI","Value","Change"]),w.push(["Followers",String(u.followerCount),u.followerChange!==void 0?`${u.followerChange}`:""]),w.push(["Reach",String(u.reach),u.reachChange!==void 0?`${u.reachChange}%`:""]),w.push(["Impressions",String(u.impressions),u.impressionsChange!==void 0?`${u.impressionsChange}%`:""]),w.push(["Interactions",String(u.totalInteractions),u.interactionsChange!==void 0?`${u.interactionsChange}%`:""]),w.push(["Accounts Engaged",u.accountsEngaged===null?"":String(u.accountsEngaged),u.accountsEngagedChange!==void 0?`${u.accountsEngagedChange}%`:""]),w.push(["Website Clicks",String(u.websiteClicks),u.websiteClicksChange!==void 0?`${u.websiteClicksChange}%`:""]),w.push([]),(M=A==null?void 0:A.topPosts)!=null&&M.length&&(w.push(["Top Posts"]),w.push(["Rank","Type","Likes","Comments","Saved","Reach","Engagement Rate","Caption"]),A.topPosts.forEach((d,P)=>{w.push([String(P+1),d.mediaType,String(d.likeCount),String(d.commentsCount),String(d.savedCount),String(d.reach),`${d.engagementRate}%`,`"${(d.caption||"").replace(/"/g,'""').substring(0,100)}"`])}));const k=w.map(d=>d.join(",")).join(` 435`),F=new Blob([k],{type:"text/csv;charset=utf-8;"}),m=URL.createObjectURL(F),L=document.createElement("a");L.href=m,L.download=`insights-${t.username}-${new Date().toISOString().split("T")[0]}.csv`,L.click(),URL.revokeObjectURL(m)},[y,t]),N=x.useCallback(()=>{!y||!t||fi({overview:y,username:t.username,selectedPeriod:p,language:i.language})},[y,t,p,i.language]);return e.jsxs(gt,{header:e.jsx(ht,{}),maxWidth:"6xl",bottomNav:e.jsx(kt,{}),children:[e.jsx(xt,{title:s("publishing.insights.pageTitle"),backTo:"/dashboard"}),e.jsx("div",{className:"pb-2",children:t?e.jsx(Qt,{overview:y,chartData:E,mediaInsights:c,mediaSnapshots:R,accountInsights:C,profileId:t==null?void 0:t.id,isSubscribed:l,loading:_,syncing:S,error:D,lastSyncAt:I,selectedPeriod:p,onPeriodChange:G,onSync:f,onConnect:V,onExportCsv:v,onExportPdf:N}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx("h2",{className:"text-xl font-semibold mb-2",children:s("publishing.insights.noProfile")}),e.jsx("p",{className:"text-muted-foreground mb-4",children:s("publishing.insights.noProfileDesc")}),e.jsx(q,{onClick:()=>n("/instagram-setup"),children:s("publishing.insights.setupProfile")})]})}),t&&e.jsxs(e.Fragment,{children:[e.jsx(q,{onClick:()=>$(!0),className:"fixed bottom-[calc(5rem+var(--sai-bottom))] left-4 right-4 z-40 h-auto rounded-2xl border border-violet-200/70 bg-background/95 px-4 py-3 text-foreground shadow-lg backdrop-blur supports-[backdrop-filter]:bg-background/85 hover:border-violet-300 hover:bg-background md:bottom-6 md:left-auto md:right-6 md:w-auto md:min-w-[250px]","aria-label":s("publishing.insights.chat.fabLabel"),children:e.jsxs("div",{className:"flex w-full items-center gap-3 text-left",children:[e.jsx("div",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-violet-100 text-violet-700 ring-1 ring-violet-200 dark:bg-violet-900/40 dark:text-violet-300 dark:ring-violet-800/60",children:e.jsx(Ct,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:s("publishing.insights.chat.fabHint")})}),e.jsx("div",{className:"mt-1 text-sm font-semibold leading-tight sm:text-[15px]",children:s("publishing.insights.chat.fabTitle")})]})]})}),e.jsx(mi,{open:b,onOpenChange:$,profileId:t.id,periodDays:p})]})]})};export{Fn 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.