PageSourceSearch

https://leadfo.net/assets/js/AdminBrain-B6pdXU6w.js

js leadfo.net collected 2026-10-02 02:03:27 UTC 92,741 bytes, 47 lines download raw bytes

1import{j as e}from"./vendor-ui-CRQIGnoB.js";import{u as Xe}from"./useAdminRole-CHXnWkJv.js";import{r as a,u as Ze}from"./vendor-react--DiKkAFz.js";import{T as Me,a as Be,b as J,c as Q}from"./tabs-BZ_Hg_7Y.js";import{c as Ce,B as L,a as U,A as es,C as ss}from"./index-DKzuHz-e.js";import{supabase as p}from"./client-D7mlWhIv.js";import{T as Z}from"./textarea-DtarV0hT.js";import{S as ne}from"./switch-CsDFi0S1.js";import{L as G}from"./label-Bvwq5u11.js";import{u as k}from"./index-rh__xJsb.js";import{I as K}from"./input-CsHnqZ-f.js";import{F as ts}from"./flask-conical-qvVhGvDl.js";import{L as M}from"./loader-circle-_eZHlf3P.js";import{R as as}from"./rotate-ccw-_x6cI-wn.js";import{S as fe}from"./QuestStyleToaster-C1pQ2YzM.js";import{P as oe}from"./plus-Bwtmv8ej.js";import{S as rs}from"./slider-BwGlVAqz.js";import{B}from"./badge-B2Kty1G_.js";import{S as me,a as ue,b as he,c as pe,d as X}from"./select-uI15hmYd.js";import{n as Y,_ as He,k as ns,$ as is,a0 as ls,a1 as os,a2 as cs,a3 as ds}from"./AuthenticatedRoutes-Di8y_Ywx.js";import{D as Ge,a as Ue,b as ze,c as Ve,g as qe}from"./dialog-BXeUR9Gc.js";import{G as $e}from"./graduation-cap-DAyarHph.js";import{F as Te}from"./file-text-BrhZqGuH.js";import{L as ge}from"./link-2-DYzqkA9d.js";import{D as se}from"./dna-ZNc9gfL3.js";import{C as ie}from"./circle-check-OtpnxEOD.js";import{G as xs}from"./globe-DRWHHQi1.js";import{C as We}from"./chevron-up-CCCTrkSK.js";import{C as ce}from"./chevron-down-DtzUPheO.js";import{T as te}from"./trash-2-B15HZ70d.js";import{B as le}from"./book-open-gdHOso_D.js";import{S as Ke}from"./sparkles-BYDvd4vJ.js";import{R as ms,a as us,b as hs}from"./index-DShmwIVv.js";import{E as Ee}from"./external-link-CA4nOhER.js";import{T as ps}from"./target-Cdg_rrt0.js";import{M as gs}from"./message-square-BbhJeTrn.js";import{S as Oe}from"./shield-_1Q6smv4.js";import{L as Pe}from"./lock-BiwWO-pO.js";import{C as fs,a as bs}from"./card-C6jCfsGf.js";import{R as ys}from"./rocket-CweN3l9F.js";import{C as js}from"./circle-x-C4Id_eNJ.js";import{R as Ns}from"./radar-BZwAlqe3.js";import"./AuthContext-Bw19ogwi.js";import"./vendor-three-DHH5iuE3.js";import"./vendor-query-CUxQGtou.js";import"./vendor-meta-Ci6Y53GW.js";import"./vendor-supabase-ClyXdaUN.js";import"./index-BGJlT0Sb.js";import"./check-gLMtDS4p.js";import"./phone-BpDuHigr.js";import"./user-BTW-69R4.js";import"./useUserSettings-Dv0KIzaK.js";import"./use-toast-9UZXZbzH.js";import"./useOnboardingQuests-CPuvlv4z.js";import"./format-CoscEkXf.js";import"./calendar-D8VBoCoj.js";import"./sliders-horizontal-bW_YgasM.js";import"./gem-B5Sp2YAH.js";import"./settings-CdjbkSPD.js";import"./credit-card-KubWseqJ.js";import"./map-02rIzUMt.js";import"./search-Ci1dqr_v.js";import"./building-2-BGtcrsNn.js";import"./clock-BwRKgzwY.js";import"./SpaceParticles-keNnA6K2.js";import"./QuestProgressPopup-GqSQXCkc.js";import"./vendor-motion-B0Q0Uqko.js";import"./crosshair-CETFjznb.js";import"./use-mobile-Dpdczg8-.js";import"./circle-alert-D8wrFPsk.js";import"./ranks-YtEk-z_o.js";import"./RankLogo-CY8Yzan5.js";import"./arrow-left-CgsGrqs4.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 vs=Ce("Beaker",[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]]);/**
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 ws=Ce("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/**
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 _s=Ce("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]),V=`
17[SUBORDINATION: This style is a FLAVOR layer. It NEVER overrides structural rules. Priority chain: Heartbeat Structure (sentence length asymmetry) > Single Question > Continuity Starters > Reality Pivot > Native Digital Voice > Social Status > Bridge Mirror > Continuous Thought > Strategic Pain > THIS STYLE. If this style pushes toward balanced/flowing sentence lengths, the Heartbeat pattern (SHORT→LONG→VERY SHORT) WINS.]`,Ss="";function ks(r){const c={friendly:`**FRIENDLY TONE** — Warm, approachable, uses contractions. Like texting a colleague you grab coffee with.
18SYNTAX: Contractions always. Casual filler ("just", "kinda", "super") OK sparingly.
19GREETING: "Hey!!", "Hey [Name]!!" — "!!" for energy, zero emojis. BANNED: "Salut" (too formal-casual mismatch).
20VOICE: Spontaneous, grounded in specific observation.
21CTA PUNCTUATION: End questions with "?" only. NEVER "!!". "!!" is exclusively for greetings.`+V,professional:`**PROFESSIONAL TONE** — Polished, respectful, direct. Active verb
21s, minimal hedging.
22SYNTAX: Zero fluff. Strong active verbs. Complete sentences.
23GREETING: "Hi [Name]," (never "Hey")
24VOICE: Authoritative peer DM, NOT a LinkedIn comment. Sharp observations, clinical close.
25CTA PUNCTUATION: End questions with "?" only. NEVER "!!".`+V,empathetic:`**EMPATHETIC TONE** — Understanding through specificity, not formula.
26SYNTAX: Focus on feelings/struggles. Longer supportive sentences.
27GREETING: "Hi [Name]!!", "Hey [Name]!!"
28VOICE: Validate their specific challenge. Gentle question.
29CTA PUNCTUATION: End questions with "?" only. NEVER "!!". "!!" is exclusively for greetings.`+V};return c[r]||c.friendly}function Cs(r){const c={conversation_starter:`**CONVERSATION STARTER** — Zero selling. Pure networking.
30HOOK: Specific verifiable observation. BRIDGE: MIRROR what the prospect experiences, don't advise or share. No product mention.
31CTA: Process question, trend opinion, challenge insight, or hypothesis about their situation, but it MUST stay tied to a pain the sender's offer actually solves. If the prospect is early stage or has fewer than 500 followers, never invent DM triage, saturation, or audience-scale pain. BANNED: Product mention, unrelated operational pain.`+V,partnership:`**PARTNERSHIP** — Mutually beneficial collaboration.
32HOOK: Their specific strength creating opportunity. BRIDGE: Value Bridge explaining bottleneck you solve.
33CTA: Natural collaboration proposal. BANNED: "Win-win", "Synergy", generic partnership language.`+V};return c[r]||c.conversation_starter}function Ts(r){const c={stealth_mode:`**STEALTH MODE** — 100% problem-focused.
34BRIDGE has NO product mention. Pure value-add. The hidden pain can still be linked to what the sender solves, but never drift into generic creator pains like DM triage unless that is the actual offer. BANNED: Any company/product/solution mention.`+V,subtle_mention:`**SUBTLE MENTION** — Hint without naming.
35BRIDGE uses indirect language. BANNED: Naming product/service directly.`+V,feature_highlight:`**FEATURE HIGHLIGHT** — Clear capability showcase.
36BRIDGE names product/service with concrete features and benefits.`+V};return c[r]||c.stealth_mode}function Es(r){const c={curiosity_gap:`**CURIOSITY GAP** — Tease without revealing. Open loop they MUST close.
37STRATEGIC ALIGNMENT: Use the prospect's businessAnalysis to identify WHICH information gap to create. The gap must relate to a problem the SENDER'S business can solve.
38Respect SOCIAL STATUS ALIGNMENT: calibrate the gap to the prospect's follower tier.
39CRAFT EVERY PHRASE FROM SCRATCH.`+V,pain_agitation:`**PAIN AGITATION** — Surface hidden struggles. Cost of inaction.
40STRATEGIC PAIN MAPPING: The pain you surface MUST be the specific frustration that the SENDER'S business or offer can solve. Use businessAnalysis + the sender's businessContext to identify WHICH pain to target. Generic pain = failure.
41Respect SOCIAL STATUS ALIGNMENT: Hustler (<500) = credibility, first traction, first qualified conversations. Grower (500-5k) = irregular results/manual prospecting. Authority (>5k) = filtering/noise. NEVER talk about DM triage, volume, influx, or attracting more people to a Hustler unless the sender explicitly sells audience growth.
42CRAFT EVERY PHRASE FROM SCRATCH.`+V};return c[r]||c.curiosity_gap}const Is="",Rs="",As=({activeLaws:r})=>{const[c,_]=a.useState(""),w=a.useMemo(()=>{const o=[],u=r.map(n=>n.rule_content).join(`
43`);o.push({regex:/[—–]/g,rule:"Em-dash banned"}),o.push({regex:/"[^"]{3,}"/g,rule:"Quotation marks around references"});const i=u.match(/BANNED WORDS?:\s*([^\n.]+)/i);i&&i[1].split(/,\s*/).map(f=>f.trim().replace(/\.$/,"")).forEach(f=>{f.length>
432&&o.push({regex:new RegExp(`\\b${f.replace(/-/g,"[-\\s]?")}\\b`,"gi"),rule:`Banned word: ${f}`})});const d=u.match(/BANNED OPENERS?:\s*([^\n]+(?:\n(?!\d)[^\n]+)*)/i);return d&&d[1].split(/",\s*"/).map(f=>f.replace(/^["']|["']$/g,"").trim()).forEach(f=>{f.length>5&&o.push({regex:new RegExp(f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),rule:"Banned opener"})}),o.push({regex:/^-\s/gm,rule:"Hyphen list banned"}),o.push({regex:/(?:^I\s[^\n]*\n){3,}/gm,rule:'3+ consecutive "I" starters'}),o},[r]),l=a.useMemo(()=>{if(!c.trim())return[];const o=[];return w.forEach(({regex:u,rule:i})=>{const d=new RegExp(u.source,u.flags);let n;for(;(n=d.exec(c))!==null;)o.push({pattern:n[0],index:n.index,length:n[0].length,rule:i})}),o.sort((u,i)=>u.index-i.index)},[c,w]),b=a.useMemo(()=>{if(!c||l.length===0)return null;const o=[];let u=0;return l.forEach(i=>{i.index>=u&&(o.push(xe(c.slice(u,i.index))),o.push(`<mark class="bg-red-500/30 text-red-300 rounded px-0.5" title="${xe(i.rule)}">${xe(c.slice(i.index,i.index+i.length))}</mark>`),u=i.index+i.length)}),o.push(xe(c.slice(u))),o.join("")},[c,l]);return e.jsxs("div",{className:"rounded-xl border border-violet-500/20 bg-violet-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ts,{className:"w-4 h-4 text-violet-400"}),e.jsx("h3",{className:"text-sm font-semibold text-violet-300",children:"Test Lab"}),l.length>0&&e.jsxs("span",{className:"ml-auto text-xs px-2 py-0.5 rounded-full bg-red-500/20 text-red-300",children:[l.length," violation",l.length>1?"s":""]})]}),e.jsx(Z,{value:c,onChange:o=>_(o.target.value),placeholder:"Paste a draft message here to check for Iron Law violations...",className:"min-h-[100px] bg-black/30 border-white/10 text-sm resize-y"}),b&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Violations highlighted:"}),e.jsx("div",{className:"p-3 rounded-lg bg-black/40 border border-white/10 text-sm text-foreground whitespace-pre-wrap break-words leading-relaxed",dangerouslySetInnerHTML:{__html:b}}),e.jsx("div",{className:"space-y-1",children:[...new Set(l.map(o=>o.rule))].map(o=>e.jsxs("p",{className:"text-xs text-red-400",children:["⚠ ",o]},o))})]}),c.trim()&&l.length===0&&e.jsx("p",{className:"text-xs text-emerald-400",children:"✅ No violations detected"})]})};function xe(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}const Ds={universal_iron_laws:Ss,human_rhythm_english:Is,human_rhythm_universal:Rs},Ls=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!0),[l,b]=a.useState(null),[o,u]=a.useState(""),i=a.useCallback(async()=>{w(!0);const{data:m,error:y}=await p.from("brain_iron_laws").select("*").order("rule_key");y?(console.error("Error fetching iron laws:",y),k.error("Failed to load Iron Laws")):c(m||[]),w(!1)},[]);a.useEffect(()=>{i()},[i]);const d=async()=>{const{data:{user:m}}=await p.auth.getUser();if(m){for(const[y,I]of Object.entries(Ds))r.find(g=>g.rule_key===y)||await p.from("brain_iron_laws").insert({rule_key:y,rule_content:I,is_active:!0,updated_by:m.id});k.success("Default Iron Laws seeded"),i()}},n=async m=>{b(m.id);const{data:{user:y}}=await p.auth.getUser(),{error:I}=await p.from("brain_iron_laws").update({rule_content:m.rule_content,is_active:m.is_active,updated_at:new Date().toISOString(),updated_by:y?.id}).eq("id",m.id);I?k.error("Failed to save"):k.success(`"${m.rule_key}" saved`),b(null)},f=async m=>{const y={...m,is_active:!m.is_active};c(I=>I.map(P=>P.id===m.id?y:P)),n(y)},x=(m,y)=>{c(I=>I.map(P=>P.id===m?{...P,rule_content:y}:P))},E=async()=>{if(!o.trim())return;const m=o.trim().toLowerCase().replace(/\s+/g,"_"),{data:{user:y}}=await p.auth.getUser(),{error:I}=await p.from("brain_iron_laws").insert({rule_key:m,rule_content:"",is_active:!0,updated_by:y?.id});I?k.error(I.message.includes("unique")?"Rule key already exists":"Failed to add rule"):(u(""),i())},R=a.useMemo(()=>r.filter(m=>m.is_active),[r]);return _?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(M,{className:"w-6 h-6 animate-spin text-violet-400"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.length," rules • ",R.length," active"]}),e.jsxs(L,{onClick:d,variant:"outline",size:"sm",className:"border-violet-500/30 text-violet-300 hover:bg-violet-500/10",children:[e.jsx(as,{className:"w-4 h-4 mr-2"}),"Seed from StyleBible.ts"]})]}),e.jsx("div",{className:"space-y-4",children:r.map(m=>e.jsxs("div",{className:"rounded-xl border p-4 space-y-3",style:{background:m.is_active?"rgba(139, 92, 246, 0.05)":"rgba(255,255,255,0.02)",borderColor:m.is_active?"rgba(139, 92, 246, 0.2)":"rgba(255,255,255,0.1)"},children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ne,{checked:m.is_active,onCheckedChange:()=>f(m)}),e.jsx(G,{className:"text-sm font-mono text-violet-300",children:m.rule_key})]}),e.jsxs(L,{size:"sm",onClick:()=>n(m),disabled:l===m.id,className:"bg-violet-500/20 text-violet-300 hover:bg-violet-500/30 border border-violet-500/30",children:[l===m.id?e.jsx(M,{className:"w-3 h-3 animate-spin"}):e.jsx(fe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1.5 text-xs",children:"Save"})]})]}),e.jsx(Z,{value:m.rule_content,onChange:y=>x(m.id,y.target.value),className:"min-h-[140px] bg-black/30 border-white/10 font-mono text-xs resize-y",disabled:!m.is_active})]},m.id))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(K,{placeholder:"New rule key (e.g., mode_stealth)",value:o,onChange:m=>u(m.target.value),className:"bg-white/5 border-white/10 font-mono text-sm",onKeyDown:m=>m.key==="Enter"&&E()}),e.jsx(L,{onClick:E,disabled:!o.trim(),size:"sm",className:"bg-violet-500/20 text-violet-300 hover:bg-violet-500/30 border border-violet-500/30",children:e.jsx(oe,{className:"w-4 h-4"})})]}),e.jsx(As,{activeLaws:R})]})},Os=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!1),l=a.useCallback(async()=>{w(!0);try{const{data:u,error:i}=await p.from("custom_style_templates").select("*").order("created_at",{ascending:!1});if(i)throw i;c(u||[])}catch(u){console.error("Error fetching custom style templates:",u)}finally{w(!1)}},[]);a.useEffect(()=>{l()},[l]);const b=a.useCallback(async u=>{try{const{data:{user:i}}=await p.auth.getUser();if(!i)throw new Error("Not authenticated");const{data:d,error:n}=await p.from("custom_style_templates").insert({user_id:i.id,name:u.name,syntax_dna:u.syntax_dna,logic_rules:u.logic_rules,training_samples:u.training_samples,source_urls:u.source_urls,base_tone_map:u.base_tone_map,voice_summary:u.voice_summary}).select().single();if(n)throw n;return await l(),k.success(`"${u.name}" saved to your style library.`),d}catch(i){throw console.error("Error saving custom style:",i),k.error("Failed to save style. Please try again."),i}},[l]),o=a.useCallback(async u=>{try{const d=r.find(f=>f.id===u)?.syntax_dna?.learning_id;d&&await p.from("brain_knowledge_snippets").delete().eq("learning_id",d);const{error:n}=await p.from("custom_style_templates").delete().eq("id",u);if(n)throw n;c(f=>f.filter(x=>x.id!==u)),k.success("Trained style deleted.")}catch(i){console.error("Error deleting custom style:",i),k.error("Failed to delete style.")}},[r]);return{templates:r,isLoading:_,fetchTemplates:l,saveTemplate:b,deleteTemplate:o}},Ps=({isOpen:r,onClose:c,isAdminMode:_=!1,onSaveComplete:w})=>{Os();
43const[l,b]=a.useState("text"),[o,u]=a.useState(""),[i,d]=a.useState(""),[n,f]=a.useState("capture"),[x,E]=a.useState(""),[R,m]=a.useState(!1),[y,I]=a.useState(!1),[P,g]=a.useState(!1),[v,F]=a.useState(!1),[s,h]=a.useState(null),[C,T]=a.useState(null),[t,S]=a.useState(""),[A,j]=a.useState(""),H=()=>{f("capture"),u(""),d(""),E(""),h(null),T(null),S(""),j(""),m(!1),I(!1),g(!1)},ae=()=>{H(),c()},q=async()=>{let D="",z="";if(l==="url"){if(!i.trim())return;z=i.trim(),m(!0),f("analyzing");try{const{data:N,error:O}=await p.functions.invoke("firecrawl-scrape",{body:{url:z,options:{formats:["markdown"],onlyMainContent:!0}}});if(O||!N?.success)throw new Error(N?.error||"Scraping failed");if(D=N.data?.markdown||N.markdown||"",!D||D.length<50)throw new Error("Not enough content scraped from URL")}catch(N){console.error("Scraping error:",N),f("capture"),m(!1);return}m(!1)}else{if(o.trim().length<50)return;D=o.trim(),f("analyzing")}S(D),j(z),I(!0);try{const{data:{session:N}}=await p.auth.getSession();if(!N?.access_token)throw new Error("Not authenticated");const{data:O,error:W}=await p.functions.invoke("extract-style-dna",{body:{text:D}});if(W||!O?.success)throw new Error(O?.error||"DNA extraction failed");h(O),E(O.base_tone_map?`${O.base_tone_map} Style`:"My Custom Style")}catch(N){console.error("DNA extraction error:",N),f("capture"),I(!1);return}I(!1),g(!0);try{const{data:N,error:O}=await p.functions.invoke("extract-style-rules",{body:{text:D}});if(O||!N?.success)throw new Error(N?.error||"Rule extraction failed");T(N)}catch(N){console.error("Rules extraction error:",N),T({logic_rules:[]})}g(!1),f("validation")},[$,be]=a.useState(_),ye=async()=>{if(!(!x.trim()||!s)){F(!0);try{const D=$?`[Global] ${x.trim()}`:x.trim(),{data:{user:z}}=await p.auth.getUser();if(!z)throw new Error("Not authenticated");const{error:N}=await p.from("custom_style_templates").insert({user_id:z.id,name:D,syntax_dna:s.syntax_dna,logic_rules:C?.logic_rules||[],training_samples:[t],source_urls:A?[A]:[],base_tone_map:s.base_tone_map,voice_summary:s.voice_summary,is_global:$});if(N)throw N;k.success(`"${D}" saved to style library.`),w?.(),ae()}catch{k.error("Failed to save style.")}finally{F(!1)}}},je=C?.logic_rules?.reduce((D,z)=>{const N=z.section_target||"global";return D[N]=(D[N]||0)+1,D},{})||{};return e.jsx(Ge,{open:r,onOpenChange:D=>!D&&ae(),children:e.jsxs(Ue,{className:"sm:max-w-[560px] bg-[#0F1115] border-white/10 max-h-[90vh] overflow-y-auto",children:[e.jsxs(ze,{children:[e.jsxs(Ve,{className:"flex items-center gap-2",children:[e.jsx($e,{className:"w-5 h-5 text-violet-400"}),"Style Trainer"]}),e.jsx(qe,{children:"Teach the AI a new writing style from any blog, article, or script."})]}),n==="capture"&&e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"flex gap-2 p-1 bg-white/5 rounded-xl",children:[e.jsxs("button",{onClick:()=>b("text"),className:U("flex-1 flex items-center justify-center gap-2 py-2 rounded-lg text-sm font-medium transition-all",l==="text"?"bg-violet-500/20 text-violet-300 ring-1 ring-violet-500/30":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Te,{className:"w-4 h-4"}),"Paste Text"]}),e.jsxs("button",{onClick:()=>b("url"),className:U("flex-1 flex items-center justify-center gap-2 py-2 rounded-lg text-sm font-medium transition-all",l==="url"?"bg-violet-500/20 text-violet-300 ring-1 ring-violet-500/30":"text-muted-foreground hover:text-foreground"),children:[e.jsx(ge,{className:"w-4 h-4"}),"Paste URL"]})]}),l==="text"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs text-muted-foreground",children:"Paste a blog post, article, YouTube script, or any writing sample (min 50 chars)"}),e.jsx(Z,{value:o,onChange:D=>u(D.target.value),placeholder:"Paste your content here...",className:"min-h-[200px] bg-white/5 border-white/10 resize-none"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[o.length," characters"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs text-muted-foreground",children:"Enter the URL of a blog post or article"}),e.jsx(K,{value:i,onChange:D=>d(D.target.value),placeholder:"https://example.com/blog-post",className:"bg-white/5 border-white/10"})]}),e.jsxs(L,{onClick:q,disabled:l==="text"?o.trim().length<50:!i.trim(),className:"w-full bg-gradient-to-r from-violet-500 to-indigo-500 hover:from-violet-600 hover:to-indigo-600",children:[e.jsx(se,{className:"w-4 h-4 mr-2"}),"Analyze Writing Style"]})]}),n==="analyzing"&&e.jsxs("div",{className:"space-y-4 py-6",children:[e.jsx(ve,{icon:ge,label:"Scraping content...",isLoading:R,isDone:!R&&l==="url",show:l==="url"}),e.jsx(ve,{icon:se,label:"Extracting syntax DNA...",isLoading:y,isDone:!!s,show:!R}),e.jsx(ve,{icon:Y,label:"Analyzing strategic rules...",isLoading:P,isDone:!!C,show:!!s})]}),n==="validation"&&s&&e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{children:"Style Name"}),e.jsx(K,{value:x,onChange:D=>E(D.target.value),placeholder:"e.g., Alex Hormozi Style",className:"bg-white/5 border-white/10"})]}),e.jsxs("div",{className:"p-4 rounded-xl bg-white/5 border border-white/10 space-y-3",children:[e.jsxs("p",{className:"text-sm text-foreground italic",children:['"',s.voice_summary,'"']}),e.jsxs(B,{variant:"outline",className:"border-violet-500/30 text-violet-300",children:["Base Tone: ",s.base_tone_map]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(we,{label:"Avg Length",value:`${s.syntax_dna?.rhythm?.avg_sentence_length||0}w`}),e.jsx(we,{label:"Formality",value:`${Math.round((s.syntax_dna?.vocabulary?.formality_score||0)*100)}%`}),e.jsx(we,{label:"Emoji",value:s.syntax_dna?.syntactic_signature?.punctuation_style?.emoji_density||"none"})]}),C&&C.logic_rules.length>0&&e.jsxs("div",{className:"p-3 rounded-xl bg-white/5 border border-white/10",children:[e.jsxs("p",{className:"text-xs text-muted-foreground mb-2",children:[C.logic_rules.length," strategic rules extracted"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(je).map(([D,z])=>e.jsxs("span",{className:"px-2 py-0.5 text-[10px] rounded bg-indigo-500/20 text-indigo-300",children:[D,": ",z]},D))})]}),_&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-violet-500/10 border border-violet-500/20",children:[e.jsx("input",{type:"checkbox",checked:$,onChange:D=>be(D.target.checked),className:"w-4 h-4 rounded border-white/20"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-violet-300",children:"Save as Global Style"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Applies to all users during generation"})]})]}),e.jsx(L,{onClick:ye,disabled:!x.trim()||v,className:"w-full bg-gradient-to-r from-violet-500 to-indigo-500",children:v?e.jsxs(e.Fragment,{children:[e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:"w-4 h-4 mr-2"}),$?"Save as Global Style":"Save to Style Library"]})})]})]})})};function ve({icon:r,label:c,isLoading:_,isDone:w,show:l}){return l?e.jsxs("div",{className:"flex items-center gap-3 px-2",children:[_?e.jsx(M,{className:"w-5 h-5 text-violet-400 animate-spin"}):w?e.jsx(ie,{className:"w-5 h-5 text-emerald-400"}
43):e.jsx(r,{className:"w-5 h-5 text-muted-foreground/50"}),e.jsx("span",{className:U("text-sm",_?"text-foreground":w?"text-emerald-300":"text-muted-foreground/50"),children:c})]}):null}function we({label:r,value:c}){return e.jsxs("div",{className:"p-3 rounded-lg bg-white/5 border border-white/10 text-center",children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:c}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:r})]})}const Fs=["hook","bridge","cta","global"],Ms=["General","Tone","Psychology","Product Integration","Objective","Format"],Bs=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!0),[l,b]=a.useState(null),[o,u]=a.useState(null),[i,d]=a.useState(!1),[n,f]=a.useState(null),x=a.useCallback(async()=>{w(!0);try{const{data:s,error:h}=await p.rpc("get_all_style_templates");if(h)throw h;c(s||[])}catch(s){console.error("Error fetching templates:",s),k.error("Failed to load style templates")}w(!1)},[]);a.useEffect(()=>{x()},[x]);const E=async s=>{u(s.id);const{error:h}=await p.from("custom_style_templates").update({syntax_dna:s.syntax_dna,logic_rules:s.logic_rules,is_global:s.is_global,name:s.name}).eq("id",s.id);h?k.error("Failed to save"):k.success(`"${s.name}" saved`),u(null)},R=async s=>{const{error:h}=await p.from("custom_style_templates").delete().eq("id",s);h?k.error("Failed to delete"):(c(C=>C.filter(T=>T.id!==s)),k.success("Style deleted"))},m=(s,h)=>{c(C=>C.map(T=>T.id===s?{...T,...h}:T))},y=(s,h,C)=>{c(T=>T.map(t=>{if(t.id!==s)return t;const S=JSON.parse(JSON.stringify(t.syntax_dna||{}));let A=S;for(let j=0;j<h.length-1;j++)A[h[j]]||(A[h[j]]={}),A=A[h[j]];return A[h[h.length-1]]=C,{...t,syntax_dna:S}}))},I=(s,h,C,T)=>{c(t=>t.map(S=>{if(S.id!==s)return S;const A=[...S.logic_rules||[]];return A[h]={...A[h],[C]:T},{...S,logic_rules:A}}))},P=r.length,g=r.filter(s=>s.is_global).length,v=r.reduce((s,h)=>{const C=h.base_tone_map||"Unknown";return s[C]=(s[C]||0)+1,s},{}),F=Object.entries(v).map(([s,h])=>({name:s,progress:Math.min(100,h*30)}));return _?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(M,{className:"w-6 h-6 animate-spin text-cyan-400"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs(L,{onClick:()=>d(!0),className:"w-full bg-gradient-to-r from-cyan-500 to-violet-500 hover:from-cyan-600 hover:to-violet-600",children:[e.jsx($e,{className:"w-4 h-4 mr-2"}),"Train from URL or Text"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(_e,{label:"Total Styles",value:P,color:"#22D3EE"}),e.jsx(_e,{label:"Global Styles",value:g,color:"#8B5CF6"}),e.jsx(_e,{label:"Tone Types",value:Object.keys(v).length,color:"#10B981"})]}),F.length>0&&e.jsxs("div",{className:"space-y-2 p-3 rounded-xl bg-white/5 border border-white/10",children:[e.jsx("p",{className:"text-xs font-semibold text-emerald-300",children:"Industry Knowledge"}),F.map(({name:s,progress:h})=>e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-[11px] text-muted-foreground",children:s}),e.jsxs("span",{className:"text-[11px] font-mono text-foreground",children:[h,"%"]})]}),e.jsx(He,{value:h,className:"h-1.5"})]},s))]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(v).map(([s,h])=>e.jsxs(B,{variant:"outline",className:"border-cyan-500/30 text-cyan-300",children:[s,": ",h]},s))}),e.jsxs("div",{className:"space-y-3",children:[r.map(s=>e.jsxs("div",{className:"rounded-xl border p-4",style:{background:s.is_global?"rgba(139, 92, 246, 0.05)":"rgba(34, 211, 238, 0.05)",borderColor:s.is_global?"rgba(139, 92, 246, 0.2)":"rgba(34, 211, 238, 0.15)"},children:[e.jsxs("div",{className:"flex items-center justify-between cursor-pointer",onClick:()=>b(l===s.id?null:s.id),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[s.is_global&&e.jsx(xs,{className:"w-4 h-4 text-violet-400"}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:s.name}),e.jsx(B,{variant:"outline",className:"text-[10px] border-white/10",children:s.base_tone_map||"?"}),s.syntax_dna?.learning_id&&e.jsxs(B,{className:"text-[9px] bg-violet-500/20 text-violet-300 border-violet-500/30 gap-1",children:[e.jsx(Y,{className:"w-2.5 h-2.5"}),"Brain"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.logic_rules?.length||0," rules"]}),l===s.id?e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}):e.jsx(ce,{className:"w-4 h-4 text-muted-foreground"})]})]}),s.voice_summary&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',s.voice_summary,'"']}),l===s.id&&e.jsxs("div",{className:"mt-4 space-y-4 pt-4 border-t border-white/10",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{className:"text-xs",children:"Name"}),e.jsx(K,{value:s.name,onChange:h=>m(s.id,{name:h.target.value}),className:"bg-black/30 border-white/10 text-sm"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ne,{checked:s.is_global,onCheckedChange:h=>m(s.id,{is_global:h})}),e.jsx(G,{className:"text-xs text-muted-foreground",children:"Global style (injected for all users)"})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-black/20 border border-white/5",children:[e.jsx("p",{className:"text-xs font-semibold text-cyan-300",children:"Syntax DNA"}),e.jsx(Se,{label:"Avg Sentence Length",value:s.syntax_dna?.rhythm?.avg_sentence_length||12,min:4,max:30,step:1,onChange:h=>y(s.id,["rhythm","avg_sentence_length"],h)}),e.jsx(Se,{label:"Fragment Ratio",value:Math.round((s.syntax_dna?.rhythm?.fragment_ratio||0)*100),min:0,max:80,step:1,onChange:h=>y(s.id,["rhythm","fragment_ratio"],h/100)}),e.jsx(Se,{label:"Formality Score",value:Math.round((s.syntax_dna?.vocabulary?.formality_score||.5)*100),min:0,max:100,step:1,onChange:h=>y(s.id,["vocabulary","formality_score"],h/100)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-semibold text-cyan-300",children:["Logic Rules (",s.logic_rules?.length||0,")"]}),e.jsx(L,{size:"sm",variant:"ghost",className:"text-xs text-violet-300 hover:text-violet-200 h-6",onClick:()=>f(n===s.id?null:s.id),children:n===s.id?"Hide Mapping":"Logic Mapping"})]}),n===s.id&&e.jsx(Hs,{rules:s.logic_rules||[],onUpdateRule:(h,C,T)=>I(s.id,h,C,T)}),n!==s.id&&(s.logic_rules||[]).map((h,C)=>e.jsxs("div",{className:"p-2 rounded bg-black/20 border border-white/5 space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"outline",className:"text-[9px] border-white/10",children:h.section_target||"global"}),e.jsx(B,{variant:"outline",className:"text-[9px] border-white/10",children:h.rule_type||"structural"})]}),e.jsx(L,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-red-400 hover:text-red-300",onClick:()=>{const T=[...s.logic_rules||[]];T.splice(C,1),m(s.id,{logic_rules:T})},children:e.jsx(te,{className:"w-3 h-3"})})]}),e.jsx(Z,{value:h.instruction||"",onChange:T=>{const t=[...s.logic_rules||[]];t[C]={...t[C],instruction:T.target.value},m(s.id,{logic_rules:t})}
43,className:"min-h-[60px] bg-black/30 border-white/5 text-xs resize-none"})]},C))]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(L,{size:"sm",onClick:()=>E(s),disabled:o===s.id,className:"bg-cyan-500/20 text-cyan-300 hover:bg-cyan-500/30 border border-cyan-500/30",children:[o===s.id?e.jsx(M,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(fe,{className:"w-3 h-3 mr-1"}),"Save"]}),e.jsxs(L,{size:"sm",variant:"ghost",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10",onClick:()=>R(s.id),children:[e.jsx(te,{className:"w-3 h-3 mr-1"})," Delete"]})]})]})]},s.id)),r.length===0&&e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No trained styles yet."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Click "Train from URL or Text" to teach the Brain a new writing style.'})]})]}),e.jsx(Ps,{isOpen:i,onClose:()=>d(!1),isAdminMode:!0,onSaveComplete:x})]})};function _e({label:r,value:c,color:_}){return e.jsxs("div",{className:"p-4 rounded-xl border text-center",style:{background:`${_}10`,borderColor:`${_}30`},children:[e.jsx("p",{className:"text-2xl font-bold",style:{color:_},children:c}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:r})]})}function Se({label:r,value:c,min:_,max:w,step:l,onChange:b}){return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(G,{className:"text-[11px] text-muted-foreground",children:r}),e.jsx("span",{className:"text-[11px] font-mono text-foreground",children:c})]}),e.jsx(rs,{value:[c],min:_,max:w,step:l,onValueChange:([o])=>b(o),className:"py-1"})]})}function Hs({rules:r,onUpdateRule:c}){const _=r.reduce((b,o,u)=>{const i=o.section_target||"global";return b[i]||(b[i]=[]),b[i].push({rule:o,idx:u}),b},{}),w=["hook","bridge","cta","global"],l={hook:"text-cyan-300 bg-cyan-500/10",bridge:"text-violet-300 bg-violet-500/10",cta:"text-amber-300 bg-amber-500/10",global:"text-emerald-300 bg-emerald-500/10"};return e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-black/20 border border-white/5",children:[e.jsx("p",{className:"text-xs font-semibold text-violet-300",children:"Logic Mapping → Composer Ingredients"}),w.map(b=>{const o=_[b]||[];return o.length===0?null:e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:`inline-block px-2 py-0.5 rounded text-[10px] font-semibold uppercase ${l[b]}`,children:[b," (",o.length," rules)"]}),o.map(({rule:u,idx:i})=>e.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-black/20 border border-white/5",children:[e.jsx("p",{className:"flex-1 text-[11px] text-muted-foreground",children:u.instruction||u.description||"No description"}),e.jsxs("div",{className:"flex flex-col gap-1 shrink-0",children:[e.jsxs(me,{value:u.section_target||"global",onValueChange:d=>c(i,"section_target",d),children:[e.jsx(ue,{className:"h-6 w-[80px] text-[9px] bg-black/30 border-white/10",children:e.jsx(he,{})}),e.jsx(pe,{children:Fs.map(d=>e.jsx(X,{value:d,className:"text-xs",children:d},d))})]}),e.jsxs(me,{value:u.ingredient_target||"General",onValueChange:d=>c(i,"ingredient_target",d),children:[e.jsx(ue,{className:"h-6 w-[80px] text-[9px] bg-black/30 border-white/10",children:e.jsx(he,{})}),e.jsx(pe,{children:Ms.map(d=>e.jsx(X,{value:d,className:"text-xs",children:d},d))})]})]})]},i))]},b)}),r.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"No rules to map."})]})}const ke=[{key:"business_logic",label:"💼 Business Logic",color:"#22D3EE"},{key:"objection_handling",label:"🛡️ Objection Handling",color:"#F59E0B"},{key:"industry_context",label:"🌍 Industry Context",color:"#10B981"}],Gs=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!0),[l,b]=a.useState(null),[o,u]=a.useState(!1),[i,d]=a.useState(""),[n,f]=a.useState(""),[x,E]=a.useState("business_logic"),R=a.useCallback(async()=>{w(!0);const{data:g,error:v}=await p.from("brain_knowledge_snippets").select("*").order("created_at",{ascending:!1});v?(console.error(v),k.error("Failed to load knowledge snippets")):c(g||[]),w(!1)},[]);a.useEffect(()=>{R()},[R]);const m=async()=>
43{if(!i.trim()||!n.trim())return;u(!0);const{error:g}=await p.from("brain_knowledge_snippets").insert({title:i.trim(),content:n.trim(),category:x,is_active:!0});g?k.error("Failed to add snippet"):(k.success("Snippet added"),d(""),f(""),R()),u(!1)},y=async g=>{b(g.id);const{error:v}=await p.from("brain_knowledge_snippets").update({title:g.title,content:g.content,is_active:g.is_active,updated_at:new Date().toISOString()}).eq("id",g.id);v?k.error("Failed to save"):k.success("Saved"),b(null)},I=async g=>{const{error:v}=await p.from("brain_knowledge_snippets").delete().eq("id",g);v?k.error("Failed to delete"):(c(F=>F.filter(s=>s.id!==g)),k.success("Deleted"))},P=(g,v)=>{c(F=>F.map(s=>s.id===g?{...s,...v}:s))};return _?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(M,{className:"w-6 h-6 animate-spin text-emerald-400"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{className:"w-4 h-4 text-emerald-400"}),e.jsx("h3",{className:"text-sm font-semibold text-emerald-300",children:"Add Knowledge Snippet"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(K,{placeholder:"Title",value:i,onChange:g=>d(g.target.value),className:"bg-black/30 border-white/10 text-sm"}),e.jsx("select",{value:x,onChange:g=>E(g.target.value),className:"bg-black/30 border border-white/10 rounded-md text-sm px-3 py-2 text-foreground",children:ke.map(g=>e.jsx("option",{value:g.key,children:g.label},g.key))})]}),e.jsx(Z,{placeholder:"Content (max 2000 chars)",value:n,onChange:g=>f(g.target.value.slice(0,2e3)),className:"min-h-[80px] bg-black/30 border-white/10 text-sm resize-y"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.length,"/2000"]}),e.jsxs(L,{size:"sm",onClick:m,disabled:o||!i.trim()||!n.trim(),className:"bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 border border-emerald-500/30",children:[o?e.jsx(M,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(oe,{className:"w-3 h-3 mr-1"}),"Add"]})]})]}),e.jsxs(Me,{defaultValue:"business_logic",children:[e.jsx(Be,{className:"bg-white/5 border border-white/10 p-1 rounded-xl",children:ke.map(g=>e.jsxs(J,{value:g.key,className:"text-xs rounded-lg px-3 py-1.5 data-[state=active]:bg-white/10",children:[g.label," (",r.filter(v=>v.category===g.key).length,")"]},g.key))}),ke.map(g=>e.jsxs(Q,{value:g.key,className:"mt-3 space-y-3",children:[r.filter(v=>v.category===g.key).map(v=>e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.02] p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(ne,{checked:v.is_active,onCheckedChange:F=>P(v.id,{is_active:F})}),e.jsx(K,{value:v.title,onChange:F=>P(v.id,{title:F.target.value}),className:"bg-transparent border-none text-sm font-medium h-auto p-0"})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Used ",v.usage_count,"x"]})]}),e.jsx(Z,{value:v.content,onChange:F=>P(v.id,{content:F.target.value.slice(0,2e3)}),className:"min-h-[80px] bg-black/20 border-white/5 text-xs resize-y"}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsxs(L,{size:"sm",onClick:()=>y(v),disabled:l===v.id,className:"bg-white/5 text-foreground hover:bg-white/10 border border-white/10 text-xs",children:[l===v.id?e.jsx(M,{className:"w-3 h-3 animate-spin"}):e.jsx(fe,{className:"w-3 h-3"}),e.jsx("span",{className:"ml-1",children:"Save"})]}),e.jsx(L,{size:"sm",variant:"ghost",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 text-xs",onClick:()=>I(v.id),children:e.jsx(te,{className:"w-3 h-3"})})]})]},v.id)),r.filter(v=>v.category===g.key).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No snippets in this category yet."})]},g.key))]})]})},Us=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!0),[l,b]=a.useState(null),o=a.useCallback(async()=>{w(!0);const{data:d,error:n}=await p.from("brain_excellent_messages").select("*").order("created_at",{ascending:!1});n?console.error(n):c(d||[]),w(!1)},[]);a.useEffect(()=>{o()},[o]);const u=async d=>{b(d.id);try{const{data:n,error:f}=await p.functions.invoke("extract-style-dna",{body:{text:d.message_text}});if(f||!n?.success)throw new Error("DNA extraction failed");const{data:x}=await p.functions.invoke("extract-style-rules",{body:{text:d.message_text}}),{data:{user:E}}=await p.auth.getUser();if(!E)throw new Error("Not authenticated");await p.from("custom_style_templates").insert({user_id:E.id,name:`[Global] From "${d.prospect_username||"Unknown"}"`,syntax_dna:n.syntax_dna,logic_rules:x?.logic_rules||[],training_samples:[d.message_text],source_urls:[],base_tone_map:n.base_tone_map,voice_summary:n.voice_summary,is_global:!0}),await p.from("brain_excellent_messages").update({extracted_as_global:!0}).eq("id",d.id),c(R=>R.map(m=>m.id===d.id?{...m,extracted_as_global:!0}:m)),k.success("Style extracted and saved as Global")}catch(n){console.error(n),k.error("Failed to extract style")}b(null)},i=async d=>{const{error:n}=await p.from("brain_excellent_messages").delete().eq("id",d);n||c(f=>f.filter(x=>
43x.id!==d))};return _?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(M,{className:"w-6 h-6 animate-spin text-amber-400"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[r.length," excellent message",r.length!==1?"s":""," collected"]}),r.length===0&&e.jsxs("div",{className:"text-center py-12 space-y-2",children:[e.jsx(Ke,{className:"w-8 h-8 text-amber-400 mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No messages marked as excellent yet."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Users can mark hooks with ⭐ from scan results."})]}),r.map(d=>e.jsxs("div",{className:"rounded-xl border border-amber-500/15 bg-amber-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[d.prospect_username&&e.jsxs(B,{variant:"outline",className:"text-[10px] border-white/10",children:["@",d.prospect_username]}),d.extracted_as_global&&e.jsxs(B,{className:"bg-violet-500/20 text-violet-300 border-violet-500/30 text-[10px]",children:[e.jsx(Y,{className:"w-3 h-3 mr-1"})," Learned"]})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(d.created_at).toLocaleDateString()})]}),e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap leading-relaxed",children:d.message_text}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[!d.extracted_as_global&&e.jsxs(L,{size:"sm",onClick:()=>u(d),disabled:l===d.id,className:"bg-amber-500/20 text-amber-300 hover:bg-amber-500/30 border border-amber-500/30 text-xs",children:[l===d.id?e.jsx(M,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(Y,{className:"w-3 h-3 mr-1"}),"Teach the Brain"]}),e.jsx(L,{size:"sm",variant:"ghost",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 text-xs",onClick:()=>i(d.id),children:e.jsx(te,{className:"w-3 h-3"})})]})]},d.id))]})},zs=()=>{const[r,c]=a.useState(null);if(a.useEffect(()=>{(async()=>{try{const[l,b,o,u]=await Promise.all([p.from("brain_iron_laws").select("id",{count:"exact"}).eq("is_active",!0),p.rpc("get_all_style_templates"),p.from("brain_knowledge_snippets").select("id",{count:"exact"}).eq("is_active",!0),p.from("brain_excellent_messages").select("id",{count:"exact"})]),i=l.data?.length||0,d=b.data?.length||0,n=o.data?.length||0,f=u.data?.length||0,x=new Set(b.data?.map(I=>I.base_tone_map).filter(Boolean)||[]),E=Math.min(i/5,1)*30,R=Math.min(x.size/4,1)*30,m=Math.min(n/10,1)*20,y=Math.min(f/15,1)*20;c(Math.round(E+R+m+y))}catch(l){console.error(l)}})()},[]),r===null)return null;const _=r>=70?"#10B981":r>=40?"#F59E0B":"#EF4444";return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative w-12 h-12",children:[e.jsxs("svg",{viewBox:"0 0 36 36",className:"w-12 h-12 -rotate-90",children:[e.jsx("circle",{cx:"18",cy:"18",r:"16",fill:"none",stroke:"rgba(255,255,255,0.1)",strokeWidth:"3"}),e.jsx("circle",{cx:"18",cy:"18",r:"16",fill:"none",stroke:_,strokeWidth:"3",strokeDasharray:`${r} ${100-r}`,strokeLinecap:"round"})]}),e.jsx("span",{className:"absolute inset-0 flex items-center justify-center text-xs font-bold",style:{color:_},children:r})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium text-foreground",children:"Brain Health"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:r>=70?"Excellent":r>=40?"Growing":"Needs data"})]})]})},Ie=ms,Re=us,Ae=hs,Vs={hook:"bg-violet-400",bridge:"bg-blue-400",cta:"bg-amber-400",tone:"bg-emerald-400",psychology:"bg-pink-400",objective:"bg-sky-400",productIntegration:"bg-orange-400",format:"bg-teal-400"},qs={hook:"Hook",bridge:"Bridge / Value Prop",cta:"CTA",tone:"Tone",psychology:"Psychology",objective:"Objective",productIntegration:"Product Integration",format:"Format"},$s={Tone:"bg-emerald-500/20 text-emerald-300 border-emerald-500/30",Objective:"bg-sky-500/20 text-sky-300 border-sky-500/30",Psychology:"bg-pink-500/20 text-pink-300 border-pink-500/30",Product:"bg-orange-500/20 text-orange-300 border-orange-500/30",Format:"bg-teal-500/20 text-teal-300 border-teal-500/30"},De=({data:r,exportSubstance:c,exportForm:_,onExportSubstanceChange:w,onExportFormChange:l,forcedMapping:b,readOnly:o,sourceUrl:u})=>e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-y-auto pr-1",children:[u&&e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg bg-white/[0.03] border border-white/10 text-[11px]",children:[e.jsx(Ee,{className:"w-3.5 h-3.5 text-cyan-400 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"Source:"}),e.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"text-cyan-400 hover:text-cyan-300 truncate",children:u})]}
43),e.jsxs("div",{className:U("rounded-xl border p-4 space-y-3 transition-opacity",c?"border-violet-500/20 bg-violet-500/5":"border-white/5 bg-white/[0.02] opacity-50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(le,{className:"w-4 h-4 text-violet-400"}),e.jsx("h3",{className:"text-sm font-semibold text-violet-300",children:"What I learned (The Substance)"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:r.substance.summary}),e.jsx("ul",{className:"space-y-1.5",children:r.substance.key_teachings.map((i,d)=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-foreground/80",children:[e.jsx(ie,{className:"w-3.5 h-3.5 text-violet-400 mt-0.5 shrink-0"}),e.jsx("span",{children:i})]},d))})]}),e.jsxs("div",{className:U("rounded-xl border p-4 space-y-3 transition-opacity",_?"border-cyan-500/20 bg-cyan-500/5":"border-white/5 bg-white/[0.02] opacity-50"),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(se,{className:"w-4 h-4 text-cyan-400"}),e.jsx("h3",{className:"text-sm font-semibold text-cyan-300",children:"What I'll mimic (The Form)"})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:r.form.summary}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:r.form.style_traits.map((i,d)=>e.jsx("span",{className:"px-2 py-0.5 rounded-full bg-cyan-500/15 text-cyan-300 text-[10px] font-medium border border-cyan-500/20",children:i},d))})]}),e.jsxs("div",{className:"rounded-xl border border-emerald-500/20 bg-emerald-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ps,{className:"w-4 h-4 text-emerald-400"}),e.jsx("h3",{className:"text-sm font-semibold text-emerald-300",children:"Impact on Outreach Composer"})]}),e.jsx("div",{className:"space-y-2",children:Object.entries(r.composer_impact).map(([i,d])=>e.jsxs("div",{className:"flex items-start gap-2.5 text-xs",children:[e.jsx("div",{className:U("w-2 h-2 rounded-full mt-1 shrink-0",Vs[i]||"bg-gray-400")}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold text-foreground/90",children:qs[i]||i}),e.jsxs("span",{className:"text-muted-foreground ml-1",children:["— ",d]})]})]},i))})]}),r.composer_mapping&&r.composer_mapping.length>0&&e.jsxs("div",{className:"rounded-xl border border-rose-500/20 bg-rose-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ns,{className:"w-4 h-4 text-rose-400"}),e.jsx("h3",{className:"text-sm font-semibold text-rose-300",children:"Composer Mapping"}),b&&e.jsxs(B,{className:"text-[9px] bg-amber-500/20 text-amber-300 border-amber-500/30 ml-auto",children:["🔒 Locked to ",b.pillar," → ",b.sub_style]})]}),e.jsx("div",{className:"space-y-3",children:r.composer_mapping.map((i,d)=>e.jsxs("div",{className:"rounded-lg bg-white/[0.03] border border-white/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[10px] font-medium text-muted-foreground",children:"Will be integrated in:"}),e.jsx(B,{className:U("text-[10px] uppercase font-bold border",$s[i.pillar]||"bg-gray-500/20 text-gray-300 border-gray-500/30"),children:i.pillar}),e.jsx(es,{className:"w-3 h-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs font-medium text-foreground/90",children:i.sub_style}),e.jsxs("span",{className:"ml-auto flex items-center gap-1 text-[10px] text-emerald-400 font-medium",children:[e.jsx(oe,{className:"w-3 h-3"}),"New variation"]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground italic leading-relaxed",children:i.reasoning})]},d))})]}),!o&&e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-4 space-y-3",children:[e.jsx("h3",{className:"text-xs font-semibold text-foreground/80 uppercase tracking-wider",children:"What to export"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ne,{id:"export-substance",checked:c,onCheckedChange:w}),e.jsxs(G,{htmlFor:"export-substance",className:"cursor-pointer space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-foreground
43/90",children:[e.jsx(vs,{className:"w-3.5 h-3.5 text-violet-400"}),"Export Substance (Logic)"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Influences content, hook structure, sales strategy — Objective, Psychology, Format"})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ne,{id:"export-form",checked:_,onCheckedChange:l}),e.jsxs(G,{htmlFor:"export-form",className:"cursor-pointer space-y-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-medium text-foreground/90",children:[e.jsx(ws,{className:"w-3.5 h-3.5 text-cyan-400"}),"Export Form (DNA)"]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Influences tone, rhythm, speech patterns — Tone, Product"})]})]})]}),e.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gs,{className:"w-4 h-4 text-amber-400"}),e.jsx("h3",{className:"text-sm font-semibold text-amber-300",children:"Here's how I'll write now"})]}),e.jsx("blockquote",{className:"border-l-2 border-amber-400/40 pl-3 text-xs text-foreground/80 italic leading-relaxed",children:r.example_sentence})]}),e.jsxs(Ie,{children:[e.jsxs(Re,{className:"flex items-center gap-2 text-xs text-muted-foreground hover:text-foreground transition-colors w-full",children:[e.jsx(_s,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:"Technical Integration"}),e.jsx(ce,{className:"w-3 h-3 ml-auto"})]}),e.jsxs(Ae,{className:"mt-2 rounded-lg border border-white/5 bg-white/[0.02] p-3 space-y-2",children:[e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground/70",children:"System Prompt:"})," ",r.technical_integration.system_prompt]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground/70",children:"Knowledge Base:"})," ",r.technical_integration.knowledge_base]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground/70",children:"Tone Filter:"})," ",r.technical_integration.tone_filter]})]})]})]}),Ye=({isOpen:r,onClose:c,onComplete:_,forcedMapping:w})=>{const[l,b]=a.useState("url"),[o,u]=a.useState(""),[i,d]=a.useState(""),[n,f]=a.useState(""),[x,E]=a.useState(""),[R,m]=a.useState("business_logic"),[y,I]=a.useState(!1),[P,g]=a.useState("input"),[v,F]=a.useState(null),[s,h]=a.useState(null),[C,T]=a.useState([]),[t,S]=a.useState(""),[A,j]=a.useState(!0),[H,ae]=a.useState(!0),q=()=>{b("url"),u(""),d(""),f(""),E(""),m("business_logic"),I(!1),g("input"),F(null),h(null),T([]),S(""),j(!0),ae(!0)},$=()=>{q(),c()},be=async()=>{if(!(!n.trim()||!x.trim())){I(!0);try{const{error:N}=await p.from("brain_knowledge_snippets").insert({title:n.trim(),content:x.trim(),category:R,is_active:!0});if(N)throw N;k.success("Snippet added to Knowledge Base"),g("done"),_?.()}catch{k.error("Failed to save snippet")}I(!1)}},ye=async()=>{let N="";if(I(!0),g("processing"),l==="url"){if(!o.trim())return;try{const{data:O,error:W}=await p.functions.invoke("firecrawl-scrape",{body:{url:o.trim(),options:{formats:["markdown"],onlyMainContent:!0}}});if(W||!O?.success)throw new Error(O?.error||"Scraping failed");if(N=O.data?.markdown||O.markdown||"",!N||N.length<50)throw new Error("Not enough content")}catch{k.error("Failed to scrape URL"),g("input"),I(!1);return}}else{if(i.trim().length<50)return;N=i.trim()}S(N);try{const{data:O,error:W}=await p.functions.invoke("extract-style-dna",{body:{text:N}});if(W||!O?.success)throw new Error("DNA extraction failed");h(O);const{data:re}=await p.functions.invoke("extract-style-rules",{body:{text:N}}),de=re?.logic_rules||[];T(de);const Le={text:N.slice(0,3e3),syntax_dna:O.syntax_dna,logic_rules:de,voice_summary:O.voice_summary,base_tone_map:O.base_tone_map};w&&(Le.forced_mapping=w);const{data:Ne,error:Qe}=await p.functions.invoke("analyze-learning-synthesis",{body:Le});if(Qe||!Ne?.success)throw new Error(Ne?.error||"Synthesis analysis failed");F(Ne.synthesis),g("synthesis")}catch(O){k.error(O.message||"Processing failed"),g("input")}I(!1)},je=async()=>
43{if(!(!A&&!H)){g("confirming");try{const{data:{user:N}}=await p.auth.getUser();if(!N)throw new Error("Not authenticated");const O=`learn_${Date.now()}`,W=l==="url"?o.trim().slice(0,60):"pasted content";if(H){const de=`[Global] ${s?.base_tone_map||"Trained"} Style`;await p.from("custom_style_templates").insert({user_id:N.id,name:de,syntax_dna:{...s?.syntax_dna||{},learning_id:O,composer_mapping:v?.composer_mapping||[]},logic_rules:C,training_samples:[t.slice(0,500)],source_urls:l==="url"?[o.trim()]:[],base_tone_map:s?.base_tone_map||"Professional",voice_summary:s?.voice_summary||"",is_global:!0})}A&&v?.substance?.key_teachings?.length&&await p.from("brain_knowledge_snippets").insert({title:`Teachings from ${W}`,content:[v.substance.summary,"","• "+v.substance.key_teachings.join(`
44• `)].join(`
45`),category:"industry_context",is_active:!0,learning_id:O});const re=[];H&&re.push("Style DNA"),A&&re.push("Teachings"),k.success(`${re.join(" + ")} applied as new variation`),g("done"),_?.()}catch(N){k.error(N.message||"Failed to apply"),g("synthesis")}}},D=P==="synthesis",z=A||H;return e.jsx(Ge,{open:r,onOpenChange:N=>!N&&$(),children:e.jsxs(Ue,{className:U("bg-[#0F1115] border-white/10 transition-all",D?"sm:max-w-[650px]":"sm:max-w-[500px]"),children:[e.jsxs(ze,{children:[e.jsxs(Ve,{className:"flex items-center gap-2",children:[e.jsx(se,{className:"w-5 h-5 text-cyan-400"}),D?"Learning Synthesis":"Feed the Brain"]}),e.jsx(qe,{children:D?"Review what the AI learned before applying changes.":"Drop content to teach the AI a new style or add knowledge."})]}),P==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8",children:[e.jsx(ie,{className:"w-12 h-12 text-emerald-400"}),e.jsx("p",{className:"text-sm text-emerald-300",children:"Successfully applied to Leadfo!"}),e.jsx(L,{onClick:$,variant:"outline",size:"sm",className:"border-white/10",children:"Close"})]}):P==="confirming"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8",children:[e.jsx(M,{className:"w-8 h-8 text-violet-400 animate-spin"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Applying to Leadfo..."})]}):P==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8",children:[e.jsx(M,{className:"w-8 h-8 text-violet-400 animate-spin"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Extracting style DNA & generating synthesis..."})]}):P==="synthesis"&&v?e.jsxs("div",{className:"space-y-4",children:[e.jsx(De,{data:v,exportSubstance:A,exportForm:H,onExportSubstanceChange:j,onExportFormChange:ae,forcedMapping:w}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(L,{onClick:()=>{g("input"),F(null)},variant:"outline",className:"flex-1 border-white/10",children:"Cancel"}),e.jsxs(L,{onClick:je,disabled:!z,className:"flex-1 bg-gradient-to-r from-cyan-500 to-violet-500 hover:from-cyan-600 hover:to-violet-600 disabled:opacity-40",children:[e.jsx(ie,{className:"w-4 h-4 mr-2"}),"Confirm and Apply to Leadfo"]})]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-white/5 rounded-xl",children:[{key:"url",icon:ge,label:"URL"},{key:"text",icon:Te,label:"Text"},{key:"snippet",icon:le,label:"Snippet"}].map(({key:N,icon:O,label:W})=>e.jsxs("button",{onClick:()=>b(N),className:U("flex-1 flex items-center justify-center gap-1.5 py-2 rounded-lg text-xs font-medium transition-all",l===N?"bg-cyan-500/20 text-cyan-300 ring-1 ring-cyan-500/30":"text-muted-foreground hover:text-foreground"),children:[e.jsx(O,{className:"w-3.5 h-3.5"}),W]},N))}),l==="url"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs text-muted-foreground",children:"Blog or article URL"}),e.jsx(K,{value:o,onChange:N=>u(N.target.value),placeholder:"https://...",className:"bg-white/5 border-white/10"})]}),l==="text"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(G,{className:"text-xs text-muted-foreground",children:"Paste content (min 50 chars)"}),e.jsx(Z,{value:i,onChange:N=>d(N.target.value),placeholder:"Paste writing sample...",className:"min-h-[150px] bg-white/5 border-white/10 resize-none"})]}),l==="snippet"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{className:"text-xs",children:"Title"}),e.jsx(K,{value:n,onChange:N=>f(N.target.value),placeholder:"e.g., Trading psychology basics",className:"bg-white/5 border-white/10"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{className:"text-xs",children:"Category"}),e.jsxs(me,{value:R,onValueChange:m,children:[e.jsx(ue,{className:"bg-white/5 border-white/10",children:e.jsx(he,{})}),e.jsxs(pe,{children:[e.jsx(X,{value:"business_logic",children:"Business Logic"}),e.jsx(X,{value:"objection_handling",children:"Objection Handling"}),e.jsx(X,{value:"industry_context",children:"Industry Context"})]})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(G,{className:"text-xs",children:"Content"}),e.jsx(Z,{value:x,onChange:N=>E(N.target.value),placeholder:"Write your knowledge snippet...",className:"min-h-[120px] bg-white/5 border-white/10 resize-none"})]})]}),e.jsxs(L,{onClick:l==="snippet"?be:ye,disabled:y||(l==="url"?!o.trim():l==="text"?i.length<50:!n.trim()||!x.trim()),className:"w-full bg-gradient-to-r from-cyan-500 to-violet-500 hover:from-cyan-600 hover:to-violet-600",children:[y?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(se,{className:"w-4 h-4 mr-2"}),l==="snippet"?"Add to Knowledge Base":"Analyze & Preview Learning"]})]})]})})},Je={Objective:{"Conversation Starter":"conversation_starter",Partnership:"partnership"},Product:{"Stealth Mode":"stealth_mode","Subtle Mention":"subtle_mention","Feature Highlight":"feature_highlight"},Tone:{Friendly:"friendly",Professional:"professional",Empathetic:"empathetic"},Psychology:{"Curiosity Gap":"curiosity_gap","Pain Agitation":"pain_agitation"},Format:{"One-Liner":"one_liner",Structured:"structured"}},Fe={};for(const[r,c]of Object.entries(Je)){Fe[r]={};for(const[_,w]of Object.entries(c))Fe[r][w]=_}function Ws(r,c){const w={Tone:l=>ks(l),Objective:l=>Cs({"Conversation Starter":"Build Relationship","Asset Drop":"Drive Traffic","Direct Meeting":"Book Meeting",Qualification:"Qualify Lead"}[l]||l),Product:l=>Ts({"Stealth Mode":"None","Subtle Mention":"Subtle","Feature Highlight":"Direct","Outcome Focus":"Subtle"}[l]||l),Psychology:l=>Es({"Curiosity Gap":"Curiosity","Pain Agitation":"Scarcity","Ego-Bait":"Reciprocity","Social Proof":"Social Proof"}[l]||l),Format:()=>"Format rules applied at generation time based on selected format type. These rules control paragraph count, greeting formulas, line break patterns, and overall structural skeleton."}[r];return w?w(c):""}const Ks=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!0),[l,b]=a.useState(null),[o,u]=a.useState({Tone:!0}
45),[i,d]=a.useState(!1),[n,f]=a.useState(null),[x,E]=a.useState(null),R=a.useCallback(async()=>{w(!0);try{const{data:s,error:h}=await p.rpc("get_all_style_templates");if(h)throw h;c(s||[])}catch{k.error("Failed to load styles")}w(!1)},[]);a.useEffect(()=>{R()},[R]);const m=async(s,h)=>{b(s);try{h&&await p.from("brain_knowledge_snippets").delete().eq("learning_id",h);const{error:C}=await p.from("custom_style_templates").delete().eq("id",s);if(C)throw C;c(T=>T.filter(t=>t.id!==s)),k.success("Variation deleted (cascade)"),x?.type==="variation"&&x.variation?.templateId===s&&E(null)}catch{k.error("Failed to delete")}b(null)},y=(s,h)=>{f({pillar:s,sub_style:h}),d(!0)},I=(s,h,C)=>{E({type:"core",pillar:s,label:h,coreLogic:C})},P=(s,h,C)=>{E({type:"variation",pillar:s,label:h,variation:C})},g=Object.entries(Je).map(([s,h])=>{const C=Object.entries(h).map(([T,t])=>{const S=Ws(s,T),A=[];return r.forEach(j=>{const H=j.syntax_dna?.composer_mapping;if(!Array.isArray(H))return;if(H.find(q=>q.pillar===s&&(q.sub_style===T||q.sub_style===t))&&j.syntax_dna?.learning_id){const q=!!(j.syntax_dna?.rhythm||j.syntax_dna?.syntactic_signature||j.syntax_dna?.vocabulary),$=Array.isArray(j.logic_rules)&&j.logic_rules.length>0;A.push({templateId:j.id,name:j.name,voiceSummary:j.voice_summary||"",learningId:j.syntax_dna.learning_id,createdAt:j.created_at,logicRules:j.logic_rules||[],exampleSentence:j.syntax_dna?.synthesis_data?.example_sentence,hasDna:q,hasSubstance:$,syntaxDna:j.syntax_dna})}}),{label:T,id:t,coreLogicFull:S,variations:A}});return{pillar:s,subStyles:C}});if(_)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(M,{className:"w-6 h-6 animate-spin text-cyan-400"})});const v={Objective:"🎯",Product:"📦",Tone:"🎨",Psychology:"🧠",Format:"📐"},F={Objective:"border-sky-500/20 bg-sky-500/5",Product:"border-orange-500/20 bg-orange-500/5",Tone:"border-emerald-500/20 bg-emerald-500/5",Psychology:"border-pink-500/20 bg-pink-500/5",Format:"border-teal-500/20 bg-teal-500/5"};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-4",children:g.map(({pillar:s,subStyles:h})=>{const C=h.reduce((T,t)=>T+t.variations.length,0);return e.jsxs(Ie,{open:o[s]||!1,onOpenChange:T=>u(t=>({...t,[s]:T})),children:[e.jsxs(Re,{className:`w-full flex items-center justify-between p-4 rounded-xl border ${F[s]||"border-white/10 bg-white/5"} hover:bg-white/[0.08] transition-colors`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:v[s]}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:s}),e.jsxs(B,{variant:"outline",className:"text-[10px] border-white/10",children:[h.length," styles"]}),C>0&&e.jsxs(B,{className:"text-[10px] bg-violet-500/20 text-violet-300 border-violet-500/30",children:[C," Brain variations"]})]}),o[s]?e.jsx(ce,{className:"w-4 h-4 text-muted-foreground"}):e.jsx(ss,{className:"w-4 h-4 text-muted-foreground"})]}),e.jsx(Ae,{className:"mt-2 space-y-2 pl-4",children:h.map(({label:T,id:t,coreLogicFull:S,variations:A})=>e.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.02] p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-medium text-foreground/90",children:T}),e.jsxs(L,{size:"sm",variant:"ghost",className:"h-6 text-[10px] text-cyan-400 hover:text-cyan-300 hover:bg-cyan-500/10",onClick:()=>y(s,T),children:[e.jsx(oe,{className:"w-3 h-3 mr-1"}),"Enrich this style"]})]}),e.jsxs("button",{type:"button",className:"w-full text-left flex items-start gap-2 p-2 rounded bg-white/[0.03] border border-white/5 hover:bg-white/[0.06] transition-colors cursor-pointer group",onClick:()=>I(s,T,S),children:[e.jsx(Oe,{className:"w-3.5 h-3.5 text-gray-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-[10px] font-medium text-gray-400",children:"Core Logic"}),e.jsx(Pe,{className:"w-2.5 h-2.5 text-gray-500"}
45),e.jsx("span",{className:"text-[9px] text-muted-foreground/50 opacity-0 group-hover:opacity-100 transition-opacity",children:"click to view"})]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5 line-clamp-2",children:[S.slice(0,150),"..."]})]})]}),A.map(j=>e.jsxs("div",{className:"flex items-start gap-2 p-2 rounded bg-violet-500/5 border border-violet-500/15 group",children:[e.jsxs("button",{type:"button",className:"flex items-start gap-2 flex-1 min-w-0 text-left cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>P(s,T,j),children:[e.jsx(Y,{className:"w-3.5 h-3.5 text-violet-400 mt-0.5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{className:"text-[10px] font-medium text-violet-300",children:j.name}),e.jsx("span",{className:"text-[9px] text-muted-foreground font-mono",children:j.learningId}),j.hasDna&&e.jsxs(B,{className:"text-[8px] h-3.5 px-1 bg-amber-500/20 text-amber-300 border-amber-500/30 gap-0.5",children:[e.jsx(se,{className:"w-2 h-2"})," DNA"]}),j.hasSubstance&&e.jsxs(B,{className:"text-[8px] h-3.5 px-1 bg-emerald-500/20 text-emerald-300 border-emerald-500/30 gap-0.5",children:[e.jsx(le,{className:"w-2 h-2"})," Substance"]})]}),j.voiceSummary&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5 italic line-clamp-1",children:['"',j.voiceSummary,'"']}),e.jsx("span",{className:"text-[9px] text-muted-foreground",children:new Date(j.createdAt).toLocaleDateString()})]})]}),e.jsx(L,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-red-400/50 hover:text-red-400 hover:bg-red-500/10 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",onClick:H=>{H.stopPropagation(),m(j.templateId,j.learningId)},disabled:l===j.templateId,children:l===j.templateId?e.jsx(M,{className:"w-3 h-3 animate-spin"}):e.jsx(te,{className:"w-3 h-3"})})]},j.templateId))]},t))})]},s)})}),e.jsx(is,{open:!!x,onOpenChange:s=>{s||E(null)},children:e.jsxs(ls,{className:"max-h-[85vh] bg-[#0d0d1a] border-white/10",children:[e.jsxs(os,{className:"pb-2",children:[e.jsx(cs,{className:"text-sm text-foreground flex items-center gap-2",children:x?.type==="core"?e.jsxs(e.Fragment,{children:[e.jsx(Oe,{className:"w-4 h-4 text-gray-400"})," Core Logic — ",x.pillar," › ",x.label]}):e.jsxs(e.Fragment,{children:[e.jsx(Y,{className:"w-4 h-4 text-violet-400"})," Brain Variation — ",x?.pillar," › ",x?.label]})}),e.jsx(ds,{className:"text-xs text-muted-foreground",children:x?.type==="core"?"Hardcoded system rules (non-deletable)":`Learning: ${x?.variation?.learningId}`})]}),e.jsxs("div",{className:"px-4 pb-6 overflow-y-auto max-h-[60vh]",children:[x?.type==="core"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Pe,{className:"w-3 h-3 text-gray-500"}),e.jsx("span",{className:"text-[10px] text-gray-500 uppercase tracking-wider",children:"Protected — Cannot be deleted"})]}),e.jsx("pre",{className:"text-xs text-foreground/80 whitespace-pre-wrap font-mono bg-white/[0.03] p-3 rounded-lg border border-white/5 leading-relaxed",children:x.coreLogic})]}),x?.type==="variation"&&x.variation&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-2",children:[x.variation.hasDna&&e.jsxs(B,{className:"text-[10px] bg-amber-500/20 text-amber-300 border-amber-500/30 gap-1",children:[e.jsx(se,{className:"w-3 h-3"})," DNA (Form/Style)"]}),x.variation.hasSubstance&&e.jsxs(B,{className:"text-[10px] bg-emerald-500/20 text-emerald-300 border-emerald-500/30 gap-1",children:[e.jsx(le,{className:"w-3 h-3"})," Substance (Teaching/Logic)"]})]}),x.variation.voiceSummary&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-violet-300 mb-1 uppercase tracking-wider",children:"Voice Summary"}),e.jsxs("p",{className:"text-xs text-foreground/80 bg-violet-500/5 p-2 rounded border border-violet-500/15 italic",children:['"',x.variation.voiceSummary,'"']})]}),x.variation.logicRules.length>0&&e.jsxs("div",{children:[e.jsxs("p",{className:"text-[10px] font-semibold text-emerald-300 mb-1 uppercase tracking-wider",children:["Logic Rules (",x.variation.logicRules.length,")"]}),e.jsx("div",{className:"space-y-1 bg-white/[0.03] p-2 rounded border border-white/5",children:x.variation.logicRules.map((s,h)=>
45e.jsxs("div",{className:"flex gap-2 text-[11px] text-foreground/70",children:[e.jsx("span",{className:"text-emerald-400 shrink-0",children:"•"}),e.jsx("span",{children:s.instruction||s.description||s.rule||JSON.stringify(s)})]},h))})]}),x.variation.hasDna&&x.variation.syntaxDna&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-amber-300 mb-1 uppercase tracking-wider",children:"Syntax DNA"}),e.jsxs("div",{className:"space-y-2 bg-white/[0.03] p-2 rounded border border-white/5",children:[x.variation.syntaxDna.rhythm&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] text-amber-400 uppercase",children:"Rhythm"}),e.jsx("pre",{className:"text-[10px] text-foreground/60 mt-0.5",children:JSON.stringify(x.variation.syntaxDna.rhythm,null,2)})]}),x.variation.syntaxDna.syntactic_signature&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] text-amber-400 uppercase",children:"Syntactic Signature"}),e.jsx("pre",{className:"text-[10px] text-foreground/60 mt-0.5",children:JSON.stringify(x.variation.syntaxDna.syntactic_signature,null,2)})]}),x.variation.syntaxDna.vocabulary&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] text-amber-400 uppercase",children:"Vocabulary"}),e.jsx("pre",{className:"text-[10px] text-foreground/60 mt-0.5",children:JSON.stringify(x.variation.syntaxDna.vocabulary,null,2)})]})]})]}),x.variation.exampleSentence&&e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] font-semibold text-cyan-300 mb-1 uppercase tracking-wider",children:"Example Sentence"}),e.jsxs("p",{className:"text-xs text-foreground/80 bg-cyan-500/5 p-2 rounded border border-cyan-500/15 italic",children:['"',x.variation.exampleSentence,'"']})]}),e.jsxs(L,{variant:"ghost",size:"sm",className:"text-red-400 hover:text-red-300 hover:bg-red-500/10 text-xs mt-2",onClick:()=>{x.variation&&m(x.variation.templateId,x.variation.learningId)},disabled:l===x.variation?.templateId,children:[l===x.variation?.templateId?e.jsx(M,{className:"w-3 h-3 animate-spin mr-1"}):e.jsx(te,{className:"w-3 h-3 mr-1"}),"Delete variation (cascade)"]})]})]})]})}),e.jsx(Ye,{isOpen:i,onClose:()=>{d(!1),f(null)},onComplete:()=>{R()},forcedMapping:n||void 0})]})},Ys=()=>{const[r,c]=a.useState([]),[_,w]=a.useState(!0),[l,b]=a.useState(null),[o,u]=a.useState(null),i=a.useCallback(async()=>{w(!0);try{const{data:n,error:f}=await p.rpc("get_all_style_templates");if(f)throw f;const E=(n||[]).filter(y=>y.syntax_dna?.learning_id),R=E.map(y=>y.syntax_dna.learning_id).filter(Boolean);let m={};if(R.length>0){const{data:y}=await p.from("brain_knowledge_snippets").select("learning_id").in("learning_id",R);(y||[]).forEach(I=>{m[I.learning_id]=(m[I.learning_id]||0)+1})}c(E.map(y=>({id:y.id,name:y.name,syntax_dna:y.syntax_dna,logic_rules:y.logic_rules||[],voice_summary:y.voice_summary,source_urls:y.source_urls||[],created_at:y.created_at,snippetCount:m[y.syntax_dna.learning_id]||0})))}catch{k.error("Failed to load history")}w(!1)},[]);a.useEffect(()=>{i()},[i]);const d=async n=>{u(n.id);try{const f=n.syntax_dna?.learning_id;f&&await p.from("brain_knowledge_snippets").delete().eq("learning_id",f);const{error:x}=await p.from("custom_style_templates").delete().eq("id",n.id);if(x)throw x;c(E=>E.filter(R=>R.id!==n.id)),k.success("Learning deleted (cascade)")}catch{k.error("Failed to delete")}u(null)};return _?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(M,{className:"w-6 h-6 animate-spin text-cyan-400"})}):r.length===0?e.jsxs("div",{className:"text-center py-12 space-y-2",children:[e.jsx(Y,{className:"w-8 h-8 text-violet-400 mx-auto opacity-50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No learnings yet."}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Use "Feed the Brain" to teach the AI new styles.'})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("p",{className:"text-xs text-muted-foreground",children:[r.length," learning",r.length!==1?"s":""," recorded"]})}),r.map(n=>{const f=l===n.id,x=n.syntax_dna?.composer_mapping||[],E=n.source_urls?.[0]||null,R=n.syntax_dna?.synthesis_data;return e.jsxs("div",{className:"rounded-xl border border-violet-500/15 bg-violet-500/5 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-white/[0.02] transition-colors",onClick:()=>b(f?null:n.id),children:[e.jsx(Y,{className:"w-4 h-4 text-violet-400 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:n.name}),n.snippetCount>0&&e.jsxs(B,{className:"text-[9px] bg-emerald-500/20 text-emerald-300 border-emerald-500/30",children:[n.snippetCount," snippet",n.snippetCount!==1?"s":""]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:new Date(n.created_at).toLocaleDateString()}),E&&e.jsxs("span",{className:"flex items-center gap-1 text-[10px] text-cyan-400",children:[e.jsx(ge,{className:"w-2.5 h-2.5"}),"URL"]}),!E&&e.jsxs("span",{className:"flex items-center gap-1 text-[10px] text-muted-foreground",children:[e.jsx(Te,{className:"w-2.5 h-2.5"}),"Pasted"]}),x.map((m,y)=>e.jsxs(B,{variant:"outline",className:"text-[9px] border-white/10",children:[m.pillar," → ",m.sub_style]},y))]})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(L,{size:"sm",variant:"ghost",className:"h-7 w-7 p-0 text-red-400/50 hover:text-red-400 hover:bg-red-500/10",onClick:m=>{m.stopPropagation(),d(n)},disabled:o===n.id,children:o===n.id?e.jsx(M,{className:"w-3.5 h-3.5 animate-spin"}):e.jsx(te,{className:"w-3.5 h-3.5"})}),f?e.jsx(We,{className:"w-4 h-4 text-muted-foreground"}):e.jsx(ce,{className:"w-4 h-4 text-muted-foreground"})]})]}),f&&e.jsx("div",{className:"px-4 pb-4 border-t border-white/5 pt-3",children:R?e.jsx(De,{data:R,exportSubstance:!0,exportForm:!0,onExportSubstanceChange:()=>{},onExportFormChange:()=>{},readOnly:!0}):e.jsxs("div",{className:"space-y-3",children:[n.voice_summary&&e.jsxs("div",{className:"p-3 rounded-lg bg-white/[0.03] border border-white/5",children:[e.jsx("p",{className:"text-[10px] font-semibold text-cyan-300 mb-1",children:"Voice Summary"}),e.jsxs("p",{className:"text-xs text-muted-foreground italic",children:['"',n.voice_summary,'"']})]}),n.logic_rules.length>0&&e.jsxs("div",{className:"p-3 rounded-lg bg-white/[0.03] border border-white/5",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-violet-300 mb-1",children:["Logic Rules (",n.logic_rules.length,")"]}),n.logic_rules.slice(0,5).map((m,y)=>e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["• ",m.instruction||m.description||"Rule"]},y))]}),E&&e.jsxs("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[10px] text-cyan-400 hover:underline",children:[e.jsx(Ee,{className:"w-3 h-3"}),"View source"]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground font-mono",children:["ID: ",n.syntax_dna?.learning_id]})]})})]},n.id)})]})},Js=[{key:"dna",label:"DNA Focus",emoji:"🧬",desc:"Prioritizes style/form extraction",color:"border-amber-500/30 bg-amber-500/10 text-amber-300"},{key:"teaching",label:"Teaching Focus",emoji:"🎓",desc:"Prioritizes logic/strategy extraction",color:"border-emerald-500/30 bg-emerald-500/10 text-emerald-300"},{key:"balanced",label:"Balanced",emoji:"⚖️",desc:"Extracts both equally",color:"border-cyan-500/30 bg-cyan-500/10 text-cyan-300"}],ee="scout_active_batch";function Qs(r){return r>=7?"text-emerald-400 bg-emerald-500/20":r>=4?"text-amber-400 bg-amber-500/20":"text-red-400 bg-red-500/20"}const Xs=()=>{const[r,c]=a.useState(""),[_,w]=a.useState("balanced"),[l,b]=a.useState("10"),[o,u]=a.useState(!1),[i,d]=a.use
45State(()=>{const t=localStorage.getItem(ee);if(t)try{const{batchId:S,startedAt:A}=JSON.parse(t);if(Date.now()-A<10*60*1e3)return S;localStorage.removeItem(ee)}catch{localStorage.removeItem(ee)}return null}),[n,f]=a.useState([]),[x,E]=a.useState([]),[R,m]=a.useState(null),[y,I]=a.useState(null),[P,g]=a.useState(10),v=a.useCallback(async()=>{const{data:t}=await p.from("brain_pending_learnings").select("*").eq("status","pending").order("relevance_score",{ascending:!1});t&&E(t)},[]);a.useEffect(()=>{if(!i)return;const t=setInterval(async()=>{const{data:S}=await p.from("brain_pending_learnings").select("*").eq("batch_id",i).order("created_at",{ascending:!0});S&&(f(S),v(),S.length>0&&S.every(j=>["pending","error","low_relevance","approved","rejected"].includes(j.status))&&!o&&localStorage.removeItem(ee))},3e3);return()=>clearInterval(t)},[i,v,o]),a.useEffect(()=>{v()},[v]);const F=async()=>{if(!r.trim())return;const t=`batch_${Date.now()}`,S=parseInt(l);d(t),u(!0),f([]),g(S),localStorage.setItem(ee,JSON.stringify({batchId:t,startedAt:Date.now(),limit:S}));const A=r.split(";").map(j=>j.trim()).filter(Boolean);try{const{data:j,error:H}=await p.functions.invoke("autonomous-scout",{body:{queries:A,limit:S,batchId:t,missionFocus:_}});if(H)throw H;k.success(`Mission complete: ${j.processed}/${j.total} sources processed`)}catch(j){k.error(j.message||"Mission failed")}finally{u(!1),localStorage.removeItem(ee),v();const{data:j}=await p.from("brain_pending_learnings").select("*").eq("batch_id",t).order("created_at",{ascending:!0});j&&f(j)}},s=async t=>{I(t.id);try{const{data:{user:S}}=await p.auth.getUser();if(!S)throw new Error("Not authenticated");const A=`learn_${Date.now()}`;await p.from("custom_style_templates").insert({user_id:S.id,name:`[Scout] ${t.base_tone_map||"Trained"} — ${(t.source_title||t.source_url).slice(0,40)}`,syntax_dna:{...t.extracted_dna||{},learning_id:A,composer_mapping:t.synthesis_data?.composer_mapping||[]},logic_rules:t.extracted_rules||[],training_samples:[t.raw_content_preview||""],source_urls:[t.source_url],base_tone_map:t.base_tone_map||"Professional",voice_summary:t.voice_summary||"",is_global:!0}),t.synthesis_data?.substance?.key_teachings?.length&&await p.from("brain_knowledge_snippets").insert({title:`Teachings from ${(t.source_title||t.source_url).slice(0,50)}`,content:[t.synthesis_data.substance.summary,"","• "+t.synthesis_data.substance.key_teachings.join(`
46• `)].join(`
47`),category:"industry_context",is_active:!0,learning_id:A}),await p.from("brain_pending_learnings").update({status:"approved"}).eq("id",t.id),k.success("Learning approved and applied"),v()}catch(S){k.error(S.message||"Approval failed")}I(null)},h=async t=>{await p.from("brain_pending_learnings").update({status:"rejected"}).eq("id",t.id),k.success("Rejected"),v()},C=async()=>{for(const t of x)await s(t)},T=async()=>{const t=x.map(S=>S.id);await p.from("brain_pending_learnings").update({status:"rejected"}).in("id",t),k.success(`Rejected ${t.length} items`),v()};return a.useEffect(()=>{const t=localStorage.getItem(ee);if(t)try{const{limit:S}=JSON.parse(t);S&&g(S),u(!0)}catch{}},[]),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-5 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"text-xs font-medium text-muted-foreground",children:["Search Keywords ",e.jsx("span",{className:"opacity-60",children:"(separate with ; for multiple)"})]}),e.jsx(K,{value:r,onChange:t=>c(t.target.value),placeholder:"e.g., Instagram DM strategies 2024 ; social selling psychology",className:"bg-white/5 border-white/10",disabled:o})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Mission Focus"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:Js.map(t=>e.jsxs("button",{onClick:()=>w(t.key),disabled:o,className:U("rounded-lg border p-3 text-left transition-all",_===t.key?t.color+" ring-1 ring-current":"border-white/5 bg-white/[0.02] text-muted-foreground hover:border-white/10"),children:[e.jsxs("div",{className:"text-sm font-medium",children:[t.emoji," ",t.label]}),e.jsx("div",{className:"text-[10px] mt-0.5 opacity-70",children:t.desc})]},t.key))})]}),e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"space-y-2 w-32",children:[e.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Limit"}),e.jsxs(me,{value:l,onValueChange:b,disabled:o,children:[e.jsx(ue,{className:"bg-white/5 border-white/10",children:e.jsx(he,{})}),e.jsxs(pe,{children:[e.jsx(X,{value:"10",children:"10 sources"}),e.jsx(X,{value:"20",children:"20 sources"}),e.jsx(X,{value:"30",children:"30 sources"})]})]})]}),e.jsxs(L,{onClick:F,disabled:o||!r.trim(),className:"bg-gradient-to-r from-cyan-500 to-violet-500 hover:from-cyan-600 hover:to-violet-600 flex-1",children:[o?e.jsx(M,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(ys,{className:"w-4 h-4 mr-2"}),o?"Mission in progress...":"Start Search Mission"]})]})]}),i&&n.length>0&&e.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:o?"🔍 Processing...":"✅ Mission Complete"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[n.length,"/",P," sources"]})]}),e.jsx(He,{value:n.length/P*100,className:"h-2"}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(t=>e.jsxs("div",{className:U("px-2 py-1 rounded text-[10px] font-medium",t.status==="pending"?"bg-emerald-500/20 text-emerald-300":t.status==="error"?"bg-red-500/20 text-red-300":(t.status==="low_relevance","bg-white/5 text-muted-foreground")),title:t.source_title||t.source_url,children:[t.status==="pending"?"✓":t.status==="error"?"✗":"○"," ",(t.source_title||t.source_url).slice(0,25),"..."]},t.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-sm font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Ke,{className:"w-4 h-4 text-amber-400"}),"Pending Queue (",x.length,")"]}),x.length>1&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(L,{size:"sm",variant:"outline",className:"text-xs border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10",onClick:C,children:"Approve All"}),e.jsx(L,{size:"sm",variant:"outline",className:"text-xs border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:T,children:"Reject All"})]})]}),x.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground text-sm",children:"No pending learnings. Start a search mission above."}):e.jsx("div",{className:"space-y-2",children:x.map(t=>e.jsx(fs,{className:"bg-white/[0.03] border-white/10",children:e.jsxs(bs,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-foreground truncate",children:t.source_title||"Untitled"}),e.jsx("span",{className:U("px-1.5 py-0.5 rounded text-[10px] font-bold",Qs(t.relevance_score)),children:t.relevance_score.toFixed(1)}),t.mission_focus&&e.jsx(B,{variant:"outline",className:"text-[10px] border-white/10",children:t.mission_focus==="dna"?"🧬 DNA":t.mission_focus==="teaching"?"🎓 Teaching":"⚖️ Balanced"}),t.base_tone_map&&e.jsx(B,{variant:"outline",className:"text-[10px] border-white/10",children:t.base_tone_map})]}),e.jsxs("a",{href:t.source_url,target:"_blank",rel:"noopener noreferrer",className:"text-[11px] text-muted-foreground hover:text-cyan-400 flex items-center gap-1 mt-1",children:[e.jsx(Ee,{className:"w-3 h-3"}),t.source_url.slice(0,60),"..."]}),t.voice_summary&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5 line-clamp-2",children:t.voice_summary}),t.synthesis_data?.composer_mapping&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:t.synthesis_data.composer_mapping.map((S,A)=>e.jsxs("span",{className:"px-1.5 py-0.5 rounded bg-rose-500/15 text-rose-300 text-[10px] font-medium border border-rose-500/20",children:[S.pillar," → ",S.sub_style]},A))})]}),e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx(L,{size:"sm",onClick:()=>s(t),disabled:y===t.id,className:"bg-emerald-600 hover:bg-emerald-700 text-white h-8 px-3",children:y===t.id?e.jsx(M,{className:"w-3 h-3 animate-spin"}):e.jsx(ie,{className:"w-3 h-3"})}),e.jsx(L,{size:"sm",variant:"outline",onClick:()=>h(t),className:"border-red-500/30 text-red-400 hover:bg-red-500/10 h-8 px-3",children:e.jsx(js,{className:"w-3 h-3"})})]})]}),e.jsxs(Ie,{open:R===t.id,onOpenChange:S=>m(S?t.id:null),children:[e.jsxs(Re,{className:"flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ce,{className:U("w-3 h-3 transition-transform",R===t.id&&"rotate-180")}
47),R===t.id?"Hide":"Show"," full synthesis"]}),e.jsx(Ae,{className:"mt-3",children:t.synthesis_data&&e.jsx(De,{data:t.synthesis_data,exportSubstance:!0,exportForm:!0,onExportSubstanceChange:()=>{},onExportFormChange:()=>{},sourceUrl:t.source_url,readOnly:!0})})]})]})},t.id))})]})]})};function ba(){const{isAdmin:r,loading:c}=Xe(),_=Ze(),[w,l]=a.useState(!1),[b,o]=a.useState({laws:0,snippets:0,globalStyles:0}),[u,i]=a.useState(0);return a.useEffect(()=>{!c&&!r&&_("/")},[r,c,_]),a.useEffect(()=>{if(!r)return;(async()=>{const[n,f,x,E]=await Promise.all([p.from("brain_iron_laws").select("id",{count:"exact",head:!0}).eq("is_active",!0),p.from("brain_knowledge_snippets").select("id",{count:"exact",head:!0}).eq("is_active",!0),p.from("custom_style_templates").select("id",{count:"exact",head:!0}).eq("is_global",!0),p.from("brain_pending_learnings").select("id",{count:"exact",head:!0}).eq("status","pending")]);o({laws:n.count||0,snippets:f.count||0,globalStyles:x.count||0}),i(E.count||0)})()},[r]),c?e.jsx("div",{className:"flex items-center justify-center min-h-[60vh]",children:e.jsx(M,{className:"w-8 h-8 animate-spin text-primary"})}):r?e.jsxs("div",{className:"space-y-4 md:space-y-6 px-3 md:px-0 pb-20 md:pb-0",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl flex items-center justify-center shrink-0",style:{background:"rgba(139, 92, 246, 0.2)"},children:e.jsx(Y,{className:"w-5 h-5",style:{color:"#8B5CF6"}})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl md:text-2xl font-bold text-foreground",children:"Leadfo Brain"}),e.jsx("p",{className:"text-xs md:text-sm text-muted-foreground",children:"Command center for AI intelligence"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(L,{onClick:()=>l(!0),size:"sm",className:"bg-gradient-to-r from-cyan-500 to-violet-500 hover:from-cyan-600 hover:to-violet-600",children:[e.jsx(oe,{className:"w-4 h-4 mr-1"}),"Feed the Brain"]}),e.jsx(zs,{})]})]}),e.jsxs("div",{className:"flex items-center gap-2 px-3 md:px-4 py-2 rounded-xl bg-white/5 border border-white/10 text-xs text-muted-foreground overflow-x-auto scrollbar-hide whitespace-nowrap",children:[e.jsx("span",{children:"Pipeline:"}),e.jsxs("span",{className:"px-2 py-0.5 rounded bg-violet-500/20 text-violet-300 shrink-0",children:[b.laws," Iron Laws"]}),e.jsx("span",{children:"→"}),e.jsxs("span",{className:"px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 shrink-0",children:[b.snippets," Knowledge Snippets"]}),e.jsx("span",{children:"→"}),e.jsxs("span",{className:"px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 shrink-0",children:[b.globalStyles," Global Styles"]}),e.jsx("span",{children:"→"}),e.jsx("span",{className:"px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 shrink-0",children:"Business Context"})]}),e.jsxs(Me,{defaultValue:"iron-laws",className:"w-full",children:[e.jsx("div",{className:"overflow-x-auto scrollbar-hide -mx-3 px-3 md:mx-0 md:px-0",children:e.jsxs(Be,{className:"w-max md:w-full justify-start bg-white/5 border border-white/10 p-1 rounded-xl h-auto",children:[e.jsx(J,{value:"iron-laws",className:"data-[state=active]:bg-violet-500/20 data-[state=active]:text-violet-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap",children:"🛡️ Iron Laws"}),e.jsx(J,{value:"styles",className:"data-[state=active]:bg-cyan-500/20 data-[state=active]:text-cyan-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap",children:"🎨 Styles"}),e.jsx(J,{value:"knowledge",className:"data-[state=active]:bg-emerald-500/20 data-[state=active]:text-emerald-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap",children:"📚 Knowledge"}),e.jsx(J,{value:"feedback",className:"data-[state=active]:bg-amber-500/20 data-[state=active]:text-amber-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap",children:"⭐ Feedback"}),e.jsx(J,{value:"control-center",className:"data-[state=active]:bg-rose-500/20 data-[state=active]:text-rose-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap",children:"🎛️ Control"}),e.jsx(J,{value:"history",className:"data-[state=active]:bg-indigo-500/20 data-[state=active]:text-indigo-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap",children:"📜 History"}),e.jsxs(J,{value:"scout",className:"data-[state=active]:bg-sky-500/20 data-[state=active]:text-sky-300 rounded-lg px-3 md:px-4 py-2 text-xs md:text-sm whitespace-nowrap relative",children:[e.jsx(Ns,{className:"w-4 h-4 mr-1"}),"Scout",u>0&&e.jsx("span",{className:"ml-1.5 px-1.5 py-0.5 rounded-full bg-amber-500 text-[10px] font-bold text-black",children:u})]})]})}),e.jsxs(Q,{value:"iron-laws",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Mandatory rules that override all generation output"}),e.jsx(Ls,{})]}),e.jsxs(Q,{value:"styles",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Trained writing patterns — Global styles apply to all users"}),e.jsx(Bs,{})]}),e.jsxs(Q,{value:"knowledge",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Context snippets injected into prompts by category"}),e.jsx(Gs,{})]}),e.jsxs(Q,{value:"feedback",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Learn from excellent messages to improve global rules"}),e.jsx(Us,{})]}),e.jsxs(Q,{value:"control-center",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Pillar-first view of all trained variations with enrich & delete controls"}),e.jsx(Ks,{})]}),e.jsxs(Q,{value:"history",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Timeline of all Brain learnings with full detail and cascade deletion"}),e.jsx(Ys,{})]}),e.jsxs(Q,{value:"scout",className:"mt-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Autonomous content discovery — search, scrape, analyze, and queue for approval"}),e.jsx(Xs,{})]})]}),e.jsx(Ye,{isOpen:w,onClose:()=>l(!1),onComplete:()=>{o(d=>({...d}))}})]}):null}export{ba 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.