1import{y as vs,r as o,s as C,j as e,I as $,B as f,b as Y,g as Je,D as Ze,bC as Qe,l as js,m as bs,n as ws,aD as Ns,aF as ys,z as Fe,J as T,d as p,u as Cs,q as Ss,cp as ks,O as _s,cq as Rs,h as es,P as Ts,U as Vs,W as Ps}from"./index-BGIpxRCe.js";import{C as _,a as P,b as F,c as U,d as R}from"./card-TV1xAd85.js";import{L as k}from"./label-DFdo1YbX.js";import{C as pe}from"./checkbox-DjmWk1ZM.js";import{u as V,w as Se}from"./xlsx-DjuO7_Ju.js";import{T as Fs,a as As,b as ss,c as as}from"./tabs-a4SwKwD3.js";import{S as Ls,a as $s,b as Is,c as Ds,d as Es}from"./select-CdLrzil7.js";import{A as Ms,a as zs,b as Us,c as Os}from"./accordion-DJdVL38V.js";import{U as Bs}from"./users-round-CAhHZmcw.js";import{D as ke}from"./download-D4LQUnD_.js";import{F as rs}from"./folder-plus-Bjr1YseL.js";import{E as He}from"./external-link-DpnyMPez.js";import{H as qs}from"./history-BasOdGeC.js";import{R as Hs}from"./rotate-ccw-76RvmfXv.js";import{T as Ae}from"./trash-2-KIhZAsR2.js";import{F as ts}from"./folder-DIwk8PJW.js";import{A as Gs}from"./arrow-left-3ib0gEtS.js";import{C as ds}from"./circle-check-Df5uIk4a.js";import{B as Ks}from"./badge-check-DlO0X34q.js";import{U as Ws}from"./users-CIoBAtz3.js";import{T as Xs}from"./trending-up-D6VF-4Aq.js";import{E as Ce}from"./eye-CZZET0v4.js";import{H as ls}from"./heart-D4so8af1.js";import{T as ns}from"./target-DgjIfBtq.js";import{F as Ys}from"./file-spreadsheet-D6uhG0kn.js";import{C as Js}from"./circle-help-NBEtbf-g.js";import{D as Zs}from"./dollar-sign-CCKdJ5WX.js";import{C as Qs}from"./circle-x-D63TupUx.js";import"./index-BdQq_4o_.js";import"./chevron-up-C4GcDybf.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 is=vs("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);function ea({onAnalyze:m}){const[g,b]=o.useState(""),[j,I]=o.useState("50"),[N,t]=o.useState(!0),[w,re]=o.useState(!0),[D,te]=o.useState(!1),[u,J]=o.useState(null),[S,H]=o.useState([]),[A,G]=o.useState({}),[K,_e]=o.useState({}),[O,le]=o.useState(""),[B,W]=o.useState(!1),[q,Re]=o.useState(""),[ne,fe]=o.useState(!1),[n,ie]=o.useState(null),[Te,ge]=o.useState(!1),[L,Z]=o.useState(new Set);o.useEffect(()=>{Z(new Set)},[u]);const X=(a,l)=>{Z(i=>{const s=new Set(i);return l?s.add(a):s.delete(a),s})},oe=a=>{u&&Z(a?new Set(u.collaborators.map(l=>l.username)):new Set)},[E,ve]=o.useState([]),[M,je]=o.useState(!1);o.useEffect(()=>{Le(),ce()},[]);const ce=async()=>{je(!0);const{data:a,error:l}=await C.from("competitor_collab_scans").select("id, handle, collaborator_count, collaborators, stats, errors, created_at").order("created_at",{ascending:!1}).limit(25);if(je(!1),l){console.error(l);return}ve(a??[])},Le=async()=>{const{data:a,error:l}=await C.from("collab_folders").select("*").order("created_at",{ascending:!1});if(l){console.error(l);return}H(a??[])},de=async a=>{const{data:l,error:i}=await C.from("collab_folder_items").select("*").eq("folder_id",a).order("collab_count",{ascending:!1});if(i){console.error(i);return}G(s=>({...s,[a]:l??[]}))},be=async()=>{const a=q.trim();if(!a){p.error("Folder name required");return}const{data:l}=await C.auth.getUser(),i=l.user?.id;if(!i){p.error("Please sign in");return}const{data:s,error:r}=await C.from("collab_folders").insert({user_id:i,name:a,competitor_handle:u?.handle??g.trim().replace(/^@/,"")??null}).select().single();if(r){p.error(r.message);return}p.success(`Folder "${a}" created`),H(d=>[s,...d]),le(s.id),Re(""),W(!1)},Q=async()=>O||(S.length===0?(p.error("Create a folder first"),W(!0),null):(p.error("Select a folder"),null)),we=async(a,l)=>{const{data:i}=await C.auth.getUser(),s=i.user?.id;if(!s)return p.error("Please sign in"),0;const r=l.map(h=>({folder_id:a,user_id:s,username:h.username,full_name:h.fullName??null,profile_pic_url:h.profilePicUrl??null,collab_count:h.collabCount,sources:h.source,sample_posts:h.samplePosts})),{error:d,count:x}=await C.from("collab_folder_items").upsert(r,{onConflict:"folder_id,username",count:"exact"});return d?(p.error(d.message),0):(await de(a),x??r.length)},ee=async()=>
6{if(!u||u.collaborators.length===0)return;const a=await Q();if(a){fe(!0);try{const l=await we(a,u.collaborators),i=S.find(s=>s.id===a)?.name??"folder";p.success(`Saved ${l} collaborators to "${i}"`)}finally{fe(!1)}}},$e=async a=>{const l=await Q();if(l){ie(a.username);try{await we(l,[a]);const i=S.find(s=>s.id===l)?.name??"folder";p.success(`Saved @${a.username} to "${i}"`)}finally{ie(null)}}},Ie=async()=>{if(!u||L.size===0){p.error("Select at least one creator");return}const a=await Q();if(!a)return;const l=u.collaborators.filter(i=>L.has(i.username));ge(!0);try{const i=await we(a,l),s=S.find(r=>r.id===a)?.name??"folder";p.success(`Saved ${i} collaborator${i===1?"":"s"} to "${s}"`),Z(new Set)}finally{ge(!1)}},c=async a=>{if(!confirm("Delete this folder and all saved collaborators in it?"))return;const{error:l}=await C.from("collab_folders").delete().eq("id",a);if(l){p.error(l.message);return}H(i=>i.filter(s=>s.id!==a)),G(i=>{const s={...i};return delete s[a],s}),O===a&&le(""),p.success("Folder deleted")},me=async(a,l)=>{const{error:i}=await C.from("collab_folder_items").delete().eq("id",l);if(i){p.error(i.message);return}G(s=>({...s,[a]:(s[a]??[]).filter(r=>r.id!==l)}))},De=a=>{const l=A[a.id]??[];if(l.length===0){p.error("Folder is empty");return}const i=l.map(x=>{const h=Array.isArray(x.sample_posts)?x.sample_posts:[];return{username:x.username,profile_url:`https://www.instagram.com/${x.username}/`,full_name:x.full_name??"",collab_count:x.collab_count,sources:(x.sources??[]).join(", "),sample_post_1:h[0]?.url??"",sample_caption_1:h[0]?.caption??"",sample_post_2:h[1]?.url??"",sample_post_3:h[2]?.url??""}}),s=V.json_to_sheet(i),r=V.book_new();V.book_append_sheet(r,s,"collaborators");const d=a.name.replace(/[^a-z0-9_-]+/gi,"_");Se(r,`${d}-${new Date().toISOString().slice(0,10)}.xlsx`)},ue=async()=>{if(!g.trim()){p.error("Enter a competitor Instagram handle or URL");return}te(!0),J(null);try{const{data:a,error:l}=await C.functions.invoke("find-competitor-collabs",{body:{handle:g.trim(),resultsLimit:Math.min(100,Math.max(10,Number(j)||50)),includeCoauthor:N,includeTagged:w}});if(l)throw l;if(a?.error)throw new Error(a.error);const i=a;J(i);const s=i.collaborators.length;p.success(`Found ${s} collaborator${s===1?"":"s"}`);try{const{data:r}=await C.auth.getUser(),d=r.user?.id;if(d){const{data:x,error:h}=await C.from("competitor_collab_scans").insert({user_id:d,handle:i.handle,collaborators:i.collaborators,stats:i.stats,errors:i.errors??null,collaborator_count:s}).select("id, handle, collaborator_count, collaborators, stats, errors, created_at").single();h?(console.error("scan save failed",h),p.error("Saved locally, but cloud save failed")):x&&ve(z=>[x,...z].slice(0,25))}}catch(r){console.error(r)}}catch(a){console.error(a),p.error(a?.message??"Failed to find collaborators")}finally{te(!1)}},Ee=()=>{if(!u)return;const a=u.collaborators.map(s=>({username:s.username,profile_url:`https://www.instagram.com/${s.username}/`,full_name:s.fullName??"",collab_count:s.collabCount,sources:s.source.join(", "),sample_post_1:s.samplePosts[0]?.url??"",sample_caption_1:s.samplePosts[0]?.caption??"",sample_post_2:s.samplePosts[1]?.url??"",sample_post_3:s.samplePosts[2]?.url??""})),l=V.json_to_sheet(a),i=V.book_new();V.book_append_sheet(i,l,"collaborators"),Se(i,`collabs-${u.handle}-${new Date().toISOString().slice(0,10)}.xlsx`)},Me=a=>{const l={handle:a.handle,collaborators:Array.isArray(a.collaborators)?a.collaborators:[],stats:a.stats??{totalCollaborators:a.collaborator_count,coauthorPostsScanned:0,taggedPostsScanned:0},errors:Array.isArray(a.errors)?a.errors:void 0};b(a.handle),J(l),p.success(`Loaded scan for @${a.handle}`),typeof window<"u"&&window.scrollTo({top:0,behavior:"smooth"})},ze=async a=>{if(!confirm("Delete this saved scan?"))return;const{error:l}=await C.from("competitor_collab_scans").delete().eq("id",a);if(l){p.error(l.message);return}ve(i=>i.filter(s=>s.id!==a))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(_,{children:[e.jsxs(P,{children:[e.jsxs(F,{className:"flex items-center gap-2",children:[e.jsx(Bs,{className:"h-5 w-5 text-primary"})," Competitor Collab Finder"]}),e.jsx(U,{children:`Paste a competitor's Instagram handle. We scan their own collab posts and the "tagged" tab to surface creators they've worked with â useful for UGC outreach.`})]}),e.jsxs(R,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(k,{htmlFor:"brand-handle",children:"Competitor Instagram handle or URL"}),e.jsx($,{id:"brand-handle",placeholder:"@genspark_ai or https://instagram.com/genspark_ai",value:g,onChange:a=>b(a.target.value),onKeyDown:a=>a.key==="Enter"&&!D&&ue()})]}),e.jsxs("div",{children:[e.jsx(k,{htmlFor:"limit",children:"Posts to scan per source"}),e.jsx($,{id:"limit",type:"number",min:10,max:100,value:j,onChange:a=>I(a.target.value)})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(pe,{checked:N,onCheckedChange:a=>t(!!a)}),"True Collab posts (dual-author)"]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(pe,{checked:w,onCheckedChange:a=>re(!!a)}),"Tagged-by-creator posts (broader UGC)"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(f,{onClick:ue,disabled:D,children:[D?e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Je,{className:"h-4 w-4 mr-2"}),D?"Scanning Instagramâ¦":"Find collaborators"]}),u&&u.collaborators.length>0&&e.jsxs(f,{variant:"outline",onClick:Ee,children:[e.jsx(ke,{className:"h-4 w-4 mr-2"})," Export CSV"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: scanning 50 posts per source costs ~1â2 Apify credits per competitor and takes 30â90 seconds."})]})]}),u&&e.jsxs(_,{children:[e.jsx(P,{children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(F,{children:[u.collaborators.length," collaborator",u.collaborators.length===1?"":"s"," found for @",u.handle]}),e.jsxs(U,{children:["Scanned ",u.stats.coauthorPostsScanned," brand post",u.stats.coauthorPostsScanned===1?"":"s"," and ",u.stats.taggedPostsScanned," tagged post",u.stats.taggedPostsScanned===1?"":"s",".",u.errors?.length?` Notes: ${u.errors.join(" · ")}`:""]})]}),u.collaborators.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ls,{value:O,onValueChange:le,children:[e.jsx($s,{className:"w-[200px]",children:e.jsx(Is,{placeholder:"Select folderâ¦"})}),e.jsx(Ds,{children:S.length===0?e.jsx("div",{className:"px-2 py-1.5 text-sm text-muted-foreground",children:"No folders yet"}):S.map(a=>e.jsx(Es,{value:a.id,children:a.name},a.id))})]}),e.jsxs(Ze,{open:B,onOpenChange:W,children:[e.jsx(Qe,{asChild:!0,children:e.jsxs(f,{variant:"outline",size:"sm",children:[e.jsx(rs,{className:"h-4 w-4 mr-1"})," New"]})}),e.jsxs(js,{children:[e.jsxs(bs,{children:[e.jsx(ws,{children:"New collab folder"}),e.jsx(Ns,{children:"Group saved creators (e.g. by competitor name)."})]}),e.jsx($,{autoFocus:!0,placeholder:u?.handle?`e.g. ${u.handle}`:"e.g. Genspark",value:q,onChange:a=>Re(a.target.value),onKeyDown:a=>a.key==="Enter"&&be()}),e.jsxs(ys,{children:[e.jsx(f,{variant:"ghost",onClick:()=>W(!1),children:"Cancel"}),e.jsx(f,{onClick:be,children:"Create"})]})]})]}),e.jsxs(f,{size:"sm",variant:"secondary",onClick:Ie,disabled:Te||L.size===0,children:[Te?e.jsx(Y,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fe,{className:"h-4 w-4 mr-1"}),"Save selected (",L.size,")"]}),e.jsxs(f,{size:"sm",onClick:ee,disabled:ne,children:[ne?e.jsx(Y,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Fe,{className:"h-4 w-4 mr-1"}),"Save all"]})]})]})}),e.jsx(R,{children:u.collaborators.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No collaborators found. Try increasing posts to scan, or this account may not run creator collabs publicly."}):e.jsxs("div",{className:"divide-y",children:[e.jsxs("div",{className:"py-2 flex items-center gap-3",children:[e.jsx(pe,{checked:L.size===u.collaborators.length&&u.collaborators.length>0,onCheckedChange:a=>oe(!!a)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:L.size>0?`${L.size} selected`:"Select all"})]}),u.collaborators.map(a=>e.jsxs("div",{className:"py-3 flex items-start gap-3",children:[e.jsx(pe,{className:"mt-1",checked:L.has(a.username),onCheckedChange:l=>X(a.username,!!l)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("a",{href:`https://www.instagram.com/${a.username}/`,target:"_blank",rel:"noreferrer",className:"font-semibold hover:underline flex items-center gap-1",children:["@",a.username,e.jsx(He,{className:"h-3 w-3"})]}),a.fullName&&e.jsx("span",{className:"text-sm text-muted-foreground",children:a.fullName}),e.jsxs(T,{variant:"secondary",children:[a.collabCount," collab",a.collabCount===1?"":"s"]}),a.source.includes("coauthor")&&e.jsx(T,{children:"Co-author"}),a.source.includes("tagged")&&e.jsx(T,{variant:"outline",children:"Tagged"})]}),a.samplePosts[0]?.caption&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:['"',a.samplePosts[0].caption,'"']}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:a.samplePosts.slice(0,3).map((l,i)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noreferrer",className:"text-xs text-primary hover:underline",children:["post ",i+1," â"]},i))})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(f,{size:"sm",variant:"ghost",onClick:()=>$e(a),disabled:n===a.username,title:"Save to folder",children:n===a.username?e.jsx(Y,{className:"h-4 w-4 animate-spin"}):e.jsx(Fe,{className:"h-4 w-4"})}),m&&e.jsx(f,{size:"sm",variant:"outline",onClick:()=>m(a.username),children:"Analyze"})]})]},a.username))]})})]}),e.jsxs(_,{children:[e.jsx(P,{children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(F,{className:"flex items-center gap-2",children:[e.jsx(qs,{className:"h-5 w-5 text-primary"})," Recent scans"]}),e.jsx(U,{children:'Every scan is auto-saved to the cloud. Click "Load" to restore results without re-running.'})]}),e.jsx(f,{variant:"ghost",size:"sm",onClick:ce,disabled:M,children:M?e.jsx(Y,{className:"h-4 w-4 animate-spin"}):e.jsx(Hs,{className:"h-4 w-4"})})]})}),e.jsx(R,{children:E.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No saved scans yet. Run a scan above to create one."}):e.jsx("div",{className:"divide-y",children:E.map(a=>e.jsxs("div",{className:"py-2 flex items-center gap-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:["@",a.handle]}),e.jsxs(T,{variant:"secondary",children:[a.collaborator_count," collab",a.collaborator_count===1?"":"s"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(a.created_at).toLocaleStr
6ing()})]})}),e.jsx(f,{size:"sm",variant:"outline",onClick:()=>Me(a),children:"Load"}),e.jsx(f,{size:"sm",variant:"ghost",onClick:()=>ze(a.id),title:"Delete scan",children:e.jsx(Ae,{className:"h-4 w-4"})})]},a.id))})})]}),e.jsxs(_,{children:[e.jsx(P,{children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(F,{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"h-5 w-5 text-primary"})," Saved folders"]}),e.jsx(U,{children:"Group collaborators by competitor for outreach. Click a folder to view, export, or remove creators."})]}),e.jsx(Ze,{open:B,onOpenChange:W,children:e.jsx(Qe,{asChild:!0,children:e.jsxs(f,{variant:"outline",size:"sm",children:[e.jsx(rs,{className:"h-4 w-4 mr-1"})," New folder"]})})})]})}),e.jsx(R,{children:S.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:'No folders yet. Create one (e.g. "Genspark") to start saving collaborators.'}):e.jsx(Ms,{type:"multiple",onValueChange:a=>{a.forEach(l=>{A[l]||de(l)})},children:S.map(a=>{const l=A[a.id]??[],i=(K[a.id]??"").trim().toLowerCase(),s=i?l.filter(r=>r.username.toLowerCase().includes(i)||(r.full_name??"").toLowerCase().includes(i)):l;return e.jsxs(zs,{value:a.id,children:[e.jsx(Us,{className:"hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-2 flex-1",children:[e.jsx(ts,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:a.name}),a.competitor_handle&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["@",a.competitor_handle]}),A[a.id]&&e.jsx(T,{variant:"secondary",className:"ml-2",children:l.length})]})}),e.jsxs(Os,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[e.jsxs(f,{size:"sm",variant:"outline",onClick:()=>De(a),children:[e.jsx(ke,{className:"h-4 w-4 mr-1"})," Export"]}),e.jsxs(f,{size:"sm",variant:"ghost",onClick:()=>c(a.id),children:[e.jsx(Ae,{className:"h-4 w-4 mr-1"})," Delete folder"]})]}),l.length>0&&e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Je,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx($,{placeholder:"Search creators by handle or nameâ¦",value:K[a.id]??"",onChange:r=>_e(d=>({...d,[a.id]:r.target.value})),className:"pl-9"})]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No saved creators yet."}):s.length===0?e.jsxs("p",{className:"text-sm text-muted-foreground",children:['No creators match "',K[a.id],'".']}):e.jsx("div",{className:"divide-y",children:s.map(r=>{const d=Array.isArray(r.sample_posts)?r.sample_posts:[];return e.jsxs("div",{className:"py-3 flex items-start gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("a",{href:`https://www.instagram.com/${r.username}/`,target:"_blank",rel:"noreferrer",className:"font-semibold hover:underline flex items-center gap-1",children:["@",r.username,e.jsx(He,{className:"h-3 w-3"})]}),r.full_name&&e.jsx("span",{className:"text-sm text-muted-foreground",children:r.full_name}),e.jsxs(T,{variant:"secondary",children:[r.collab_count," collab",r.collab_count===1?"":"s"]}),(r.sources??[]).includes("coauthor")&&e.jsx(T,{children:"Co-author"}),(r.sources??[]).includes("tagged")&&e.jsx(T,{variant:"outline",children:"Tagged"})]}),d[0]?.caption&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:['"',d[0].caption,'"']}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.slice(0,3).map((x,h)=>e.jsxs("a",{href:x.url,target:"_blank",rel:"noreferrer",className:"text-xs text-primary hover:underline",children:["post ",h+1," â"]},h))})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[m&&e.jsx(f,{size:"sm",variant:"outline",onClick:()=>m(r.username),children:"Analyze"}),e.jsx(f,{size:"sm",variant:"ghost",onClick:()=>me(a.id,r.id),title:"Remove",children:e.jsx(Ae,{className:"h-4 w-4"})})]})]},r.id)})})]})]},a.id)})})})]})]})}const v=m=>new Intl.NumberFormat("en-US").format(Math.round(m)),y=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(m),Pe={custom:{label:"Custom",ctr:.5,conv:2,ltv:30,hint:"Your own numbers"}
6,saas:{label:"SaaS / B2B",ctr:.4,conv:2,ltv:240,hint:"Lower CTR, high LTV (annual contracts)"},b2cApp:{label:"B2C app",ctr:.6,conv:2.5,ltv:35,hint:"Mobile/web app subscriptions"},creator:{label:"Creator product",ctr:.8,conv:1.5,ltv:60,hint:"Courses, one-time digital products"},ecommerce:{label:"E-commerce",ctr:.5,conv:1,ltv:70,hint:"Physical goods, repeat orders"}},os=.7;function sa(m){return m>=5?1.3:m<=1?.7:1}const aa={low:{ctr:.5,conv:.75,ltv:.67},base:{ctr:1,conv:1,ltv:1},high:{ctr:1.5,conv:1.25,ltv:1.33}};function Oe(m,g,b,j,I,N,t){const w=aa[m],re=b/100*w.ctr,D=j/100*w.conv,te=I*w.ltv,u=g*re,J=u*D,S=J*te,H=S+N,A=H-t;return{scenario:m,ctr:Number((re*100).toFixed(3)),paidConversion:Number((D*100).toFixed(3)),ltv:Number(te.toFixed(2)),clicks:Number(u.toFixed(1)),customers:Number(J.toFixed(2)),customerRevenue:Number(S.toFixed(2)),viewRevenue:Number(N.toFixed(2)),revenue:Number(H.toFixed(2)),roi:Number(A.toFixed(2)),roiPct:t>0?Number((A/t*100).toFixed(1)):0,verdict:A>=0?"profitable":"unprofitable"}}function $a(){const m=Cs(),{user:g,loading:b}=Ss(),{isStaff:j,loading:I}=ks(),[N,t]=o.useState(""),[w,re]=o.useState("380"),[D,te]=o.useState("15"),[u,J]=o.useState("0"),[S,H]=o.useState("1"),[A,G]=o.useState("custom"),[K,_e]=o.useState("0.5"),[O,le]=o.useState("2"),[B,W]=o.useState("30"),[q,Re]=o.useState("median"),[ne,fe]=o.useState(!1),[n,ie]=o.useState(null),[Te,ge]=o.useState("analyzer"),[L,Z]=o.useState(!1),[X,oe]=o.useState(null),[E,ve]=o.useState([]),[M,je]=o.useState("0"),[ce,Le]=o.useState(!0),[de,be]=o.useState({}),[Q,we]=o.useState("date"),[ee,$e]=o.useState("desc"),Ie=o.useMemo(()=>{const s=d=>{const x=d.result,h=x.profitability,z=x.inputs?.ratePerVideo??(h.numVideos>0?h.totalCost/h.numVideos:h.totalCost);switch(Q){case"followers":return x.metrics.followers||0;case"engagement":return x.metrics.engagementRate||0;case"ratePerVideo":return z||0;case"medianViews":return x.metrics.medianReelViews??x.metrics.avgReelViews??0;case"avgLikes":return x.metrics.avgLikes||0;case"roiUsd":return h.scenarios?.base.roi??h.roi??0;case"roiPct":return h.scenarios?.base.roiPct??h.roiPct??0;case"date":default:return new Date(d.created_at).getTime()}},r=[...E];return r.sort((d,x)=>ee==="asc"?s(d)-s(x):s(x)-s(d)),r},[E,Q,ee]);o.useEffect(()=>{if(n?.audience?.viewerTypes){const s={};n.audience.viewerTypes.forEach(r=>{s[r.type]=!0}),be(s)}},[n]);const c=o.useMemo(()=>{if(!n)return null;const s=n.metrics,r=q==="average"?s.avgReelViews:q==="trimmed"?s.trimmedMeanReelViews??s.avgReelViews:s.medianReelViews??s.avgReelViews,d=Math.max(1,Math.floor(Number(S)||1)),x=r*d,h=x*os,z=Math.max(0,Number(w)||0),ms=n.audience.viewerTypes.length?n.audience.viewerTypes.filter(Ue=>de[Ue.type]!==!1).reduce((Ue,gs)=>Ue+(gs.share||0),0):1,Ge=Math.max(0,Math.min(1,ms||1)),xe=h*Ge,Ke=ce?sa(s.engagementRate||0):1,Ne=(Number(K)||0)*Ke,ye=Number(O)||0,Ve=Number(B)||0,he=Math.max(0,Number(M)||0),We={low:Oe("low",xe,Ne,ye,Ve,he,z),base:Oe("base",xe,Ne,ye,Ve,he,z),high:Oe("high",xe,Ne,ye,Ve,he,z)},us=h>0?z/h*1e3:0,Xe=xe*(ye/100)*Ve,xs=Xe>0?(z-he)/Xe*100:NaN,Ye=xe*(Ne/100)*(ye/100),hs=Ye>0?(z-he)/Ye:NaN,ps=We.base.customerRevenue+he,fs=Math.round(h/1e3*5*.3);return{perVideoViews:r,projectedViews:h,organicProjectedViews:x,addressableViews:xe,effIcpShare:Ge,erMult:Ke,effCtrPct:Ne,cpm:us,scenarios:We,breakeven:{requiredCtrPct:xs,requiredLtv:hs,maxCost:ps},suggestedBrandCredit:fs}},[n,q,S,w,K,O,B,M,ce,de]);o.useEffect(()=>{b||I||(g?j||m("/"):m("/auth"))},[g,j,b,I,m]);const me=o.useCallback(async()=>{const{data:s,error:r}=await C.from("influencer_analyses").select("id, handle, result, created_at").order("created_at",{ascending:!1});if(r){console.error(r);return}ve(s??[])},[]);o.useEffect(()=>{g&&j&&me()},[g,j,me]);const De=s=>{if(G(s),s==="custom")return;const r=Pe[s];_e(String(r.ctr)),le(String(r.conv)),W(String(r.ltv))},ue=async s=>{const r=(s??N).trim();if(!r){p.error("Enter an Instagram handle or URL");return}fe(!0),ie(null),oe(null);try{const{data:d,error:x}=await C.functions.invoke("analyze-instagram-influencer",{body:{handle:r,totalRate:Number(w)||0,targetCpm:Number(D)||15,valuePerView:Number(u)||0,numVideos:Math.max(1,Math.floor(Number(S)||1)),ctr:Number(K)||0,paidConversion:Number(O)||0,ltv:Number(B)||0,viewsBasis:q}});if(x)throw x;if(d?.error)throw new Error(d.error);ie(d),p.success("Analysis complete")}catch(d){console.error(d),p.error(d?.message??"Failed to analyze profile")}finally{fe(!1)}},Ee=async()=>
6{if(!(!n||!g)){Z(!0);try{const{data:s,error:r}=await C.from("influencer_analyses").insert({user_id:g.id,handle:n.handle,result:n}).select("id").single();if(r)throw r;oe(s.id),p.success("Analysis saved"),me()}catch(s){console.error(s),p.error(s?.message??"Failed to save")}finally{Z(!1)}}},Me=s=>{const r=qe([s]);Se(r,`influencer-${s.result.handle}-${s.id.slice(0,8)}.xlsx`)},ze=()=>{if(!n)return;const s=qe([{id:X??"current",handle:n.handle,result:n,created_at:new Date().toISOString()}]);Se(s,`influencer-${n.handle}.xlsx`)},a=()=>{if(!E.length)return;const s=qe(E);Se(s,`influencer-analyses-${new Date().toISOString().slice(0,10)}.xlsx`)},l=async s=>{if(!confirm("Delete this saved analysis?"))return;const{error:r}=await C.from("influencer_analyses").delete().eq("id",s);if(r){p.error("Failed to delete");return}X===s&&oe(null),p.success("Deleted"),me()},i=s=>{ie(s.result),oe(s.id),t(s.handle),window.scrollTo({top:0,behavior:"smooth"})};return b||I?e.jsx("div",{className:"min-h-screen flex items-center justify-center pt-20",children:e.jsx(Y,{className:"h-6 w-6 animate-spin text-primary"})}):e.jsx(_s,{children:e.jsxs("div",{className:"min-h-screen pt-24 pb-12 px-4 max-w-6xl mx-auto",children:[e.jsx("div",{className:"mb-6 flex items-center justify-between",children:e.jsxs("div",{children:[e.jsxs(f,{variant:"ghost",size:"sm",onClick:()=>m("/admin"),className:"mb-2",children:[e.jsx(Gs,{className:"h-4 w-4 mr-1"})," Back to Admin"]}),e.jsxs("h1",{className:"text-3xl font-bold flex items-center gap-2",children:[e.jsx(Rs,{className:"h-7 w-7 text-primary"}),"Instagram Influencer Analyzer"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Estimate engagement, audience, and ROI for sponsorship deals."})]})}),e.jsxs(Fs,{value:Te,onValueChange:s=>ge(s),className:"w-full",children:[e.jsxs(As,{className:"mb-4",children:[e.jsx(ss,{value:"analyzer",children:"ROI Analyzer"}),e.jsx(ss,{value:"collabs",children:"Competitor Collab Finder"})]}),e.jsx(as,{value:"collabs",children:e.jsx(ea,{onAnalyze:s=>{t(s),ge("analyzer"),window.scrollTo({top:0,behavior:"smooth"}),ue(s)}})}),e.jsxs(as,{value:"analyzer",children:[e.jsxs(_,{className:"mb-6",children:[e.jsxs(P,{children:[e.jsx(F,{children:"Analyze a creator"}),e.jsx(U,{children:"Paste an Instagram handle (@nasa) or profile URL, set your rate card and targets."})]}),e.jsx(R,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(k,{htmlFor:"handle",children:"Instagram handle or URL"}),e.jsx($,{id:"handle",placeholder:"@nasa or https://instagram.com/nasa",value:N,onChange:s=>t(s.target.value),onKeyDown:s=>s.key==="Enter"&&!ne&&ue()})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs(k,{className:"flex items-center gap-1",children:[e.jsx(es,{className:"h-3.5 w-3.5"})," Benchmark preset"]}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-1",children:Object.keys(Pe).map(s=>e.jsx(f,{type:"button",size:"sm",variant:A===s?"default":"outline",onClick:()=>De(s),children:Pe[s].label},s))}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[Pe[A].hint," â overrides CTR / paid % / LTV below. Edit any field to fine-tune."]})]}),e.jsxs("div",{children:[e.jsx(k,{htmlFor:"rate",children:"Total deal rate (USD)"}),e.jsx($,{id:"rate",type:"number",min:"0",value:w,onChange:s=>re(s.target.value)})]}),e.jsxs("div",{children:[e.jsx(k,{htmlFor:"numVideos",children:"# of videos in deal"}),e.jsx($,{id:"numVideos",type:"number",min:"1",step:"1",value:S,onChange:s=>H(s.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Typical 1â3"})]}),e.jsxs("div",{children:[e.jsxs(k,{htmlFor:"ctr",className:"flex items-center gap-1",children:["CTR % (views â link clicks)",e.jsx(se,{children:"Percentage of viewers who tap your link-in-bio / sticker. Realistic IG sponsored CTR is 0.2â0.8% â anything â¥1% is exceptional."})]}),e.jsx($,{id:"ctr",type:"number",min:"0",step:"0.1",value:K,onChange:s=>{_e(s.target.value),G("custom")}}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Typical 0.2â0.8% (IG sponsored)"})]}),e.jsxs("div",{children:[e.jsxs(k,{htmlFor:"paid",className:"flex items-center gap-1",children:["Paid conversion % (clicks â paid)",e.jsx(se,{children:"Of people who click, what % become paying customers. Cold IG traffic typically converts at 1â3% (warm/aligned audie
6nces can reach 3â5%)."})]}),e.jsx($,{id:"paid",type:"number",min:"0",step:"0.1",value:O,onChange:s=>{le(s.target.value),G("custom")}}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Typical 1â3% (cold IG traffic)"})]}),e.jsxs("div",{children:[e.jsxs(k,{htmlFor:"ltv",className:"flex items-center gap-1",children:["LTV (USD per paying customer)",e.jsx(se,{children:"Lifetime value: total revenue you expect from one customer across their entire relationship â already bakes in churn."})]}),e.jsx($,{id:"ltv",type:"number",min:"0",step:"1",value:B,onChange:s=>{W(s.target.value),G("custom")}}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Avg revenue per customer over lifetime (bakes in churn)"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs(k,{className:"flex items-center gap-1",children:["Base ROI on",e.jsx(se,{children:"Median = middle reel (most realistic). Trimmed mean drops top/bottom 10% to ignore viral outliers. Average is easily skewed by 1â2 viral hits."})]}),e.jsx("div",{className:"flex gap-2 mt-1",children:["median","trimmed","average"].map(s=>e.jsx(f,{type:"button",size:"sm",variant:q===s?"default":"outline",onClick:()=>Re(s),className:"capitalize",children:s==="trimmed"?"Trimmed mean (10%)":`${s} views`},s))}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Median is most realistic â average can be inflated by 1â2 viral reels."})]}),e.jsx("div",{className:"md:col-span-2 flex items-end",children:e.jsx(f,{onClick:()=>ue(),disabled:ne,className:"w-full",children:ne?e.jsxs(e.Fragment,{children:[e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"})," Analyzingâ¦"]}):"Analyze"})})]})})]}),n&&c&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(f,{onClick:Ee,disabled:L||!!X,variant:X?"outline":"default",children:[L?e.jsx(Y,{className:"h-4 w-4 mr-2 animate-spin"}):X?e.jsx(ds,{className:"h-4 w-4 mr-2 text-green-600"}):e.jsx(Fe,{className:"h-4 w-4 mr-2"}),X?"Saved":"Save analysis"]}),e.jsxs(f,{onClick:ze,variant:"outline",children:[e.jsx(ke,{className:"h-4 w-4 mr-2"})," Download Excel"]})]}),e.jsx(_,{children:e.jsx(R,{className:"pt-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 items-start",children:[n.profile.profilePicUrl&&e.jsx("img",{src:n.profile.profilePicUrl,alt:n.handle,className:"w-20 h-20 rounded-full object-cover border"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("h2",{className:"text-2xl font-bold",children:["@",n.handle]}),n.profile.verified&&e.jsx(Ks,{className:"h-5 w-5 text-blue-500"}),n.profile.isBusinessAccount&&e.jsx(T,{variant:"secondary",children:"Business"}),n.profile.category&&e.jsx(T,{variant:"outline",children:n.profile.category})]}),n.profile.fullName&&e.jsx("p",{className:"text-muted-foreground",children:n.profile.fullName}),n.audience.description&&e.jsx("p",{className:"mt-2 text-sm",children:n.audience.description})]})]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(ae,{icon:e.jsx(Ws,{className:"h-4 w-4"}),label:"Followers",value:v(n.metrics.followers)}),e.jsx(ae,{icon:e.jsx(Xs,{className:"h-4 w-4"}),label:"Engagement rate",value:`${n.metrics.engagementRate}%`,sub:ra(n.metrics.engagementRate)}),e.jsx(ae,{icon:e.jsx(Ce,{className:"h-4 w-4"}),label:"Median reel views",value:v(n.metrics.medianReelViews??0),sub:"typical reel"}),e.jsx(ae,{icon:e.jsx(Ce,{className:"h-4 w-4"}),label:"Trimmed mean (10%)",value:v(n.metrics.trimmedMeanReelViews??0),sub:"outliers dropped"}),e.jsx(ae,{icon:e.jsx(Ce,{className:"h-4 w-4"}),label:"Avg reel views",value:v(n.metrics.avgReelViews),sub:"can be skewed"}),e.jsx(ae,{icon:e.jsx(ls,{className:"h-4 w-4"}),label:"Avg likes",value:v(n.metrics.avgLikes)}),e.jsx(ae,{icon:e.jsx(is,{className:"h-4 w-4"}),label:"Avg comments",value:v(n.metrics.avgComments)}),e.jsx(ta,{icon:e.jsx(Ce,{className:"h-3 w-3"}),label:"Total reel views (lifetime)",value:v(n.metrics.totalReelViews),sub:`${n.metrics.reelsAnalyzed} reels`})]}),e.jsxs(_,{className:"border-primary/30",children:[e.jsxs(P,{className:"pb-3",children:[e.jsxs(F,{className:"text-base flex items-center gap-2",children:[e.jsx(es,{className:"h-4 w-4 text-primary"}
6)," Adjustments (recalculate live)"]}),e.jsx(U,{children:"Tune realism without re-running the scrape."})]}),e.jsxs(R,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(k,{htmlFor:"brandCredit",className:"flex items-center gap-1",children:["Brand value credit (USD)",e.jsx(se,{children:"Non-direct-response upside: usage rights, UGC, brand impressions, social proof. Suggested â $5 CPM à views à 30%."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{id:"brandCredit",type:"number",min:"0",step:"1",value:M,onChange:s=>je(s.target.value)}),e.jsxs(f,{type:"button",size:"sm",variant:"outline",onClick:()=>je(String(c.suggestedBrandCredit)),children:["Use ",y(c.suggestedBrandCredit)]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Adds to revenue in all scenarios."})]}),e.jsxs("div",{children:[e.jsxs(k,{className:"flex items-center gap-1",children:["Engagement-rate multiplier",e.jsx(se,{children:"ER â¥5% â CTR Ã1.3 · ER 1â5% â Ã1.0 · ER <1% â Ã0.7. Engaged audiences click more."})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(pe,{id:"applyEr",checked:ce,onCheckedChange:s=>Le(!!s)}),e.jsxs(k,{htmlFor:"applyEr",className:"font-normal cursor-pointer",children:["Apply ER multiplier â current: ",e.jsxs("span",{className:"font-semibold",children:["Ã",c.erMult.toFixed(2)]})," ","(ER ",n.metrics.engagementRate,"%)"]})]})]})]}),n.audience.viewerTypes.length>0&&e.jsxs("div",{children:[e.jsxs(k,{className:"flex items-center gap-1",children:[e.jsx(ns,{className:"h-3.5 w-3.5"})," In-ICP viewer segments",e.jsx(se,{children:"Only views from selected segments count toward conversion. Reflects that a 20K medical-student account is more valuable to a study tool than a 20K general-lifestyle account."})]}),e.jsx("div",{className:"flex flex-wrap gap-3 mt-2",children:n.audience.viewerTypes.map(s=>{const r=de[s.type]!==!1;return e.jsxs("label",{className:"flex items-center gap-2 text-sm border rounded-md px-2 py-1 cursor-pointer hover:bg-muted/50",children:[e.jsx(pe,{checked:r,onCheckedChange:d=>be(x=>({...x,[s.type]:!!d}))}),e.jsx("span",{className:"capitalize",children:s.type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(s.share*100),"%"]})]},s.type)})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Addressable share: ",e.jsxs("span",{className:"font-semibold",children:[Math.round(c.effIcpShare*100),"%"]})," of views (",v(c.addressableViews)," addressable / ",v(c.projectedViews)," total)."]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(cs,{title:"CPM verdict",verdict:c.cpm>0&&c.cpm<=(Number(D)||15),primary:`${y(c.cpm)} CPM`,detail:`Based on ${q} reel views (${v(c.perVideoViews)}/video à ${Math.round(os*100)}% sponsored reach). Total deal ${y(Number(w)||0)} / ${v(c.projectedViews)} projected views (${v(c.organicProjectedViews)} organic baseline).`}),e.jsx(cs,{title:"ROI verdict (base case)",verdict:c.scenarios.base.roi>=0,primary:`${c.scenarios.base.roi>=0?"+":""}${y(c.scenarios.base.roi)} (${c.scenarios.base.roiPct}%)`,detail:`${v(c.addressableViews)} addressable views à ${c.scenarios.base.ctr}% CTR = ${v(c.scenarios.base.clicks)} clicks à ${c.scenarios.base.paidConversion}% paid = ${v(c.scenarios.base.customers)} customers à ${y(c.scenarios.base.ltv)} LTV = ${y(c.scenarios.base.customerRevenue)}${Number(M)>0?` + ${y(Number(M))} brand credit`:""}. Cost ${y(Number(w)||0)}.`})]}),e.jsxs(_,{className:"border-amber-500/40",children:[e.jsxs(P,{className:"pb-2",children:[e.jsxs(F,{className:"text-base flex items-center gap-2",children:[e.jsx(ns,{className:"h-4 w-4 text-amber-600"})," Break-even (your negotiation targets)"]}),e.jsx(U,{children:"What would have to be true â holding everything else constant â to get to $0 ROI."})]}),e.jsx(R,{children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3 text-sm",children:[e.jsx(Be,{label:"Required CTR",value:isFinite(c.breakeven.requiredCtrPct)?`${c.breakeven.requiredCtrPct.toFixed(2)}
6%`:"N/A",hint:isFinite(c.breakeven.requiredCtrPct)?`vs your ${c.scenarios.base.ctr}% â ${c.breakeven.requiredCtrPct<=c.scenarios.base.ctr?"achievable":"would need to outperform"}`:"Set conv % and LTV first"}),e.jsx(Be,{label:"Required LTV",value:isFinite(c.breakeven.requiredLtv)&&c.breakeven.requiredLtv>0?y(c.breakeven.requiredLtv):"N/A",hint:isFinite(c.breakeven.requiredLtv)&&c.breakeven.requiredLtv>0?`vs your ${y(Number(B)||0)} â ${c.breakeven.requiredLtv<=(Number(B)||0)?"achievable":"would need higher-value customers"}`:"Set CTR and conv % first"}),e.jsx(Be,{label:"Max deal price",value:y(c.breakeven.maxCost),hint:`vs your ${y(Number(w)||0)} â ${c.breakeven.maxCost>=(Number(w)||0)?"you have headroom":`negotiate down ~${y(Math.max(0,(Number(w)||0)-c.breakeven.maxCost))}`}`})]})})]}),e.jsxs(_,{children:[e.jsxs(P,{children:[e.jsx(F,{className:"text-lg",children:"Scenario range (low / base / high)"}),e.jsx(U,{children:"Influencer performance is wildly variable. Low scales CTR Ã0.5 / paid Ã0.75 / LTV Ã0.67; high scales Ã1.5 / Ã1.25 / Ã1.33."})]}),e.jsx(R,{children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:["low","base","high"].map(s=>{const r=c.scenarios[s],d=r.roi>=0;return e.jsxs("div",{className:`rounded-lg border p-3 ${d?"border-green-500/40":"border-red-500/40"}`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:s}),e.jsx(T,{variant:d?"default":"destructive",className:d?"bg-green-500/15 text-green-700 dark:text-green-400 border-green-500/30":"",children:d?"Profitable":"Not profitable"})]}),e.jsxs("div",{className:"text-xl font-bold",children:[r.roi>=0?"+":"",y(r.roi)]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[r.roiPct,"% ROI"]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-2 space-y-0.5",children:[e.jsxs("div",{children:["CTR ",r.ctr,"% · Paid ",r.paidConversion,"% · LTV ",y(r.ltv)]}),e.jsxs("div",{children:[v(r.clicks)," clicks â ",v(r.customers)," customers"]}),e.jsxs("div",{children:["Revenue ",y(r.revenue),Number(M)>0?` (incl. ${y(Number(M))} brand)`:""]})]})]},s)})})})]}),n.audience.viewerTypes.length>0&&e.jsxs(_,{children:[e.jsxs(P,{children:[e.jsx(F,{className:"text-lg",children:"Likely viewer types"}),e.jsx(U,{children:"AI-inferred from bio + recent captions. Approximate, not verified demographics. Toggle ICP fit above."})]}),e.jsx(R,{className:"space-y-3",children:n.audience.viewerTypes.map((s,r)=>e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between text-sm mb-1",children:[e.jsx("span",{className:"font-medium capitalize",children:s.type}),e.jsxs("span",{className:"text-muted-foreground",children:[Math.round(s.share*100),"%"]})]}),e.jsx("div",{className:"w-full bg-muted h-2 rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${Math.min(100,s.share*100)}%`}})}),s.reason&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:s.reason})]},r))})]}),n.metrics.topReels.length>0&&e.jsxs(_,{children:[e.jsx(P,{children:e.jsx(F,{className:"text-lg",children:"Top reels by views"})}),e.jsx(R,{className:"space-y-3",children:n.metrics.topReels.map((s,r)=>e.jsxs("div",{className:"border rounded p-3",children:[e.jsxs("div",{className:"flex justify-between gap-4 text-sm",children:[e.jsxs("div",{className:"flex gap-4 text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ce,{className:"h-3 w-3"}),v(s.views)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ls,{className:"h-3 w-3"}),v(s.likes)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(is,{className:"h-3 w-3"}),v(s.comments)]})]}),s.url&&e.jsx("a",{href:s.url,target:"_blank",rel:"noreferrer",className:"text-primary text-xs hover:underline",children:"View"})]}),s.caption&&e.jsx("p",{className:"text-sm mt-2 line-clamp-2 text-foreground/80",children:s.caption})]},r))})]})]}),e.jsxs(_,{className:"mt-8",children:[e.jsxs(P,{className:"flex flex-row items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(F,{className:"flex items-center gap-2",children:[e.jsx(Ys,{className:"h-5 w-5"})," Saved analyses"]}),e.jsxs(U,{children:[E.length," saved · Click a row to reopen."]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(k,{className:"text-xs text-muted-foreground",children:"Sort by"}),e.jsxs("select",{value:Q,onChange:s=>we(s.target.value),className:"h-9 rounded-md border border-input bg-background px-2 text-sm",children:[e.jsx("option",{value:"date",children:"Date saved"}),e.jsx("option",{value:"followers",children:"Follower count"}),e.jsx("option",{value:"engagement",children:"Engagement rate"}),e.jsx("option",{value:"ratePerVideo",children:"Per-video price"}),e.jsx("option",{value:"medianViews",children:"Median reel views"}
6),e.jsx("option",{value:"avgLikes",children:"Average likes"}),e.jsx("option",{value:"roiUsd",children:"Base ROI ($)"}),e.jsx("option",{value:"roiPct",children:"Base ROI (%)"})]}),e.jsx(f,{variant:"outline",size:"sm",onClick:()=>$e(ee==="asc"?"desc":"asc"),title:ee==="asc"?"Ascending":"Descending",children:ee==="asc"?"â Asc":"â Desc"}),e.jsxs(f,{onClick:a,variant:"outline",size:"sm",disabled:!E.length,children:[e.jsx(ke,{className:"h-4 w-4 mr-2"})," Download all"]})]})]}),e.jsx(R,{children:E.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No saved analyses yet."}):e.jsx("div",{className:"divide-y",children:Ie.map(s=>e.jsxs("div",{className:"flex items-center justify-between py-3 gap-3",children:[e.jsxs("button",{onClick:()=>i(s),className:"flex-1 text-left hover:opacity-80",children:[e.jsxs("div",{className:"font-medium",children:["@",s.handle]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[v(s.result.metrics.followers)," followers · ER ",s.result.metrics.engagementRate,"% · ROI ",s.result.profitability.roiPct,"% · ",new Date(s.created_at).toLocaleDateString()]})]}),e.jsx(T,{variant:s.result.profitability.roiVerdict==="profitable"?"default":"destructive",children:s.result.profitability.roiVerdict}),e.jsx(f,{variant:"outline",size:"sm",onClick:()=>window.open(`https://instagram.com/${s.handle.replace(/^@/,"")}`,"_blank","noopener,noreferrer"),title:"Open Instagram profile",children:e.jsx(He,{className:"h-3 w-3"})}),e.jsx(f,{variant:"outline",size:"sm",onClick:()=>Me(s),children:e.jsx(ke,{className:"h-3 w-3"})}),e.jsx(f,{variant:"outline",size:"sm",onClick:()=>l(s.id),children:e.jsx(Ae,{className:"h-3 w-3"})})]},s.id))})})]})]})]})]})})}function ra(m){return m>=5?"exceptional":m>=3?"strong":m>=1?"average":"low"}function se({children:m}){return e.jsxs(Ts,{children:[e.jsx(Vs,{asChild:!0,children:e.jsx("button",{type:"button",className:"inline-flex","aria-label":"More info",children:e.jsx(Js,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-foreground"})})}),e.jsx(Ps,{className:"max-w-xs text-xs",children:m})]})}function ae({icon:m,label:g,value:b,sub:j}){return e.jsx(_,{children:e.jsxs(R,{className:"pt-4 pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[m,g]}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:b}),j&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j})]})})}function ta({icon:m,label:g,value:b,sub:j}){return e.jsx(_,{className:"opacity-70",children:e.jsxs(R,{className:"pt-3 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground",children:[m,g]}),e.jsx("div",{className:"text-sm font-medium mt-0.5",children:b}),j&&e.jsx("div",{className:"text-[11px] text-muted-foreground",children:j})]})})}function Be({label:m,value:g,hint:b}){return e.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3",children:[e.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:m}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:g}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:b})]})}function cs({title:m,verdict:g,primary:b,detail:j}){return e.jsxs(_,{className:g?"border-green-500/40":"border-red-500/40",children:[e.jsx(P,{className:"pb-2",children:e.jsxs(F,{className:"text-sm flex items-center gap-2",children:[e.jsx(Zs,{className:"h-4 w-4"}),m,g?e.jsxs(T,{className:"bg-green-500/15 text-green-700 dark:text-green-400 border-green-500/30 ml-auto",children:[e.jsx(ds,{className:"h-3 w-3 mr-1"})," Profitable"]}):e.jsxs(T,{variant:"destructive",className:"ml-auto",children:[e.jsx(Qs,{className:"h-3 w-3 mr-1"})," Not profitable"]})]})}),e.jsxs(R,{children:[e.jsx("div",{className:"text-2xl font-bold mb-1",children:b}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j})]})]})}function qe(m){const g=V.book_new(),b=m.map(N=>{const t=N.result;return{Handle:t.handle,"Saved At":new Date(N.created_at).toLocaleString(),"Full Name":t.profile.fullName,Verified:t.profile.verified?"Yes":"No",Category:t.profile.category,Followers:t.metrics.followers,Following:t.metrics.following,Posts:t.metrics.postsCount,"Reels Analyzed":t.metrics.reelsAnalyzed,"Engagement Rate %":t.metrics.engagementRate,"Total Reel Views":t.metrics.totalReelViews,"Avg Reel Views":t.metrics.avgReelViews,"Median Reel Views":t.metrics.medianReelViews??0,"Trimmed Mean Reel Views (10%)":t.metrics.trimmedMeanReelViews??0,"ROI Basis":t.profitability.viewsBasis??"median","Per-Video Views Used":t.profitability.perVideoViews??t.metrics.avgReelViews,"Avg Likes":t.metrics.avgLikes,"Avg Comments":t.metrics.avgComments,"Rate Per Video (USD)":t.inputs.ratePerVideo,"Number of Videos":t.inputs.numVideos??1,"Total Deal Cost (USD)":t.profitability.totalCost??t.input
6s.ratePerVideo,"Target CPM (USD)":t.inputs.targetCpm,"CTR % (viewsâclicks)":t.inputs.ctr??0,"Paid Conversion % (clicksâpaid)":t.inputs.paidConversion??0,"LTV (USD/customer)":t.inputs.ltv??0,"Projected Customers (base)":t.profitability.projectedCustomers??t.profitability.projectedSubscribers??0,"Customer Revenue (USD, base)":t.profitability.customerRevenue??t.profitability.subscriptionRevenue??0,"Projected Total Views":t.profitability.projectedViews,"CPM (USD)":t.profitability.cpm,"CPM Verdict":t.profitability.cpmVerdict,"Projected Revenue (Base, USD)":t.profitability.projectedRevenue,"ROI Base (USD)":t.profitability.roi,"ROI Base %":t.profitability.roiPct,"ROI Base Verdict":t.profitability.roiVerdict,"ROI Low (USD)":t.profitability.scenarios?.low.roi??"","ROI High (USD)":t.profitability.scenarios?.high.roi??"","Audience Description":t.audience.description,Biography:t.profile.biography}});V.book_append_sheet(g,V.json_to_sheet(b),"Summary");const j=m.flatMap(N=>N.result.audience.viewerTypes.map(t=>({Handle:N.result.handle,"Viewer Type":t.type,"Share %":Math.round(t.share*100),Reason:t.reason})));j.length&&V.book_append_sheet(g,V.json_to_sheet(j),"Viewer Types");const I=m.flatMap(N=>N.result.metrics.topReels.map((t,w)=>({Handle:N.result.handle,Rank:w+1,Views:t.views,Likes:t.likes,Comments:t.comments,URL:t.url,Caption:t.caption})));return I.length&&V.book_append_sheet(g,V.json_to_sheet(I),"Top Reels"),g}export{$a 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.