@realtimex/realtimex-alchemy 1.0.59 → 1.0.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.0.61] - 2026-01-28
9
+
10
+ ### Fixed
11
+ - **Profile Sync**: Fixed an issue where names provided during signup were not correctly syncing to the user profile. Added a robust database trigger to propagate metadata from `auth.users` to `public.profiles`.
12
+ - **UI**: Updated Account Settings to gracefully fallback to auth metadata if the profile record is still initializing.
13
+
14
+ ## [1.0.60] - 2026-01-28
15
+
16
+ ### Added
17
+ - **Content Intelligence**: Implemented "Alchemist's Distillation" – The AI now actively cleanses mined content during analysis, stripping navigation, ads, and "read more" noise while preserving the core text verbatim.
18
+ - **Data Quality**: Signals now store the AI-refined version of content (`refined_content`) instead of raw HTML scrapes, significantly improving the quality of future RAG retrieval.
19
+
20
+ ### Improved
21
+ - **Context Window**: Increased the analysis safety ceiling from 10k to **200k characters** (~50k tokens). This ensures deep-dive articles, long-form essays, and technical documentation are analyzed in full without truncation.
22
+
8
23
  ## [1.0.59] - 2026-01-28
9
24
 
10
25
  ### Added
@@ -120,8 +120,12 @@ export class AlchemistService {
120
120
  content = `Page Title: ${entry.title} (Login/paywall required - content not accessible)`;
121
121
  }
122
122
  else {
123
- // Truncate to avoid token limits (keep ~8000 chars)
124
- const truncated = cleaned.length > 10000 ? cleaned.substring(0, 10000) + '...' : cleaned;
123
+ // Safety ceiling to prevent pathological cases (e.g., entire doc sites scraped as one page)
124
+ // 200k chars 50k tokens - only triggers on edge cases, not normal articles
125
+ const MAX_SAFE_CHARS = 200000;
126
+ const truncated = cleaned.length > MAX_SAFE_CHARS
127
+ ? cleaned.substring(0, MAX_SAFE_CHARS) + '\n\n[Content truncated - exceeds 200k chars]'
128
+ : cleaned;
125
129
  content = `Page Title: ${entry.title}\nContent: ${truncated}`;
126
130
  }
127
131
  }
@@ -142,11 +146,25 @@ export class AlchemistService {
142
146
  level: 'info',
143
147
  userId
144
148
  }, supabase);
145
- // 3. LLM Analysis
149
+ // 3. LLM Analysis (+ Content Cleaning)
146
150
  const response = await this.analyzeContent(content, finalUrl, settings, learningContext);
147
151
  const duration = Date.now() - startAnalysis;
148
152
  // 4. Save Signal (ALWAYS save for Active Learning - Low scores = candidates for boost)
149
153
  console.log(`[AlchemistService] Saving signal (${response.score}%)...`);
154
+ // DECISION: Use "refined_content" from LLM if available and valid, otherwise fallback to our cleaned version
155
+ let finalContentToSave = content;
156
+ if (!isGatedContent && response.refined_content && response.refined_content.length > 50) {
157
+ // Use the LLM's pristine version
158
+ finalContentToSave = response.refined_content;
159
+ // Re-prefix title if lost (optional, but good for context)
160
+ if (!finalContentToSave.startsWith('Page Title:')) {
161
+ finalContentToSave = `Page Title: ${entry.title}\n\n${finalContentToSave}`;
162
+ }
163
+ }
164
+ else {
165
+ // Fallback: Use original content (already has 200k safety ceiling applied above)
166
+ finalContentToSave = content;
167
+ }
150
168
  const { data: insertedSignal, error: insertError } = await supabase
151
169
  .from('signals')
152
170
  .insert([{
@@ -158,13 +176,14 @@ export class AlchemistService {
158
176
  category: response.category,
159
177
  entities: response.entities,
160
178
  tags: (response.tags || []).map(t => t.toLowerCase().trim()),
161
- content: content,
179
+ content: finalContentToSave,
162
180
  // Mark as dismissed if low score OR gated content
163
181
  is_dismissed: response.score < 50 || isGatedContent,
164
182
  metadata: {
165
183
  original_source_url: entry.url,
166
184
  resolved_at: new Date().toISOString(),
167
- is_gated: isGatedContent
185
+ is_gated: isGatedContent,
186
+ ai_cleaned: !!(response.refined_content && response.refined_content.length > 50)
168
187
  }
169
188
  }])
170
189
  .select()
@@ -281,7 +300,7 @@ export class AlchemistService {
281
300
  - "Page not found", error pages, access denied
282
301
  - App store pages, download prompts
283
302
  - Empty or placeholder content
284
- For these, return: score=0, category="Other", summary="[Login wall/Navigation page/etc]", tags=[], entities=[]
303
+ For these, return: score=0, category="Other", summary="[Login wall/Navigation page/etc]", tags=[], entities=[], refined_content=""
285
304
 
286
305
  2. SCORING GUIDE:
287
306
  - High (80-100): Original research, data, insights, technical depth. MATCHES USER INTERESTS.
@@ -297,6 +316,13 @@ export class AlchemistService {
297
316
  "machine learning", "startups", "regulations", "cybersecurity", "investing"
298
317
  NEVER include: "login", "navigation", "authentication", "menu", "footer", "social media", "facebook", "meta"
299
318
 
319
+ 5. CONTENT REFINEMENT (The "Alchemist's Distillation"):
320
+ - You must CLEAN the input content to remove noise.
321
+ - Remove: "Read more" links, social media footers, "Subscribe" prompts, navigation elements, ads.
322
+ - KEEP: The core article text VERBATIM. Do not rewrite sentences. Do not fix grammar. Only remove noise lines.
323
+ - If the content is already clean, return it as is.
324
+ - This "refined_content" will be stored as the permanent record.
325
+
300
326
  Return STRICT JSON:
301
327
  {
302
328
  "score": number (0-100),
@@ -304,7 +330,8 @@ export class AlchemistService {
304
330
  "summary": string (1-sentence concise gist, or "[Junk page]" if score=0),
305
331
  "entities": string[] (people, companies, products mentioned),
306
332
  "tags": string[] (3-5 TOPIC tags only, no platform/UI terms),
307
- "relevant": boolean (true if score > 50)
333
+ "relevant": boolean (true if score > 50),
334
+ "refined_content": string (The noise-free, verbatim article text)
308
335
  }
309
336
  `;
310
337
  const response = await sdk.llm.chat([
@@ -69,7 +69,7 @@ ${j}`}class Ct extends Error{constructor({message:t,code:n,cause:r,name:s}){var
69
69
  `,"aria-label":`Digit ${v+1}`},v))})}const vh=[{code:"en",label:"English",flag:"🇺🇸"},{code:"fr",label:"Français",flag:"🇫🇷"},{code:"es",label:"Español",flag:"🇪🇸"},{code:"ko",label:"한국어",flag:"🇰🇷"},{code:"ja",label:"日本語",flag:"🇯🇵"},{code:"vi",label:"Tiếng Việt",flag:"🇻🇳"}];function Np({collapsed:e=!1,position:t="bottom"}){const{i18n:n}=Ze(),[r,s]=R.useState(!1),o=R.useRef(null),a=vh.find(u=>u.code===n.language)||vh[0];R.useEffect(()=>{const u=f=>{o.current&&!o.current.contains(f.target)&&s(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[]);const c=u=>{n.changeLanguage(u),s(!1)};return h.jsxs("div",{className:"relative",ref:o,children:[h.jsxs("button",{onClick:()=>s(!r),className:`flex items-center gap-2 px-3 py-1.5 rounded-lg bg-white/5 border border-white/10 hover:bg-white/10 transition-all text-xs font-medium text-fg/70 ${e?"justify-center px-1.5":""}`,title:e?a.label:void 0,children:[!e&&h.jsx(jj,{size:14,className:"text-primary"}),h.jsx("span",{children:a.flag}),!e&&h.jsxs(h.Fragment,{children:[h.jsx("span",{className:"hidden sm:inline",children:a.label}),h.jsx(Ps,{size:12,className:`transition-transform duration-300 ${r?"rotate-180":""}`})]})]}),h.jsx(Pt,{children:r&&h.jsx(Fe.div,{initial:{opacity:0,y:10,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.95},className:`absolute ${e?"left-0":"right-0"} ${t==="top"?"bottom-full mb-2":"top-full mt-2"} w-48 bg-[#1a1a1a] border border-white/10 rounded-xl shadow-2xl z-[9999] overflow-y-auto max-h-[280px] scrollbar-thin scrollbar-thumb-white/10`,children:h.jsx("div",{className:"py-1",children:vh.map(u=>h.jsxs("button",{onClick:()=>c(u.code),className:"flex items-center justify-between w-full px-4 py-2.5 text-xs text-left hover:bg-white/5 transition-colors",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("span",{children:u.flag}),h.jsx("span",{className:u.code===n.language?"text-primary font-bold":"text-fg/70",children:u.label})]}),u.code===n.language&&h.jsx(Ts,{size:14,className:"text-primary"})]},u.code))})})})]})}function dL({onAuthSuccess:e,isInitialized:t=!0}){const{t:n}=Ze(),[r,s]=R.useState(""),[o,a]=R.useState(""),[c,u]=R.useState(""),[f,p]=R.useState(""),[g,y]=R.useState(!1),[v,b]=R.useState(!t),[w,k]=R.useState(null),[j,C]=R.useState("password"),[S,P]=R.useState("email"),[N,A]=R.useState(""),$=async B=>{B.preventDefault(),y(!0),k(null);try{if(v){const{error:L}=await oe.auth.signUp({email:r,password:o,options:{data:{first_name:c,last_name:f,full_name:`${c} ${f}`.trim()}}});if(L)throw L;e()}else if(j==="password"){const{error:L}=await oe.auth.signInWithPassword({email:r,password:o});if(L)throw L;e()}else if(j==="otp")if(S==="email"){const{error:L}=await oe.auth.signInWithOtp({email:r,options:{shouldCreateUser:!1}});if(L)throw L;P("verify")}else await G()}catch(L){k(L.message)}finally{y(!1)}},G=async()=>{y(!0),k(null);try{const{data:B,error:L}=await oe.auth.verifyOtp({email:r,token:N,type:"magiclink"});if(L)throw L;if(!B.session)throw new Error("Failed to create session");e()}catch(B){k(B.message||n("auth.invalid_code"))}finally{y(!1)}};return h.jsx("div",{className:"flex flex-col items-center justify-center p-8 h-full bg-gradient-to-t from-bg to-bg/50",children:h.jsxs(Fe.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"w-full max-w-xl glass p-12 space-y-10 relative",children:[h.jsx("div",{className:"absolute top-4 right-4 z-50",children:h.jsx(Np,{position:"bottom"})}),h.jsxs("div",{className:"text-center space-y-2 pt-2",children:[h.jsx("h2",{className:"text-3xl font-black italic tracking-tighter uppercase",children:n(!t&&v?"auth.title_init":v?"auth.title_join":j==="otp"?"auth.title_mystic":"auth.title_login")}),h.jsx("p",{className:"text-xs text-fg/40 font-mono tracking-widest uppercase",children:n(!t&&v?"auth.desc_init":j==="otp"?S==="email"?"auth.desc_mystic_email":"auth.desc_mystic_code":"auth.desc_login")})]}),h.jsx("form",{onSubmit:$,className:"space-y-4",children:h.jsxs(Pt,{mode:"wait",children:[v&&h.jsxs(Fe.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"grid grid-cols-2 gap-4 overflow-hidden",children:[h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:n("auth.first_name")}),h.jsx("input",{type:"text",value:c,onChange:B=>u(B.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:n("auth.first_name_placeholder"),required:!0})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:n("auth.last_name")}),h.jsx("input",{type:"text",value:f,onChange:B=>p(B.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:n("auth.last_name_placeholder"),required:!0})]})]},"signup-fields"),j==="otp"&&S==="verify"?h.jsxs(Fe.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6 py-4",children:[h.jsx("div",{className:"flex justify-center",children:h.jsx(uL,{value:N,onChange:A,length:6,onComplete:B=>{A(B)},error:!!w})}),h.jsx("button",{type:"button",onClick:()=>P("email"),className:"w-full text-[10px] font-bold uppercase text-primary/40 hover:text-primary transition-colors tracking-widest",children:n("auth.change_email")}),h.jsxs("button",{type:"button",disabled:g||N.length!==6,onClick:G,className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center justify-center gap-2",children:[g?h.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}):h.jsx(Hy,{size:18}),n("auth.verify_code")]})]},"otp-verify"):h.jsxs(Fe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"space-y-4",children:[h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:n("auth.email_address")}),h.jsxs("div",{className:"relative",children:[h.jsx(Tj,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg/20",size:16}),h.jsx("input",{type:"email",value:r,onChange:B=>s(B.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 pl-10 pr-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:n("auth.email_placeholder"),required:!0})]})]}),(v||j==="password")&&h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:n("auth.complexity_key")}),h.jsxs("div",{className:"relative",children:[h.jsx(Cj,{className:"absolute left-3 top-1/2 -translate-y-1/2 text-fg/20",size:16}),h.jsx("input",{type:"password",value:o,onChange:B=>a(B.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 pl-10 pr-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:n("auth.password_placeholder"),required:!0})]})]}),h.jsxs("button",{type:"submit",disabled:g,className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center justify-center gap-2",children:[g&&h.jsx("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}),v?h.jsx($j,{size:18}):h.jsx(Hy,{size:18}),n(v?"auth.init_account":j==="otp"?"auth.send_code":"auth.unseal_engine")]})]},"base-login")]})}),w&&j==="password"&&h.jsx(Fe.p,{initial:{opacity:0},animate:{opacity:1},className:"text-xs text-error font-medium bg-error/10 p-3 rounded-lg border border-error/10",children:w}),h.jsxs("div",{className:"space-y-4",children:[!v&&h.jsx("div",{className:"flex flex-col gap-2",children:j==="password"?h.jsxs("button",{type:"button",onClick:()=>{C("otp"),P("email"),k(null)},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all text-fg/40 hover:text-primary",children:[h.jsx(wj,{size:16})," ",n("auth.sign_in_code")]}):h.jsxs("button",{type:"button",onClick:()=>{C("password"),k(null)},className:"w-full flex items-center justify-center gap-2 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all text-fg/40 hover:text-primary",children:[h.jsx(c_,{size:16})," ",n("auth.sign_in_password")]})}),h.jsxs("p",{className:"text-center text-xs text-fg/40",children:[n(v?"auth.already_alchemist":"auth.new_to_alchemy")," "," ",h.jsx("button",{onClick:()=>{b(!v),C("password"),k(null)},className:"text-primary font-bold hover:underline",children:n(v?"auth.login_instead":"auth.create_account")})]})]})]})})}function hL(e){const t=e.trim();return t?t.startsWith("http://")||t.startsWith("https://")?t:`https://${t}.supabase.co`:""}function fL(e){const t=e.match(/https?:\/\/([^.]+)\.supabase\.co/);return t?t[1]:""}function $w({onComplete:e,open:t=!0,canClose:n=!1}){const{t:r}=Ze(),[s,o]=R.useState("welcome"),[a,c]=R.useState(""),[u,f]=R.useState(""),[p,g]=R.useState(""),[y,v]=R.useState(""),[b,w]=R.useState(null),[k,j]=R.useState(!1),[C,S]=R.useState([]),[P,N]=R.useState("idle"),A=R.useRef(null);if(R.useEffect(()=>{A.current?.scrollIntoView({behavior:"smooth"})},[C]),!t)return null;const $=async()=>{w(null),j(!0),o("validating");const L=hL(a),Y=u.trim(),X=await oL(L,Y);if(X.valid){sL({url:L,anonKey:Y});try{const H=Fw(L,Y),{data:K,error:te}=await H.from("init_state").select("is_initialized").single();if(!te&&K&&K.is_initialized>0){o("success"),setTimeout(()=>{window.location.reload()},1500);return}}catch{console.log("[SetupWizard] init_state check failed, showing migration step")}const de=fL(L);g(de),o("migration"),j(!1)}else w(X.error||r("common.error")),o("credentials"),j(!1)},G=async()=>{if(!p){w(r("setup.project_id_required"));return}if(!y){w(r("setup.access_token_required"));return}w(null),S([]),N("running"),o("migrating");try{const Y=(await fetch("/api/migrate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectId:p,accessToken:y})})).body?.getReader(),X=new TextDecoder;if(!Y)throw new Error(r("setup.stream_error"));for(;;){const{done:de,value:H}=await Y.read();if(de)break;const te=X.decode(H).split(`
70
70
  `).filter(ne=>ne.startsWith("data: "));for(const ne of te)try{const J=JSON.parse(ne.slice(6));J.type==="done"?J.data==="success"?(N("success"),o("success"),setTimeout(()=>{window.location.reload()},2e3)):(N("failed"),w(r("setup.migration_failed_logs"))):S(le=>[...le,J.data])}catch{}}}catch(L){N("failed"),w(L.message||"Migration failed"),S(Y=>[...Y,`Error: ${L.message}`])}},B=()=>{o("success"),setTimeout(()=>{window.location.reload()},1500)};return h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-6 bg-bg/80 backdrop-blur-sm",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:"w-full max-w-xl glass p-12 space-y-10 relative",children:[h.jsx("div",{className:"absolute top-4 right-4 z-50",children:h.jsx(Np,{position:"bottom"})}),h.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/10 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2 pointer-events-none"}),h.jsxs(Pt,{mode:"wait",children:[s==="welcome"&&h.jsxs(Fe.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 bg-primary/10 rounded-xl",children:h.jsx(ta,{className:"w-6 h-6 text-primary"})}),h.jsx("div",{className:"flex-1",children:h.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:r("setup.welcome_title")})})]}),h.jsx("p",{className:"text-sm text-fg/50 font-medium",children:r("setup.welcome_desc")})]}),h.jsxs("div",{className:"glass bg-white/5 border-white/10 p-4 rounded-xl space-y-3",children:[h.jsx("p",{className:"text-xs font-bold uppercase tracking-widest text-primary/70",children:r("setup.requirements")}),h.jsxs("ul",{className:"space-y-2",children:[h.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[h.jsx(Ts,{className:"w-4 h-4 text-emerald-500"})," ",r("setup.project_url")]}),h.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[h.jsx(Ts,{className:"w-4 h-4 text-emerald-500"})," ",r("setup.anon_key")]}),h.jsxs("li",{className:"flex items-center gap-2 text-sm text-fg/60",children:[h.jsx(Ts,{className:"w-4 h-4 text-emerald-500"})," ",r("account.credentials")]})]})]}),h.jsxs("div",{className:"flex flex-col gap-3",children:[h.jsxs("a",{href:"https://supabase.com",target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-center gap-2 py-3 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/60",children:[r("setup.forge_project")," ",h.jsx($i,{size:14})]}),h.jsxs("button",{onClick:()=>o("credentials"),className:"w-full py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-2",children:[r("setup.begin_init")," ",h.jsx(aj,{size:18})]})]})]},"welcome"),s==="credentials"&&h.jsxs(Fe.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:r("setup.credentials_title")}),h.jsx("p",{className:"text-sm text-fg/50 font-medium lowercase",children:r("setup.credentials_desc")})]}),h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:r("setup.project_url")}),h.jsx("input",{type:"text",value:a,onChange:L=>c(L.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:r("setup.project_url_placeholder")})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:r("setup.anon_key")}),h.jsx("input",{type:"password",value:u,onChange:L=>f(L.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all",placeholder:r("setup.anon_key_placeholder")})]})]}),b&&h.jsxs("div",{className:"bg-error/10 border border-error/20 p-3 rounded-xl flex items-center gap-3",children:[h.jsx(br,{className:"w-5 h-5 text-error"}),h.jsx("p",{className:"text-xs text-error font-bold tracking-tight",children:b})]}),h.jsxs("div",{className:"flex gap-3",children:[h.jsx("button",{onClick:()=>o("welcome"),className:"flex-1 py-4 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:r("common.back")}),h.jsxs("button",{onClick:$,disabled:!a||!u,className:"flex-[2] py-4 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.01] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2",children:[r("setup.connect_essence")," ",h.jsx(nn,{size:18})]})]})]},"credentials"),s==="validating"&&h.jsxs(Fe.div,{initial:{opacity:0},animate:{opacity:1},className:"flex flex-col items-center justify-center py-12 space-y-6",children:[h.jsxs("div",{className:"relative",children:[h.jsx("div",{className:"absolute inset-0 bg-primary/20 blur-xl rounded-full"}),h.jsx(Rt,{className:"w-16 h-16 animate-spin text-primary relative z-10"})]}),h.jsxs("div",{className:"text-center space-y-2",children:[h.jsx("h3",{className:"text-xl font-bold italic uppercase tracking-tighter",children:r("setup.validating")}),h.jsx("p",{className:"text-sm text-fg/40 font-mono tracking-widest uppercase animate-pulse",children:r("setup.resonance")})]})]},"validating"),s==="migration"&&h.jsxs(Fe.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},className:"space-y-6",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 bg-accent/10 rounded-xl",children:h.jsx(oc,{className:"w-6 h-6 text-accent"})}),h.jsx("div",{className:"flex-1",children:h.jsx("h2",{className:"text-2xl font-black italic tracking-tighter uppercase",children:r("setup.init_schema")})})]}),h.jsx("p",{className:"text-sm text-fg/50 font-medium",children:r("setup.schema_desc")})]}),h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:r("setup.project_id")}),h.jsx("input",{type:"text",value:p,onChange:L=>g(L.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all font-mono",placeholder:r("setup.project_id_placeholder")}),h.jsx("p",{className:"text-[10px] text-fg/30 ml-1",children:r("setup.project_id_help")})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:r("setup.access_token")}),h.jsx("input",{type:"password",value:y,onChange:L=>v(L.target.value),className:"w-full bg-black/20 border border-border/20 rounded-xl py-3 px-4 text-sm focus:border-primary/50 outline-none transition-all font-mono",placeholder:r("setup.access_token_placeholder")}),h.jsxs("p",{className:"text-[10px] text-fg/30 ml-1",children:["Generate at"," ",h.jsx("a",{href:"https://supabase.com/dashboard/account/tokens",target:"_blank",rel:"noopener noreferrer",className:"text-accent hover:underline",children:r("setup.access_token_link")})]})]})]}),b&&h.jsxs("div",{className:"bg-error/10 border border-error/20 p-3 rounded-xl flex items-center gap-3",children:[h.jsx(br,{className:"w-5 h-5 text-error"}),h.jsx("p",{className:"text-xs text-error font-bold tracking-tight",children:b})]}),h.jsxs("div",{className:"flex gap-3",children:[h.jsx("button",{onClick:B,className:"flex-1 py-4 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:r("common.skip")}),h.jsxs("button",{onClick:G,disabled:!p||!y,className:"flex-[2] py-4 bg-gradient-to-r from-accent to-primary text-white font-bold rounded-xl shadow-lg glow-accent hover:scale-[1.01] active:scale-95 transition-all disabled:opacity-50 disabled:grayscale flex items-center justify-center gap-2",children:[h.jsx(Oj,{size:18})," ",r("setup.run_migrations")]})]})]},"migration"),s==="migrating"&&h.jsxs(Fe.div,{initial:{opacity:0},animate:{opacity:1},className:"space-y-6",children:[h.jsxs("div",{className:"space-y-2",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(Rt,{className:"w-6 h-6 animate-spin text-accent"}),h.jsx("h2",{className:"text-xl font-black italic tracking-tighter uppercase",children:r("setup.running_migrations")})]}),h.jsx("p",{className:"text-sm text-fg/40",children:r("setup.take_minute")})]}),h.jsxs("div",{className:"bg-black/40 border border-border/20 rounded-xl p-4 h-64 overflow-y-auto font-mono text-xs",children:[C.map((L,Y)=>h.jsx("div",{className:`py-0.5 ${L.includes("✅")||L.includes("SUCCESS")?"text-emerald-400":L.includes("❌")||L.includes("Error")?"text-red-400":L.includes("⚠️")?"text-amber-400":"text-fg/60"}`,children:L},Y)),h.jsx("div",{ref:A})]}),P==="failed"&&h.jsxs("div",{className:"flex gap-3",children:[h.jsxs("button",{onClick:()=>o("migration"),className:"flex-1 py-3 border border-border/20 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-white/5 transition-all text-fg/40",children:[h.jsx(c_,{size:14,className:"inline mr-2"})," ",r("setup.back")]}),h.jsx("button",{onClick:G,className:"flex-1 py-3 bg-accent/20 border border-accent/30 rounded-xl text-xs font-bold uppercase tracking-widest hover:bg-accent/30 transition-all text-accent",children:r("setup.retry")})]})]},"migrating"),s==="success"&&h.jsxs(Fe.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"flex flex-col items-center justify-center py-12 space-y-6",children:[h.jsx("div",{className:"p-4 bg-emerald-500/20 rounded-full",children:h.jsx(Cs,{className:"w-16 h-16 text-emerald-500"})}),h.jsxs("div",{className:"text-center space-y-2",children:[h.jsx("h3",{className:"text-2xl font-black italic uppercase tracking-tighter",children:r("setup.engine_aligned")}),h.jsx("p",{className:"text-sm text-fg/40 font-mono tracking-widest uppercase",children:r("setup.restarting")})]})]},"success")]})]})})}const Kr={chrome:{icon:h.jsx(yj,{size:18}),name:"Google Chrome",color:"text-yellow-500"},firefox:{icon:h.jsx(Bd,{size:18}),name:"Mozilla Firefox",color:"text-orange-500"},safari:{icon:h.jsx(Bd,{size:18}),name:"Safari",color:"text-blue-500"},edge:{icon:h.jsx(Bd,{size:18}),name:"Microsoft Edge",color:"text-cyan-500"},brave:{icon:h.jsx(nn,{size:18}),name:"Brave",color:"text-orange-400"},arc:{icon:h.jsx(nn,{size:18}),name:"Arc",color:"text-purple-500"}};function pL({sources:e,onChange:t}){const{t:n}=Ze(),[r,s]=R.useState(!1),[o,a]=R.useState({}),[c,u]=R.useState(""),[f,p]=R.useState("chrome"),[g,y]=R.useState(!1),v=async()=>{s(!0);try{const{data:C}=await Qe.get("/api/browser-paths/detect");a(C)}catch(C){console.error("Detection failed:",C)}finally{s(!1)}},b=C=>{const S=o[C];if(!S||!S.found||!S.valid||e.find(A=>A.browser===C&&A.path===S.path))return;const N={browser:C,path:S.path,enabled:!0,label:`${Kr[C].name} (${n("engine.auto_detected")})`};t([...e,N])},w=async()=>{if(c.trim()){y(!0);try{const{data:C}=await Qe.post("/api/browser-paths/validate",{path:c});if(!C.valid){alert(n("engine.invalid_path",{error:C.error||n("engine.not_a_browser_db")})),y(!1);return}const S={browser:f,path:c,enabled:!0,label:`${Kr[f].name} (${n("engine.custom")})`};t([...e,S]),u("")}catch(C){console.error("Validation failed:",C),alert(n("engine.validation_failed"))}finally{y(!1)}}},k=C=>{const S=[...e];S[C].enabled=!S[C].enabled,t(S)},j=C=>{t(e.filter((S,P)=>P!==C))};return h.jsxs("div",{className:"space-y-6",children:[h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(sc,{size:14})," ",n("engine.auto_detect_title")]}),h.jsxs("button",{onClick:v,disabled:r,className:"px-3 py-1.5 text-xs font-bold uppercase tracking-widest bg-primary/10 hover:bg-primary/20 text-primary rounded-lg transition-all flex items-center gap-2",children:[r?h.jsx(Rt,{size:12,className:"animate-spin"}):h.jsx(sc,{size:12}),n(r?"engine.scanning":"engine.scan_system")]})]}),Object.keys(o).length>0&&h.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:Object.keys(Kr).map(C=>{const S=o[C],P=Kr[C],N=e.some(A=>A.browser===C&&A.path===S?.path);return h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`glass p-4 rounded-xl border ${S?.found&&S?.valid?"border-success/20 bg-success/5":S?.found?"border-error/20 bg-error/5":"border-border/10"}`,children:[h.jsxs("div",{className:"flex items-start justify-between mb-2",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("div",{className:P.color,children:P.icon}),h.jsx("span",{className:"text-sm font-bold",children:P.name})]}),S?.found&&S?.valid?h.jsx(Ts,{size:16,className:"text-success"}):S?.found?h.jsx(br,{size:16,className:"text-error"}):h.jsx(Cn,{size:16,className:"text-fg/20"})]}),S?.found?h.jsxs(h.Fragment,{children:[h.jsx("p",{className:"text-[10px] font-mono text-fg/40 truncate mb-2",children:S.path}),S.valid?h.jsx("button",{onClick:()=>b(C),disabled:N,className:`w-full py-1.5 text-xs font-bold uppercase tracking-widest rounded-lg transition-all ${N?"bg-fg/5 text-fg/30 cursor-not-allowed":"bg-success/10 hover:bg-success/20 text-success"}`,children:n(N?"engine.already_added":"engine.add_source")}):h.jsx("p",{className:"text-[10px] text-error font-medium",children:S.error})]}):h.jsx("p",{className:"text-[10px] text-fg/30 italic",children:n("engine.not_found")})]},C)})})]}),h.jsxs("div",{className:"space-y-3",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(_j,{size:14})," ",n("engine.add_custom_path")]}),h.jsxs("div",{className:"glass p-4 rounded-xl space-y-3",children:[h.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[h.jsx("select",{value:f,onChange:C=>p(C.target.value),className:"bg-black/20 border border-border/5 rounded-xl py-2 px-3 text-sm focus:border-primary/30 outline-none transition-all",children:Object.keys(Kr).map(C=>h.jsx("option",{value:C,children:Kr[C].name},C))}),h.jsx("input",{type:"text",value:c,onChange:C=>u(C.target.value),placeholder:n("engine.custom_path_placeholder"),className:"col-span-2 bg-black/20 border border-border/5 rounded-xl py-2 px-3 text-sm focus:border-primary/30 outline-none transition-all"})]}),h.jsxs("button",{onClick:w,disabled:!c.trim()||g,className:"w-full py-2.5 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg hover:scale-[1.01] active:scale-95 transition-all flex items-center justify-center gap-2 disabled:opacity-50 disabled:grayscale",children:[g?h.jsx(Rt,{size:16,className:"animate-spin"}):h.jsx(Mf,{size:16}),n(g?"engine.validating":"engine.add_custom_source")]})]})]}),e.length>0&&h.jsxs("div",{className:"space-y-3",children:[h.jsx("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40",children:n("engine.configured_sources",{count:e.length})}),h.jsx("div",{className:"space-y-2",children:h.jsx(Pt,{children:e.map((C,S)=>h.jsxs(Fe.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},exit:{opacity:0,x:20},className:`glass p-4 rounded-xl border border-border/10 flex items-center justify-between ${!C.enabled&&"opacity-50"}`,children:[h.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[h.jsx("div",{className:Kr[C.browser].color,children:Kr[C.browser].icon}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsx("p",{className:"text-sm font-bold",children:C.label}),h.jsx("p",{className:"text-[10px] font-mono text-fg/40 truncate",children:C.path})]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:()=>k(S),className:`px-3 py-1.5 text-xs font-bold uppercase tracking-widest rounded-lg transition-all ${C.enabled?"bg-success/10 text-success":"bg-fg/5 text-fg/40"}`,children:C.enabled?n("engine.enabled"):n("engine.disabled")}),h.jsx("button",{onClick:()=>j(S),className:"p-2 hover:bg-error/10 text-error rounded-lg transition-all",children:h.jsx(Cn,{size:16})})]})]},`${C.browser}-${C.path}`))})})]})]})}const Uw=R.createContext(void 0);function mL({children:e}){const[t,n]=R.useState([]),r=R.useCallback((s,o="info")=>{const a=Math.random().toString(36).substr(2,9),c={id:a,type:o,message:s};n(u=>[...u,c]),setTimeout(()=>{n(u=>u.filter(f=>f.id!==a))},3e3)},[]);return h.jsxs(Uw.Provider,{value:{showToast:r},children:[e,h.jsx(gL,{toasts:t})]})}function Kc(){const e=R.useContext(Uw);if(!e)throw new Error("useToast must be used within ToastProvider");return e}function gL({toasts:e}){return h.jsx("div",{className:"fixed bottom-6 right-6 z-[100] flex flex-col gap-2 pointer-events-none",children:h.jsx(Pt,{children:e.map(t=>h.jsx(yL,{toast:t},t.id))})})}function yL({toast:e}){const t={success:h.jsx(Ts,{size:18,className:"text-success"}),error:h.jsx(Cn,{size:18,className:"text-error"}),warning:h.jsx(br,{size:18,className:"text-accent"}),info:h.jsx(m_,{size:18,className:"text-primary"})},n={success:"border-success/20 bg-success/10",error:"border-error/20 bg-error/10",warning:"border-accent/20 bg-accent/10",info:"border-primary/20 bg-primary/10"};return h.jsxs(Fe.div,{initial:{opacity:0,y:20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,x:100,scale:.95},className:`glass px-4 py-3 rounded-xl border ${n[e.type]} flex items-center gap-3 min-w-[300px] max-w-md pointer-events-auto shadow-lg`,children:[t[e.type],h.jsx("span",{className:"text-sm font-medium flex-1",children:e.message})]})}const Bw=new Set(["login","log in","log-in","signin","sign in","sign-in","signup","sign up","sign-up","authentication","auth","password","register","registration","oauth","sso","navigation","menu","footer","header","sidebar","nav","breadcrumb","cookie","cookies","consent","privacy","terms","sitemap","ui","ux","user interface","interface","button","form","modal","popup","banner","facebook","meta","instagram","twitter","x","linkedin","tiktok","youtube","google","google drive","gmail","apple","icloud","microsoft","office","outlook","teams","pinterest","reddit","whatsapp","messenger","slack","discord","zoom","dropbox","notion","figma","github","gitlab","social media","social network","social","share","like","follow","post","error","not found","404","403","500","access denied","no content","empty","page not found","unavailable","blocked","forbidden","unauthorized","website","web page","webpage","page","site","web","app","application","download","install","home","homepage","main","index","default","about","contact","help","support","faq","blog","news","article"]);function xL(){const{t:e}=Ze(),{showToast:t}=Kc(),[n,r]=R.useState("realtimexai"),[s,o]=R.useState("gpt-4.1-mini"),[a,c]=R.useState("realtimexai"),[u,f]=R.useState("text-embedding-3-small"),[p,g]=R.useState([]),[y,v]=R.useState([]),[b,w]=R.useState([]),[k,j]=R.useState(!1),[C,S]=R.useState(!1),[P,N]=R.useState(!1),[A,$]=R.useState(!1),[G,B]=R.useState(!1),[L,Y]=R.useState(!1),[X,de]=R.useState(null),[H,K]=R.useState([]),[te,ne]=R.useState([]);R.useEffect(()=>{J().then(Z=>{le(Z)}),Yn()},[]);const J=async()=>{const Z={llmProvider:"realtimexai",llmModel:"gpt-4.1-mini",embeddingProvider:"realtimexai",embeddingModel:"text-embedding-3-small"},{data:{user:Ie}}=await oe.auth.getUser();if(!Ie)return Z;const{data:ee}=await oe.from("alchemy_settings").select("*").eq("user_id",Ie.id).maybeSingle();if(ee){const me=ee.llm_provider||Z.llmProvider,Ee=ee.llm_model||Z.llmModel,Se=ee.embedding_provider||Z.embeddingProvider,qe=ee.embedding_model||Z.embeddingModel;r(me),o(Ee),c(Se),f(qe),g(ee.custom_browser_paths||[]),v(ee.blacklist_domains||[]);const we=ee.blocked_tags||[];return we.length>0?w(we):w(Array.from(Bw)),{llmProvider:me,llmModel:Ee,embeddingProvider:Se,embeddingModel:qe}}else{const me=new Date(Date.now()-2592e6).toISOString();return await oe.from("alchemy_settings").insert({user_id:Ie.id,llm_provider:Z.llmProvider,llm_model:Z.llmModel,embedding_provider:Z.embeddingProvider,embedding_model:Z.embeddingModel,max_urls_per_sync:50,sync_mode:"incremental",sync_start_date:me}),Z}},le=async Z=>{const Ie=Z?.llmProvider||"realtimexai",ee=Z?.llmModel||"gpt-4.1-mini",me=Z?.embeddingProvider||"realtimexai",Ee=Z?.embeddingModel||"text-embedding-3-small";try{const[Se,qe]=await Promise.all([Qe.get("/api/sdk/providers/chat",{timeout:65e3}),Qe.get("/api/sdk/providers/embed",{timeout:65e3})]);if(Se.data.success&&qe.data.success){const we=Se.data.providers||[],Xe=qe.data.providers||[];if(de({chat:we,embed:Xe}),Y(!0),console.log("[AlchemistEngine] SDK providers loaded"),console.log(" Chat providers:",we.map(et=>et.provider)),console.log(" Embed providers:",Xe.map(et=>et.provider)),we.length>0){const et=we.some(tt=>tt.provider===Ie);if(et){const tt=we.find(ae=>ae.provider===Ie);!tt?.models?.some(ae=>ae.id===ee)&&tt?.models?.length>0&&o(tt.models[0].id)}else{const tt=we[0];r(tt.provider),tt.models?.length>0&&o(tt.models[0].id)}D(et?Ie:we[0].provider,we)}if(Xe.length>0){const et=Xe.some(tt=>tt.provider===me);if(et){const tt=Xe.find(ae=>ae.provider===me);!tt?.models?.some(ae=>ae.id===Ee)&&tt?.models?.length>0&&f(tt.models[0].id)}else{const tt=Xe[0];c(tt.provider),tt.models?.length>0&&f(tt.models[0].id)}T(et?me:Xe[0].provider,Xe)}}}catch{console.log("[AlchemistEngine] SDK not available"),Y(!1)}},T=(Z,Ie)=>{if(Ie&&Array.isArray(Ie)){const me=Ie.find(Ee=>Ee.provider===Z);if(me&&me.models){const Ee=me.models.map(Se=>Se.id);console.log(`[AlchemistEngine] Using SDK embedding models for ${Z}:`,Ee),K(Ee);return}}console.log(`[AlchemistEngine] Using hardcoded embedding models for ${Z}`);const ee=[];Z==="realtimexai"||Z==="openai"?ee.push("text-embedding-3-small","text-embedding-3-large","text-embedding-ada-002"):Z==="gemini"&&ee.push("embedding-001"),K(ee)},D=(Z,Ie)=>{if(Ie&&Array.isArray(Ie)){const me=Ie.find(Ee=>Ee.provider===Z);if(me&&me.models){const Ee=me.models.map(Se=>Se.id);console.log(`[AlchemistEngine] Using SDK chat models for ${Z}:`,Ee),ne(Ee);return}}console.log(`[AlchemistEngine] Using hardcoded chat models for ${Z}`);const ee=[];Z==="realtimexai"||Z==="openai"?ee.push("gpt-4o","gpt-4o-mini","gpt-4-turbo","gpt-3.5-turbo"):Z==="anthropic"?ee.push("claude-3-5-sonnet-20241022","claude-3-5-haiku-20241022","claude-3-opus-20240229"):Z==="google"?ee.push("gemini-2.0-flash-exp","gemini-1.5-pro","gemini-1.5-flash"):Z==="ollama"&&ee.push("llama3","mistral","codellama","phi"),ne(ee)},W=async()=>{j(!0);try{const{data:{user:Z}}=await oe.auth.getUser();if(!Z){t(e("engine.save_error_login"),"error"),j(!1);return}const{error:Ie}=await oe.from("alchemy_settings").upsert({user_id:Z.id,llm_provider:n,llm_model:s,embedding_provider:a,embedding_model:u,customized_at:new Date().toISOString()},{onConflict:"user_id"});Ie?(console.error("[AlchemistEngine] Save error:",Ie),t(`${e("common.error")}: ${Ie.message}`,"error")):t(e("engine.save_success_llm"),"success")}catch(Z){console.error("[AlchemistEngine] Unexpected error:",Z),t(`Unexpected error: ${Z.message}`,"error")}finally{j(!1)}},O=async()=>{S(!0);try{const{data:{user:Z}}=await oe.auth.getUser();if(!Z){t(e("engine.save_error_login"),"error"),S(!1);return}const{error:Ie}=await oe.from("alchemy_settings").upsert({user_id:Z.id,custom_browser_paths:p},{onConflict:"user_id"});Ie?(console.error("[AlchemistEngine] Save browser sources error:",Ie),t(`${e("common.error")}: ${Ie.message}`,"error")):t(e("engine.save_success_browser"),"success")}catch(Z){console.error("[AlchemistEngine] Unexpected error:",Z),t(`Unexpected error: ${Z.message}`,"error")}finally{S(!1)}},ve=async()=>{N(!0);try{const{data:{user:Z}}=await oe.auth.getUser();if(!Z){t(e("engine.save_error_login"),"error"),N(!1);return}const Ie=y.filter(me=>me.trim().length>0),{error:ee}=await oe.from("alchemy_settings").upsert({user_id:Z.id,blacklist_domains:Ie},{onConflict:"user_id"});ee?(console.error("[AlchemistEngine] Save blacklist error:",ee),t(`${e("common.error")}: ${ee.message}`,"error")):(t(e("engine.save_success_blacklist"),"success"),await J())}catch(Z){console.error("[AlchemistEngine] Unexpected error:",Z),t(`Unexpected error: ${Z.message}`,"error")}finally{N(!1)}},pe=async()=>{$(!0);try{const{data:{user:Z}}=await oe.auth.getUser();if(!Z){t(e("engine.save_error_login"),"error"),$(!1);return}const Ie=b.filter(me=>me.trim().length>0),{error:ee}=await oe.from("alchemy_settings").upsert({user_id:Z.id,blocked_tags:Ie},{onConflict:"user_id"});ee?(console.error("[AlchemistEngine] Save blocked tags error:",ee),t(`${e("common.error")}: ${ee.message}`,"error")):(t(e("engine.save_success_tags"),"success"),await J())}catch(Z){console.error("[AlchemistEngine] Unexpected error:",Z),t(`Unexpected error: ${Z.message}`,"error")}finally{$(!1)}},[ge,Te]=R.useState(""),[fe,$e]=R.useState(""),[rt,_t]=R.useState(!1),Yn=async()=>{const{data:{user:Z}}=await oe.auth.getUser();if(!Z)return;const{data:Ie}=await oe.from("user_persona").select("*").eq("user_id",Z.id).maybeSingle();Ie&&(Te(Ie.interest_summary||""),$e(Ie.anti_patterns||""))},Qn=async()=>{_t(!0);try{const{data:{user:Z}}=await oe.auth.getUser();if(!Z){t("Please log in to save persona","error"),_t(!1);return}const{error:Ie}=await oe.from("user_persona").upsert({user_id:Z.id,interest_summary:ge,anti_patterns:fe,last_updated_at:new Date().toISOString()},{onConflict:"user_id"});Ie?(console.error("[AlchemistEngine] Save persona error:",Ie),t(`${e("common.error")}: ${Ie.message}`,"error")):t(e("engine.save_success_persona"),"success")}catch(Z){console.error("[AlchemistEngine] Unexpected error:",Z),t(`Unexpected error: ${Z.message}`,"error")}finally{_t(!1)}},Zn=async()=>{B(!0);try{const{data:Z}=await Qe.post("/api/llm/test",{baseUrl,modelName,apiKey});Z.success?t(e("engine.test_success",{model:Z.model||""}),"success"):t(`${e("engine.test_fail",{message:Z.message})}`,"error")}catch(Z){console.error("[AlchemistEngine] Test error:",Z),t(`Test failed: ${Z.message}`,"error")}finally{B(!1)}};return h.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[h.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[h.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:e("engine.title")}),h.jsx("p",{className:"text-sm text-fg/50 font-medium",children:e("engine.subtitle")})]}),h.jsx("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:h.jsxs("div",{className:"max-w-7xl mx-auto animate-in fade-in slide-in-from-bottom-2 duration-500",children:[h.jsxs("section",{className:"space-y-6 mb-8",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(p_,{size:14})," ",e("engine.configuration")]}),h.jsxs("div",{className:"flex gap-3",children:[h.jsxs("button",{onClick:Zn,disabled:G||k,className:"px-6 py-3 bg-surface hover:bg-surface/80 border border-border text-fg font-bold rounded-xl shadow-sm hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[G?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(nn,{size:18,className:"text-accent"}),e("engine.test_connection")]}),h.jsxs("button",{onClick:W,disabled:k,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[k?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_config")]})]})]}),h.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[h.jsxs("div",{className:"glass p-6 space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:e("engine.llm_provider")}),L?h.jsxs("span",{className:"text-xs text-green-500 flex items-center gap-1",children:[h.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),e("engine.sdk_connected")]}):h.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[h.jsx("span",{className:"w-2 h-2 bg-orange-500 rounded-full"}),e("engine.sdk_not_available")]})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-xs font-medium text-fg/60",children:e("engine.provider")}),h.jsx("select",{value:n,onChange:Z=>{r(Z.target.value),D(Z.target.value,X?.chat)},className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:X?.chat&&X.chat.length>0?X.chat.map(Z=>h.jsx("option",{value:Z.provider,children:Z.provider==="realtimexai"?"RealTimeX.AI":Z.provider.charAt(0).toUpperCase()+Z.provider.slice(1)},Z.provider)):h.jsx("option",{value:"",disabled:!0,children:e("engine.loading_providers")})})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-xs font-medium text-fg/60",children:e("engine.intelligence_model")}),h.jsx("select",{value:s,onChange:Z=>o(Z.target.value),className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:te.length>0?te.map(Z=>h.jsx("option",{value:Z,children:Z},Z)):h.jsxs(h.Fragment,{children:[h.jsx("option",{value:"gpt-4o",children:"gpt-4o"}),h.jsx("option",{value:"gpt-4o-mini",children:"gpt-4o-mini"}),h.jsx("option",{value:"gpt-4-turbo",children:"gpt-4-turbo"})]})})]}),h.jsx("div",{className:"p-3 bg-primary/5 rounded-xl",children:h.jsx("p",{className:"text-[10px] text-primary/60 font-medium leading-relaxed",children:e(L?"engine.sdk_info_success":"engine.sdk_info_fail")})})]}),h.jsxs("div",{className:"glass p-6 space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:e("engine.embedding_provider")}),L?h.jsxs("span",{className:"text-xs text-green-500 flex items-center gap-1",children:[h.jsx("span",{className:"w-2 h-2 bg-green-500 rounded-full"}),e("engine.sdk_connected")]}):h.jsxs("span",{className:"text-xs text-orange-500 flex items-center gap-1",children:[h.jsx("span",{className:"w-2 h-2 bg-orange-500 rounded-full"}),e("engine.sdk_not_available")]})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-xs font-medium text-fg/60",children:e("engine.provider")}),h.jsx("select",{value:a,onChange:Z=>{c(Z.target.value),T(Z.target.value,X?.embed)},className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:X?.embed&&X.embed.length>0?X.embed.map(Z=>h.jsx("option",{value:Z.provider,children:Z.provider==="realtimexai"?"RealTimeX.AI":Z.provider.charAt(0).toUpperCase()+Z.provider.slice(1)},Z.provider)):h.jsx("option",{value:"",disabled:!0,children:e("engine.loading_providers")})})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-xs font-medium text-fg/60",children:e("engine.embedding_model")}),h.jsx("select",{value:u,onChange:Z=>f(Z.target.value),className:"w-full px-4 py-3 bg-surface border border-border rounded-xl text-fg focus:outline-none focus:ring-2 focus:ring-primary/50",children:H.length>0?H.map(Z=>h.jsx("option",{value:Z,children:Z},Z)):h.jsxs(h.Fragment,{children:[h.jsx("option",{value:"text-embedding-3-small",children:"text-embedding-3-small"}),h.jsx("option",{value:"text-embedding-3-large",children:"text-embedding-3-large"}),h.jsx("option",{value:"text-embedding-ada-002",children:"text-embedding-ada-002"})]})})]}),h.jsx("div",{className:"p-3 bg-primary/5 rounded-xl",children:h.jsx("p",{className:"text-[10px] text-primary/60 font-medium leading-relaxed",children:e(L?"engine.embedding_info_success":"engine.embedding_info_fail")})})]})]})]}),h.jsxs("section",{className:"space-y-6 mb-8",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx("span",{className:"text-xl",children:"🧠"})," ",e("engine.persona_title")]}),h.jsxs("button",{onClick:Qn,disabled:rt,className:"px-6 py-3 bg-surface hover:bg-surface/80 border border-border text-fg font-bold rounded-xl shadow-sm hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[rt?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_memory")]})]}),h.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[h.jsxs("div",{className:"glass p-6 space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:e("engine.interests_title")}),h.jsx("span",{className:"text-xs text-green-500 bg-green-500/10 px-2 py-1 rounded-full border border-green-500/20",children:e("engine.interests_priority")})]}),h.jsx("p",{className:"text-xs text-fg/50 leading-relaxed",children:e("engine.interests_desc")}),h.jsx("textarea",{value:ge,onChange:Z=>Te(Z.target.value),placeholder:e("engine.interests_placeholder"),className:"w-full h-32 px-4 py-3 bg-surface border border-border rounded-xl text-sm text-fg placeholder:text-fg/40 focus:outline-none focus:ring-2 focus:ring-green-500/30 resize-none"})]}),h.jsxs("div",{className:"glass p-6 space-y-4",children:[h.jsxs("div",{className:"flex items-center justify-between mb-2",children:[h.jsx("h3",{className:"text-sm font-semibold text-fg/80",children:e("engine.antipatterns_title")}),h.jsx("span",{className:"text-xs text-red-400 bg-red-500/10 px-2 py-1 rounded-full border border-red-500/20",children:e("engine.antipatterns_priority")})]}),h.jsx("p",{className:"text-xs text-fg/50 leading-relaxed",children:e("engine.antipatterns_desc")}),h.jsx("textarea",{value:fe,onChange:Z=>$e(Z.target.value),placeholder:e("engine.antipatterns_placeholder"),className:"w-full h-32 px-4 py-3 bg-surface border border-border rounded-xl text-sm text-fg placeholder:text-fg/40 focus:outline-none focus:ring-2 focus:ring-red-500/30 resize-none"})]})]})]}),h.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[h.jsx("section",{className:"space-y-6",children:h.jsxs("div",{className:"space-y-4",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(ta,{size:14})," ",e("engine.browser_sources")]}),h.jsxs("div",{className:"glass p-8 space-y-6",children:[h.jsx(pL,{sources:p,onChange:g}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:O,disabled:C,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[C?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_browser")]})})]})]})}),h.jsx("section",{className:"space-y-6",children:h.jsxs("div",{className:"space-y-4",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(nn,{size:14})," ",e("engine.blacklist_title")]}),h.jsxs("div",{className:"glass p-8 space-y-6",children:[h.jsx("div",{className:"space-y-2",children:h.jsx("p",{className:"text-sm text-fg/60",children:e("engine.blacklist_desc")})}),h.jsxs("div",{className:"space-y-2",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e("engine.blacklist_label")}),h.jsx("textarea",{value:y.join(`
71
71
  `),onChange:Z=>v(Z.target.value.split(`
72
- `).map(Ie=>Ie.trim())),placeholder:e("engine.blacklist_placeholder"),className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),h.jsx("p",{className:"text-xs text-fg/50 ml-1",children:e("engine.blacklist_examples")})]}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:ve,disabled:P,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[P?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_blacklist")]})})]})]})})]}),h.jsx("section",{className:"space-y-6 mt-8",children:h.jsxs("div",{className:"space-y-4",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(Df,{size:14})," ",e("engine.blocked_tags_title")]}),h.jsxs("div",{className:"glass p-8 space-y-6",children:[h.jsx("div",{className:"space-y-2",children:h.jsx("p",{className:"text-sm text-fg/60",children:e("engine.blocked_tags_desc")})}),h.jsxs("div",{className:"space-y-2",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e("engine.blocked_tags_label")}),h.jsx("textarea",{value:b.join("; "),onChange:Z=>w(Z.target.value.split(";").map(Ie=>Ie.trim())),placeholder:e("engine.blocked_tags_placeholder"),className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),h.jsx("p",{className:"text-xs text-fg/50 ml-1",children:e("engine.blocked_tags_info")})]}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:pe,disabled:A,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[A?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_blocked_tags")]})})]})]})})]})})]})}const Vw=R.createContext(null);function vL({children:e}){const[t,n]=R.useState(!1),r=()=>n(!0),s=()=>n(!1);return h.jsx(Vw.Provider,{value:{isExpanded:t,setIsExpanded:n,openTerminal:r,closeTerminal:s},children:e})}function _L(){const e=R.useContext(Vw);if(!e)throw new Error("useTerminal must be used within a TerminalProvider");return e}function bL({isExpanded:e,onToggle:t,onNavigate:n,liftUp:r}={}){const{t:s}=Ze(),[o,a]=R.useState([]),{isExpanded:c,setIsExpanded:u}=_L(),[f,p]=R.useState({}),g=e!==void 0?e:c,y=t||(()=>u(!c)),v=r?"bottom-32":"bottom-6";R.useEffect(()=>{b();const S=oe.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},P=>{const N=P.new;N.event_type==="error"&&p(A=>({...A,[N.id]:!0})),a(A=>{const $=[N,...A];return $.length>50?$.slice(0,50):$})}).subscribe();return()=>{oe.removeChannel(S)}},[]);const b=async()=>{const{data:S}=await oe.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(30);S&&a(S)},w=S=>{p(P=>({...P,[S]:!P[S]}))},k=S=>{switch(S.toLowerCase()){case"reading":return s("terminal.state_reading");case"thinking":return s("terminal.state_thinking");case"signal":return s("terminal.state_signal");case"skipped":return s("terminal.state_skipped");case"error":return s("terminal.state_error");case"completed":return s("terminal.state_completed");default:return S}},j=S=>{const P=S.message||"";if(P.startsWith("Reading content from:")){const N=P.split("Reading content from: ")[1]||"";return s("terminal.msg_reading",{url:N})}if(P.startsWith("Analyzing relevance of:")){const N=P.split("Analyzing relevance of: ")[1]||"";return s("terminal.msg_thinking",{title:N})}if(P.startsWith("Found signal:")){const N=S.metadata?.summary||S.details?.summary||"",A=S.metadata?.score||S.details?.score||0;return s("terminal.msg_found_signal",{summary:N,score:A})}if(P.startsWith("Low signal stored for review")){const N=P.match(/\((\d+)%\)/),A=N?N[1]:"0",$=P.split("): ")[1]||"";return s("terminal.msg_low_signal",{score:A,title:$})}if(P.startsWith("Analysis failed for")){const N=P.split("Analysis failed for ")[1]||"",A=N.split(": ")[0]||"",$=N.split(": ")[1]||"";return s("terminal.msg_failed",{title:A,error:$})}return P.startsWith("Sync completed:")?s("terminal.msg_sync_completed",{signals:S.metadata?.signals_found||S.details?.signals_found||0,skipped:S.metadata?.skipped||S.details?.skipped||0,errors:S.metadata?.errors||S.details?.errors||0}):P},C=(S,P,N,A)=>{if(P==="debug")return h.jsx(dj,{size:14,className:"text-fg/40"});if(N?.is_completion||A?.is_completion)return h.jsx(Cs,{size:14,className:"text-success"});switch(S){case"analysis":return h.jsx(d_,{size:14,className:"text-primary"});case"action":return h.jsx(nn,{size:14,className:"text-accent"});case"error":return h.jsx(Vy,{size:14,className:"text-error"});case"system":return h.jsx(Tc,{size:14,className:"text-success"});default:return h.jsx(m_,{size:14,className:"text-fg/40"})}};return g?h.jsxs(Fe.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},className:"fixed bottom-6 right-6 z-50 w-[450px] max-h-[600px] glass shadow-2xl flex flex-col overflow-hidden border-primary/10",children:[h.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/50",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx(oc,{size:18,className:"text-primary"}),h.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",children:s("terminal.title")}),h.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold bg-success/10 text-success px-2 py-0.5 rounded-full border border-success/10 animate-pulse ml-2",children:[h.jsx(oj,{size:10})," ",s("terminal.live")]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:()=>a([]),className:"text-[10px] uppercase font-bold text-fg/40 hover:text-fg px-2 py-1 transition-colors",children:s("terminal.clear")}),h.jsx("button",{onClick:y,className:"text-fg/40 hover:text-fg p-1 transition-colors",children:h.jsx(Aj,{size:18})})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar bg-black/20",children:[o.length===0&&h.jsx("div",{className:"text-center py-12 text-fg/20 italic text-xs",children:s("terminal.idle")}),o.map(S=>h.jsxs("div",{className:"relative flex items-start gap-3 group",children:[h.jsx("div",{className:`mt-1 flex-shrink-0 w-6 h-6 rounded-full bg-surface border flex items-center justify-center ${S.metadata?.is_completion||S.details?.is_completion?"border-success/50 bg-success/5":"border-white/5"}`,children:C(S.event_type,S.level,S.metadata,S.details)}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-mono text-fg/60 shrink-0",children:new Date(S.created_at||Date.now()).toLocaleTimeString()}),h.jsx("span",{className:`text-xs font-bold uppercase tracking-wider ${S.level==="error"?"text-error":S.level==="warn"?"text-orange-400":S.event_type==="analysis"?"text-primary":"text-fg/90"}`,children:k(S.agent_state)}),S.metadata?.actionable&&n&&h.jsxs("button",{onClick:()=>n("logs",S.metadata?.actionable),className:"ml-auto flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold tracking-wider hover:bg-primary/20 transition-all font-mono",children:[S.metadata.actionable.label,h.jsx(Ps,{size:10,className:"-rotate-90"})]}),S.duration_ms&&!S.metadata?.actionable&&h.jsxs("span",{className:"ml-auto text-[10px] font-mono bg-bg/50 px-1.5 py-0.5 rounded flex items-center gap-1 text-fg/40",children:[h.jsx(Pi,{size:10}),S.duration_ms,"ms"]})]}),S.metadata?.is_completion||S.details?.is_completion?h.jsxs("div",{className:"bg-success/5 border border-success/20 rounded-lg p-3 space-y-2 mt-2",children:[h.jsxs("div",{className:"flex items-center gap-2 text-success font-bold uppercase text-[9px] tracking-[0.2em]",children:[h.jsx(Cs,{className:"w-3.5 h-3.5"}),s("terminal.run_completed")]}),h.jsxs("div",{className:"grid grid-cols-3 gap-4 pt-1",children:[h.jsxs("div",{className:"space-y-0.5",children:[h.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:s("terminal.signals")}),h.jsx("p",{className:"text-sm font-bold text-primary",children:S.metadata?.signals_found||S.details?.signals_found||0})]}),h.jsxs("div",{className:"space-y-0.5",children:[h.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:s("terminal.urls")}),h.jsx("p",{className:"text-sm font-bold",children:S.metadata?.total_urls||S.details?.total_urls||0})]}),h.jsxs("div",{className:"space-y-0.5",children:[h.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:s("terminal.skipped")}),h.jsx("p",{className:"text-sm font-bold text-fg/60",children:S.metadata?.skipped||S.details?.skipped||0})]})]}),(S.metadata?.errors||S.details?.errors)>0&&h.jsxs("div",{className:"pt-1 border-t border-success/10 flex items-center justify-between mt-1",children:[h.jsxs("p",{className:"text-[10px] text-error font-bold flex items-center gap-1.5",children:[h.jsx(Vy,{size:12}),s("terminal.failed_to_process",{count:S.metadata?.errors||S.details?.errors})]}),n&&h.jsxs("button",{onClick:()=>n("logs",{filter:"errors"}),className:"flex items-center gap-1 text-[9px] uppercase font-bold text-error bg-error/10 border border-error/20 px-2 py-1 rounded hover:bg-error/20 transition-all group/btn",children:[s("terminal.view_logs"),h.jsx(Xl,{size:10,className:"group-hover/btn:translate-x-0.5 transition-transform"})]})]})]}):h.jsx("p",{className:`text-sm break-words leading-relaxed ${S.level==="debug"?"text-fg/50 font-mono text-xs":""}`,children:j(S)}),(S.details||S.metadata)&&h.jsxs("div",{className:"mt-2 text-xs",children:[h.jsxs("button",{onClick:()=>w(S.id),className:"flex items-center gap-1 text-fg/40 hover:text-primary transition-colors",children:[f[S.id]?h.jsx(h_,{size:12}):h.jsx(Ps,{size:12}),f[S.id]?s("terminal.hide_details"):s("terminal.view_details")]}),h.jsx(Pt,{children:f[S.id]&&h.jsx(Fe.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:h.jsx("pre",{className:"mt-2 p-3 bg-bg/50 rounded border border-white/5 font-mono text-[10px] overflow-x-auto text-fg/70",children:JSON.stringify({...S.details,...S.metadata},null,2)})})})]})]})]},S.id))]})]}):h.jsxs("button",{onClick:y,className:`fixed ${v} right-6 z-50 glass p-4 flex items-center gap-3 hover:bg-surface transition-all shadow-xl group border-primary/10`,children:[h.jsxs("div",{className:"relative",children:[h.jsx(oc,{size:20,className:"text-primary"}),o.length>0&&h.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2 w-2",children:[h.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),h.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]}),h.jsx("span",{className:"text-xs font-bold uppercase tracking-widest hidden group-hover:block animate-in fade-in slide-in-from-right-2",children:s("terminal.engine_log")})]})}const qw="1.0.0",wL="20260127000004";async function kL(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?{version:null,latestMigrationTimestamp:"0"}:{version:null,latestMigrationTimestamp:null}:{version:qw,latestMigrationTimestamp:t||null}}catch{return{version:null,latestMigrationTimestamp:null}}}async function SL(e){const t=qw,n=wL,r=await kL(e);if(r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const s=n,o=r.latestMigrationTimestamp;return s>o?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:o,message:`New migrations available. Database is at ${o}, app has ${s}.`}:{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:o,message:"Database schema is up-to-date."}}return{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:"Database schema unknown. Migration required."}}function jL(){const{t:e}=Ze(),[t,n]=R.useState("profile"),[r,s]=R.useState(!1);return h.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[h.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[h.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:e("account.title")}),h.jsx("p",{className:"text-sm text-fg/50 font-medium",children:e("account.desc")})]}),h.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[h.jsxs("aside",{className:"w-64 border-r border-border p-4 space-y-1",children:[h.jsx(_h,{active:t==="profile",onClick:()=>n("profile"),icon:h.jsx(Nc,{size:18}),label:e("account.profile")}),h.jsx(_h,{active:t==="security",onClick:()=>n("security"),icon:h.jsx(g_,{size:18}),label:e("account.security")}),h.jsx(_h,{active:t==="supabase",onClick:()=>n("supabase"),icon:h.jsx(ta,{size:18}),label:e("account.supabase")})]}),h.jsxs("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:[t==="profile"&&h.jsx(EL,{}),t==="security"&&h.jsx(CL,{}),t==="supabase"&&h.jsx(TL,{})]})]})]})}function EL(){const[e,t]=R.useState(""),[n,r]=R.useState(""),[s,o]=R.useState(""),[a,c]=R.useState(!1),[u,f]=R.useState(!1),[p,g]=R.useState(null),[y,v]=R.useState(!0),{t:b}=Ze();R.useEffect(()=>{w()},[]);const w=async()=>{const{data:{user:C}}=await oe.auth.getUser();if(!C)return;o(C.email||"");const{data:S}=await oe.from("profiles").select("*").eq("id",C.id).maybeSingle();S&&(t(S.first_name||""),r(S.last_name||""),g(S.avatar_url));const{data:P}=await oe.from("alchemy_settings").select("sound_enabled").eq("user_id",C.id).maybeSingle();P&&v(P.sound_enabled??!0)},k=async()=>{c(!0);const{data:{user:C}}=await oe.auth.getUser();C&&(await oe.from("profiles").upsert({id:C.id,first_name:e,last_name:n,full_name:e&&n?`${e} ${n}`:e||n||null}),await oe.from("alchemy_settings").update({sound_enabled:y}).eq("user_id",C.id),c(!1))},j=async C=>{const S=C.target.files?.[0];if(S){f(!0);try{const{data:{user:P}}=await oe.auth.getUser();if(!P)return;const N=S.name.split(".").pop(),A=`${P.id}/avatar-${Date.now()}.${N}`,{error:$}=await oe.storage.from("avatars").upload(A,S,{upsert:!0});if($)throw $;const{data:{publicUrl:G}}=oe.storage.from("avatars").getPublicUrl(A);await oe.from("profiles").update({avatar_url:G}).eq("id",P.id),g(G)}catch(P){console.error("Avatar upload failed:",P)}finally{f(!1)}}};return h.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[h.jsxs("section",{className:"flex items-start gap-8",children:[h.jsxs("div",{className:"relative group",children:[h.jsx("div",{className:"w-32 h-32 rounded-3xl bg-surface border border-border flex items-center justify-center overflow-hidden shadow-xl",children:p?h.jsx("img",{src:p,alt:"Avatar",className:"w-full h-full object-cover"}):h.jsx(Nc,{size:48,className:"text-fg/20"})}),h.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer rounded-3xl",children:[h.jsx(fj,{size:24,className:"text-white"}),h.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:j,disabled:u})]}),u&&h.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-3xl",children:h.jsx(Rt,{size:24,className:"text-primary animate-spin"})})]}),h.jsxs("div",{className:"flex-1 space-y-4",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsx(bc,{label:b("account.first_name"),value:e,onChange:t,placeholder:"Zosimos"}),h.jsx(bc,{label:b("account.last_name"),value:n,onChange:r,placeholder:"of Panopolis"})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:b("account.email_locked")}),h.jsx("input",{type:"email",value:s,readOnly:!0,className:"w-full bg-black/5 border border-border rounded-xl py-3 px-4 text-sm text-fg/40 cursor-not-allowed"})]})]})]}),h.jsxs("section",{className:"glass p-6 space-y-4",children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[y?h.jsx(Jy,{size:20,className:"text-primary"}):h.jsx(Xy,{size:20,className:"text-fg/40"}),b("account.sound_effects")]}),h.jsx("p",{className:"text-xs text-fg/40",children:b("account.sound_desc")}),h.jsx("button",{onClick:()=>v(!y),className:`w-full p-4 rounded-xl border-2 transition-all ${y?"bg-primary/10 border-primary/30 text-primary":"bg-surface border-border text-fg/40"}`,children:h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{className:"font-semibold text-sm",children:b(y?"common.enabled":"common.disabled")}),y?h.jsx(Jy,{size:18}):h.jsx(Xy,{size:18})]})})]}),h.jsxs("section",{className:"glass p-6 space-y-4",children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[h.jsx(Ky,{size:20,className:"text-error"}),b("account.sign_out")]}),h.jsx("p",{className:"text-xs text-fg/40",children:b("account.logout_desc")}),h.jsx("button",{onClick:()=>oe.auth.signOut(),className:"w-full p-4 rounded-xl border-2 bg-error/10 border-error/30 text-error hover:bg-error hover:text-white transition-all",children:h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{className:"font-semibold text-sm",children:b("account.sign_out")}),h.jsx(Ky,{size:18})]})})]}),h.jsx("div",{className:"flex justify-end pt-4 border-t border-border",children:h.jsxs("button",{onClick:k,disabled:a,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[a?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),b("account.preserve_profile")]})})]})}function CL(){const[e,t]=R.useState(""),[n,r]=R.useState(""),[s,o]=R.useState(!1),[a,c]=R.useState(null),[u,f]=R.useState(!1),{t:p}=Ze(),g=async()=>{if(!e||e!==n){c(p("account.password_mismatch"));return}if(e.length<8){c(p("account.password_too_short"));return}o(!0),c(null),f(!1);const{error:y}=await oe.auth.updateUser({password:e});y?c(y.message):(f(!0),t(""),r("")),o(!1)};return h.jsx("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:h.jsxs("div",{className:"glass p-6 space-y-6",children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[h.jsx(kj,{size:20,className:"text-error"})," ",p("account.security_title")]}),h.jsxs("div",{className:"space-y-4",children:[h.jsx(bc,{label:p("account.new_password"),type:"password",value:e,onChange:t,placeholder:"••••••••"}),h.jsx(bc,{label:p("account.confirm_password"),type:"password",value:n,onChange:r,placeholder:"••••••••"})]}),a&&h.jsx("p",{className:"text-xs text-error font-mono bg-error/5 p-3 rounded-lg border border-error/10",children:a}),u&&h.jsx("p",{className:"text-xs text-success font-mono bg-success/5 p-3 rounded-lg border border-success/10",children:p("account.password_rotate_success")}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:g,disabled:s,className:"px-6 py-3 bg-error/10 text-error hover:bg-error hover:text-white font-bold rounded-xl border border-error/20 transition-all flex items-center gap-2",children:[s?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(g_,{size:18}),p("account.rotate_key")]})})]})})}function TL(){const[e,t]=R.useState(!1),[n,r]=R.useState(null),s=Rs(),o=aL(),{t:a}=Ze();R.useEffect(()=>{s&&SL(oe).then(r)},[]);const c=()=>{confirm(a("account.sever_confirm"))&&(iL(),window.location.reload())};return h.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[h.jsxs("section",{className:"space-y-6",children:[h.jsx("div",{className:"flex items-center justify-between",children:h.jsxs("div",{children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[h.jsx(ta,{size:20,className:"text-primary"})," ",a("account.essence_resonance")]}),h.jsx("p",{className:"text-xs text-fg/40 font-medium",children:a("account.byok_desc")})]})}),h.jsx("div",{className:"glass p-8 space-y-8",children:s?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-start gap-4 p-4 glass bg-emerald-500/5 border border-emerald-500/20 rounded-2xl",children:[h.jsx(Cs,{className:"w-6 h-6 text-emerald-500 mt-1"}),h.jsxs("div",{className:"flex-1 space-y-1",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("p",{className:"font-bold text-fg italic uppercase tracking-tighter",children:a("account.established_link")}),n?.latestMigrationTimestamp&&h.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-full border border-emerald-500/20",children:["v",n.latestMigrationTimestamp]})]}),h.jsx("p",{className:"text-xs font-mono text-fg/40 break-all",children:s.url})]})]}),o==="env"&&h.jsxs("div",{className:"flex items-center gap-3 p-3 bg-amber-500/5 border border-amber-500/10 rounded-xl",children:[h.jsx(br,{size:16,className:"text-amber-500"}),h.jsx("p",{className:"text-[10px] text-amber-500 font-bold uppercase tracking-widest leading-none",children:a("account.env_notice")})]}),h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("button",{onClick:()=>t(!0),className:"px-4 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[h.jsx(Tc,{size:14})," ",a("account.realign_link")]}),o==="ui"&&h.jsxs("button",{onClick:c,className:"px-4 py-3 glass border-error/10 hover:bg-error/10 text-error/60 hover:text-error text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[h.jsx(zf,{size:14})," ",a("account.sever_link")]})]}),h.jsxs("div",{className:"space-y-1 pt-4 border-t border-border/10",children:[h.jsx("label",{className:"text-[9px] font-bold uppercase tracking-widest text-fg/20 ml-1",children:a("account.anon_secret_fragment")}),h.jsxs("div",{className:"p-3 bg-surface/50 rounded-xl font-mono text-[11px] text-fg/30 break-all border border-border",children:[s.anonKey.substring(0,32),"..."]})]})]}):h.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-6",children:[h.jsx(ta,{size:48,className:"text-fg/10"}),h.jsxs("div",{className:"space-y-2",children:[h.jsx("p",{className:"font-bold italic uppercase tracking-tighter",children:a("account.no_resonance")}),h.jsx("p",{className:"text-xs text-fg/40 max-w-[240px]",children:a("account.no_resonance_desc")})]}),h.jsx("button",{onClick:()=>t(!0),className:"px-8 py-3 bg-primary text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] transition-all uppercase tracking-widest text-xs",children:a("account.initiate_link")})]})})]}),h.jsx($w,{open:e,onComplete:()=>t(!1),canClose:!0})]})}function _h({active:e,icon:t,label:n,onClick:r}){return h.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${e?"glass bg-primary/10 text-primary border-primary/20 shadow-sm":"text-fg/40 hover:bg-surface hover:text-fg"}`,children:[e?ea.cloneElement(t,{className:"text-primary"}):t,h.jsx("span",{className:"font-semibold text-sm",children:n})]})}function bc({label:e,value:t,onChange:n,placeholder:r,type:s="text"}){return h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e}),h.jsx("input",{type:s,value:t,onChange:o=>n(o.target.value),className:"w-full bg-surface border border-border rounded-xl py-3 px-4 text-sm text-fg placeholder:text-fg/40 focus:border-[var(--border-hover)] outline-none transition-all",placeholder:r})]})}function NL({signal:e,onClose:t}){const{t:n}=Ze(),[r,s]=ea.useState(!1);if(!e)return null;const o=()=>{const u=`# ${e.title}
72
+ `).map(Ie=>Ie.trim())),placeholder:e("engine.blacklist_placeholder"),className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),h.jsx("p",{className:"text-xs text-fg/50 ml-1",children:e("engine.blacklist_examples")})]}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:ve,disabled:P,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[P?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_blacklist")]})})]})]})})]}),h.jsx("section",{className:"space-y-6 mt-8",children:h.jsxs("div",{className:"space-y-4",children:[h.jsxs("label",{className:"text-xs font-bold uppercase tracking-widest text-fg/40 flex items-center gap-2",children:[h.jsx(Df,{size:14})," ",e("engine.blocked_tags_title")]}),h.jsxs("div",{className:"glass p-8 space-y-6",children:[h.jsx("div",{className:"space-y-2",children:h.jsx("p",{className:"text-sm text-fg/60",children:e("engine.blocked_tags_desc")})}),h.jsxs("div",{className:"space-y-2",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e("engine.blocked_tags_label")}),h.jsx("textarea",{value:b.join("; "),onChange:Z=>w(Z.target.value.split(";").map(Ie=>Ie.trim())),placeholder:e("engine.blocked_tags_placeholder"),className:"w-full h-40 px-4 py-3 rounded-xl border border-border bg-surface text-fg text-sm placeholder:text-fg/40 focus:outline-none focus:border-[var(--border-hover)] transition-all resize-none"}),h.jsx("p",{className:"text-xs text-fg/50 ml-1",children:e("engine.blocked_tags_info")})]}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:pe,disabled:A,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[A?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),e("engine.save_blocked_tags")]})})]})]})})]})})]})}const Vw=R.createContext(null);function vL({children:e}){const[t,n]=R.useState(!1),r=()=>n(!0),s=()=>n(!1);return h.jsx(Vw.Provider,{value:{isExpanded:t,setIsExpanded:n,openTerminal:r,closeTerminal:s},children:e})}function _L(){const e=R.useContext(Vw);if(!e)throw new Error("useTerminal must be used within a TerminalProvider");return e}function bL({isExpanded:e,onToggle:t,onNavigate:n,liftUp:r}={}){const{t:s}=Ze(),[o,a]=R.useState([]),{isExpanded:c,setIsExpanded:u}=_L(),[f,p]=R.useState({}),g=e!==void 0?e:c,y=t||(()=>u(!c)),v=r?"bottom-32":"bottom-6";R.useEffect(()=>{b();const S=oe.channel("processing_events_feed").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events"},P=>{const N=P.new;N.event_type==="error"&&p(A=>({...A,[N.id]:!0})),a(A=>{const $=[N,...A];return $.length>50?$.slice(0,50):$})}).subscribe();return()=>{oe.removeChannel(S)}},[]);const b=async()=>{const{data:S}=await oe.from("processing_events").select("*").order("created_at",{ascending:!1}).limit(30);S&&a(S)},w=S=>{p(P=>({...P,[S]:!P[S]}))},k=S=>{switch(S.toLowerCase()){case"reading":return s("terminal.state_reading");case"thinking":return s("terminal.state_thinking");case"signal":return s("terminal.state_signal");case"skipped":return s("terminal.state_skipped");case"error":return s("terminal.state_error");case"completed":return s("terminal.state_completed");default:return S}},j=S=>{const P=S.message||"";if(P.startsWith("Reading content from:")){const N=P.split("Reading content from: ")[1]||"";return s("terminal.msg_reading",{url:N})}if(P.startsWith("Analyzing relevance of:")){const N=P.split("Analyzing relevance of: ")[1]||"";return s("terminal.msg_thinking",{title:N})}if(P.startsWith("Found signal:")){const N=S.metadata?.summary||S.details?.summary||"",A=S.metadata?.score||S.details?.score||0;return s("terminal.msg_found_signal",{summary:N,score:A})}if(P.startsWith("Low signal stored for review")){const N=P.match(/\((\d+)%\)/),A=N?N[1]:"0",$=P.split("): ")[1]||"";return s("terminal.msg_low_signal",{score:A,title:$})}if(P.startsWith("Analysis failed for")){const N=P.split("Analysis failed for ")[1]||"",A=N.split(": ")[0]||"",$=N.split(": ")[1]||"";return s("terminal.msg_failed",{title:A,error:$})}return P.startsWith("Sync completed:")?s("terminal.msg_sync_completed",{signals:S.metadata?.signals_found||S.details?.signals_found||0,skipped:S.metadata?.skipped||S.details?.skipped||0,errors:S.metadata?.errors||S.details?.errors||0}):P},C=(S,P,N,A)=>{if(P==="debug")return h.jsx(dj,{size:14,className:"text-fg/40"});if(N?.is_completion||A?.is_completion)return h.jsx(Cs,{size:14,className:"text-success"});switch(S){case"analysis":return h.jsx(d_,{size:14,className:"text-primary"});case"action":return h.jsx(nn,{size:14,className:"text-accent"});case"error":return h.jsx(Vy,{size:14,className:"text-error"});case"system":return h.jsx(Tc,{size:14,className:"text-success"});default:return h.jsx(m_,{size:14,className:"text-fg/40"})}};return g?h.jsxs(Fe.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},className:"fixed bottom-6 right-6 z-50 w-[450px] max-h-[600px] glass shadow-2xl flex flex-col overflow-hidden border-primary/10",children:[h.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/50",children:[h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx(oc,{size:18,className:"text-primary"}),h.jsx("span",{className:"text-xs font-bold uppercase tracking-widest",children:s("terminal.title")}),h.jsxs("div",{className:"flex items-center gap-1.5 text-[9px] font-bold bg-success/10 text-success px-2 py-0.5 rounded-full border border-success/10 animate-pulse ml-2",children:[h.jsx(oj,{size:10})," ",s("terminal.live")]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:()=>a([]),className:"text-[10px] uppercase font-bold text-fg/40 hover:text-fg px-2 py-1 transition-colors",children:s("terminal.clear")}),h.jsx("button",{onClick:y,className:"text-fg/40 hover:text-fg p-1 transition-colors",children:h.jsx(Aj,{size:18})})]})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 custom-scrollbar bg-black/20",children:[o.length===0&&h.jsx("div",{className:"text-center py-12 text-fg/20 italic text-xs",children:s("terminal.idle")}),o.map(S=>h.jsxs("div",{className:"relative flex items-start gap-3 group",children:[h.jsx("div",{className:`mt-1 flex-shrink-0 w-6 h-6 rounded-full bg-surface border flex items-center justify-center ${S.metadata?.is_completion||S.details?.is_completion?"border-success/50 bg-success/5":"border-white/5"}`,children:C(S.event_type,S.level,S.metadata,S.details)}),h.jsxs("div",{className:"flex-1 min-w-0",children:[h.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[h.jsx("span",{className:"text-xs font-mono text-fg/60 shrink-0",children:new Date(S.created_at||Date.now()).toLocaleTimeString()}),h.jsx("span",{className:`text-xs font-bold uppercase tracking-wider ${S.level==="error"?"text-error":S.level==="warn"?"text-orange-400":S.event_type==="analysis"?"text-primary":"text-fg/90"}`,children:k(S.agent_state)}),S.metadata?.actionable&&n&&h.jsxs("button",{onClick:()=>n("logs",S.metadata?.actionable),className:"ml-auto flex items-center gap-1 bg-primary/10 text-primary border border-primary/20 px-1.5 py-0.5 rounded text-[10px] uppercase font-bold tracking-wider hover:bg-primary/20 transition-all font-mono",children:[S.metadata.actionable.label,h.jsx(Ps,{size:10,className:"-rotate-90"})]}),S.duration_ms&&!S.metadata?.actionable&&h.jsxs("span",{className:"ml-auto text-[10px] font-mono bg-bg/50 px-1.5 py-0.5 rounded flex items-center gap-1 text-fg/40",children:[h.jsx(Pi,{size:10}),S.duration_ms,"ms"]})]}),S.metadata?.is_completion||S.details?.is_completion?h.jsxs("div",{className:"bg-success/5 border border-success/20 rounded-lg p-3 space-y-2 mt-2",children:[h.jsxs("div",{className:"flex items-center gap-2 text-success font-bold uppercase text-[9px] tracking-[0.2em]",children:[h.jsx(Cs,{className:"w-3.5 h-3.5"}),s("terminal.run_completed")]}),h.jsxs("div",{className:"grid grid-cols-3 gap-4 pt-1",children:[h.jsxs("div",{className:"space-y-0.5",children:[h.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:s("terminal.signals")}),h.jsx("p",{className:"text-sm font-bold text-primary",children:S.metadata?.signals_found||S.details?.signals_found||0})]}),h.jsxs("div",{className:"space-y-0.5",children:[h.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:s("terminal.urls")}),h.jsx("p",{className:"text-sm font-bold",children:S.metadata?.total_urls||S.details?.total_urls||0})]}),h.jsxs("div",{className:"space-y-0.5",children:[h.jsx("p",{className:"text-[10px] text-fg/40 uppercase",children:s("terminal.skipped")}),h.jsx("p",{className:"text-sm font-bold text-fg/60",children:S.metadata?.skipped||S.details?.skipped||0})]})]}),(S.metadata?.errors||S.details?.errors)>0&&h.jsxs("div",{className:"pt-1 border-t border-success/10 flex items-center justify-between mt-1",children:[h.jsxs("p",{className:"text-[10px] text-error font-bold flex items-center gap-1.5",children:[h.jsx(Vy,{size:12}),s("terminal.failed_to_process",{count:S.metadata?.errors||S.details?.errors})]}),n&&h.jsxs("button",{onClick:()=>n("logs",{filter:"errors"}),className:"flex items-center gap-1 text-[9px] uppercase font-bold text-error bg-error/10 border border-error/20 px-2 py-1 rounded hover:bg-error/20 transition-all group/btn",children:[s("terminal.view_logs"),h.jsx(Xl,{size:10,className:"group-hover/btn:translate-x-0.5 transition-transform"})]})]})]}):h.jsx("p",{className:`text-sm break-words leading-relaxed ${S.level==="debug"?"text-fg/50 font-mono text-xs":""}`,children:j(S)}),(S.details||S.metadata)&&h.jsxs("div",{className:"mt-2 text-xs",children:[h.jsxs("button",{onClick:()=>w(S.id),className:"flex items-center gap-1 text-fg/40 hover:text-primary transition-colors",children:[f[S.id]?h.jsx(h_,{size:12}):h.jsx(Ps,{size:12}),f[S.id]?s("terminal.hide_details"):s("terminal.view_details")]}),h.jsx(Pt,{children:f[S.id]&&h.jsx(Fe.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"overflow-hidden",children:h.jsx("pre",{className:"mt-2 p-3 bg-bg/50 rounded border border-white/5 font-mono text-[10px] overflow-x-auto text-fg/70",children:JSON.stringify({...S.details,...S.metadata},null,2)})})})]})]})]},S.id))]})]}):h.jsxs("button",{onClick:y,className:`fixed ${v} right-6 z-50 glass p-4 flex items-center gap-3 hover:bg-surface transition-all shadow-xl group border-primary/10`,children:[h.jsxs("div",{className:"relative",children:[h.jsx(oc,{size:20,className:"text-primary"}),o.length>0&&h.jsxs("span",{className:"absolute -top-1 -right-1 flex h-2 w-2",children:[h.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75"}),h.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-primary"})]})]}),h.jsx("span",{className:"text-xs font-bold uppercase tracking-widest hidden group-hover:block animate-in fade-in slide-in-from-right-2",children:s("terminal.engine_log")})]})}const qw="1.0.0",wL="20260128144000";async function kL(e){try{const{data:t,error:n}=await e.rpc("get_latest_migration_timestamp");return n?n.code==="42883"?{version:null,latestMigrationTimestamp:"0"}:{version:null,latestMigrationTimestamp:null}:{version:qw,latestMigrationTimestamp:t||null}}catch{return{version:null,latestMigrationTimestamp:null}}}async function SL(e){const t=qw,n=wL,r=await kL(e);if(r.latestMigrationTimestamp&&r.latestMigrationTimestamp.trim()!==""){const s=n,o=r.latestMigrationTimestamp;return s>o?{needsMigration:!0,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:o,message:`New migrations available. Database is at ${o}, app has ${s}.`}:{needsMigration:!1,appVersion:t,dbVersion:r.version,latestMigrationTimestamp:o,message:"Database schema is up-to-date."}}return{needsMigration:!0,appVersion:t,dbVersion:null,latestMigrationTimestamp:null,message:"Database schema unknown. Migration required."}}function jL(){const{t:e}=Ze(),[t,n]=R.useState("profile"),[r,s]=R.useState(!1);return h.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[h.jsxs("header",{className:"px-8 py-6 border-b border-border",children:[h.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:e("account.title")}),h.jsx("p",{className:"text-sm text-fg/50 font-medium",children:e("account.desc")})]}),h.jsxs("div",{className:"flex-1 flex overflow-hidden",children:[h.jsxs("aside",{className:"w-64 border-r border-border p-4 space-y-1",children:[h.jsx(_h,{active:t==="profile",onClick:()=>n("profile"),icon:h.jsx(Nc,{size:18}),label:e("account.profile")}),h.jsx(_h,{active:t==="security",onClick:()=>n("security"),icon:h.jsx(g_,{size:18}),label:e("account.security")}),h.jsx(_h,{active:t==="supabase",onClick:()=>n("supabase"),icon:h.jsx(ta,{size:18}),label:e("account.supabase")})]}),h.jsxs("main",{className:"flex-1 overflow-y-auto custom-scrollbar p-8",children:[t==="profile"&&h.jsx(EL,{}),t==="security"&&h.jsx(CL,{}),t==="supabase"&&h.jsx(TL,{})]})]})]})}function EL(){const[e,t]=R.useState(""),[n,r]=R.useState(""),[s,o]=R.useState(""),[a,c]=R.useState(!1),[u,f]=R.useState(!1),[p,g]=R.useState(null),[y,v]=R.useState(!0),{t:b}=Ze();R.useEffect(()=>{w()},[]);const w=async()=>{const{data:{user:C}}=await oe.auth.getUser();if(!C)return;o(C.email||"");const{data:S}=await oe.from("profiles").select("*").eq("id",C.id).maybeSingle();S?(t(S.first_name||C.user_metadata?.first_name||""),r(S.last_name||C.user_metadata?.last_name||""),g(S.avatar_url)):(t(C.user_metadata?.first_name||""),r(C.user_metadata?.last_name||""));const{data:P}=await oe.from("alchemy_settings").select("sound_enabled").eq("user_id",C.id).maybeSingle();P&&v(P.sound_enabled??!0)},k=async()=>{c(!0);const{data:{user:C}}=await oe.auth.getUser();C&&(await oe.from("profiles").upsert({id:C.id,first_name:e,last_name:n,full_name:e&&n?`${e} ${n}`:e||n||null}),await oe.from("alchemy_settings").update({sound_enabled:y}).eq("user_id",C.id),c(!1))},j=async C=>{const S=C.target.files?.[0];if(S){f(!0);try{const{data:{user:P}}=await oe.auth.getUser();if(!P)return;const N=S.name.split(".").pop(),A=`${P.id}/avatar-${Date.now()}.${N}`,{error:$}=await oe.storage.from("avatars").upload(A,S,{upsert:!0});if($)throw $;const{data:{publicUrl:G}}=oe.storage.from("avatars").getPublicUrl(A);await oe.from("profiles").update({avatar_url:G}).eq("id",P.id),g(G)}catch(P){console.error("Avatar upload failed:",P)}finally{f(!1)}}};return h.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[h.jsxs("section",{className:"flex items-start gap-8",children:[h.jsxs("div",{className:"relative group",children:[h.jsx("div",{className:"w-32 h-32 rounded-3xl bg-surface border border-border flex items-center justify-center overflow-hidden shadow-xl",children:p?h.jsx("img",{src:p,alt:"Avatar",className:"w-full h-full object-cover"}):h.jsx(Nc,{size:48,className:"text-fg/20"})}),h.jsxs("label",{className:"absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer rounded-3xl",children:[h.jsx(fj,{size:24,className:"text-white"}),h.jsx("input",{type:"file",className:"hidden",accept:"image/*",onChange:j,disabled:u})]}),u&&h.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 rounded-3xl",children:h.jsx(Rt,{size:24,className:"text-primary animate-spin"})})]}),h.jsxs("div",{className:"flex-1 space-y-4",children:[h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsx(bc,{label:b("account.first_name"),value:e,onChange:t,placeholder:"Zosimos"}),h.jsx(bc,{label:b("account.last_name"),value:n,onChange:r,placeholder:"of Panopolis"})]}),h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:b("account.email_locked")}),h.jsx("input",{type:"email",value:s,readOnly:!0,className:"w-full bg-black/5 border border-border rounded-xl py-3 px-4 text-sm text-fg/40 cursor-not-allowed"})]})]})]}),h.jsxs("section",{className:"glass p-6 space-y-4",children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[y?h.jsx(Jy,{size:20,className:"text-primary"}):h.jsx(Xy,{size:20,className:"text-fg/40"}),b("account.sound_effects")]}),h.jsx("p",{className:"text-xs text-fg/40",children:b("account.sound_desc")}),h.jsx("button",{onClick:()=>v(!y),className:`w-full p-4 rounded-xl border-2 transition-all ${y?"bg-primary/10 border-primary/30 text-primary":"bg-surface border-border text-fg/40"}`,children:h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{className:"font-semibold text-sm",children:b(y?"common.enabled":"common.disabled")}),y?h.jsx(Jy,{size:18}):h.jsx(Xy,{size:18})]})})]}),h.jsxs("section",{className:"glass p-6 space-y-4",children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[h.jsx(Ky,{size:20,className:"text-error"}),b("account.sign_out")]}),h.jsx("p",{className:"text-xs text-fg/40",children:b("account.logout_desc")}),h.jsx("button",{onClick:()=>oe.auth.signOut(),className:"w-full p-4 rounded-xl border-2 bg-error/10 border-error/30 text-error hover:bg-error hover:text-white transition-all",children:h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("span",{className:"font-semibold text-sm",children:b("account.sign_out")}),h.jsx(Ky,{size:18})]})})]}),h.jsx("div",{className:"flex justify-end pt-4 border-t border-border",children:h.jsxs("button",{onClick:k,disabled:a,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] active:scale-95 transition-all flex items-center gap-2",children:[a?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(_r,{size:18}),b("account.preserve_profile")]})})]})}function CL(){const[e,t]=R.useState(""),[n,r]=R.useState(""),[s,o]=R.useState(!1),[a,c]=R.useState(null),[u,f]=R.useState(!1),{t:p}=Ze(),g=async()=>{if(!e||e!==n){c(p("account.password_mismatch"));return}if(e.length<8){c(p("account.password_too_short"));return}o(!0),c(null),f(!1);const{error:y}=await oe.auth.updateUser({password:e});y?c(y.message):(f(!0),t(""),r("")),o(!1)};return h.jsx("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:h.jsxs("div",{className:"glass p-6 space-y-6",children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[h.jsx(kj,{size:20,className:"text-error"})," ",p("account.security_title")]}),h.jsxs("div",{className:"space-y-4",children:[h.jsx(bc,{label:p("account.new_password"),type:"password",value:e,onChange:t,placeholder:"••••••••"}),h.jsx(bc,{label:p("account.confirm_password"),type:"password",value:n,onChange:r,placeholder:"••••••••"})]}),a&&h.jsx("p",{className:"text-xs text-error font-mono bg-error/5 p-3 rounded-lg border border-error/10",children:a}),u&&h.jsx("p",{className:"text-xs text-success font-mono bg-success/5 p-3 rounded-lg border border-success/10",children:p("account.password_rotate_success")}),h.jsx("div",{className:"flex justify-end pt-2",children:h.jsxs("button",{onClick:g,disabled:s,className:"px-6 py-3 bg-error/10 text-error hover:bg-error hover:text-white font-bold rounded-xl border border-error/20 transition-all flex items-center gap-2",children:[s?h.jsx(Rt,{size:18,className:"animate-spin"}):h.jsx(g_,{size:18}),p("account.rotate_key")]})})]})})}function TL(){const[e,t]=R.useState(!1),[n,r]=R.useState(null),s=Rs(),o=aL(),{t:a}=Ze();R.useEffect(()=>{s&&SL(oe).then(r)},[]);const c=()=>{confirm(a("account.sever_confirm"))&&(iL(),window.location.reload())};return h.jsxs("div",{className:"max-w-2xl space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-500",children:[h.jsxs("section",{className:"space-y-6",children:[h.jsx("div",{className:"flex items-center justify-between",children:h.jsxs("div",{children:[h.jsxs("h3",{className:"text-lg font-bold flex items-center gap-2",children:[h.jsx(ta,{size:20,className:"text-primary"})," ",a("account.essence_resonance")]}),h.jsx("p",{className:"text-xs text-fg/40 font-medium",children:a("account.byok_desc")})]})}),h.jsx("div",{className:"glass p-8 space-y-8",children:s?h.jsxs(h.Fragment,{children:[h.jsxs("div",{className:"flex items-start gap-4 p-4 glass bg-emerald-500/5 border border-emerald-500/20 rounded-2xl",children:[h.jsx(Cs,{className:"w-6 h-6 text-emerald-500 mt-1"}),h.jsxs("div",{className:"flex-1 space-y-1",children:[h.jsxs("div",{className:"flex items-center justify-between",children:[h.jsx("p",{className:"font-bold text-fg italic uppercase tracking-tighter",children:a("account.established_link")}),n?.latestMigrationTimestamp&&h.jsxs("span",{className:"text-[10px] font-mono bg-emerald-500/10 text-emerald-500 px-2 py-0.5 rounded-full border border-emerald-500/20",children:["v",n.latestMigrationTimestamp]})]}),h.jsx("p",{className:"text-xs font-mono text-fg/40 break-all",children:s.url})]})]}),o==="env"&&h.jsxs("div",{className:"flex items-center gap-3 p-3 bg-amber-500/5 border border-amber-500/10 rounded-xl",children:[h.jsx(br,{size:16,className:"text-amber-500"}),h.jsx("p",{className:"text-[10px] text-amber-500 font-bold uppercase tracking-widest leading-none",children:a("account.env_notice")})]}),h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("button",{onClick:()=>t(!0),className:"px-4 py-3 glass hover:bg-surface text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[h.jsx(Tc,{size:14})," ",a("account.realign_link")]}),o==="ui"&&h.jsxs("button",{onClick:c,className:"px-4 py-3 glass border-error/10 hover:bg-error/10 text-error/60 hover:text-error text-xs font-bold uppercase tracking-widest transition-all flex items-center justify-center gap-2",children:[h.jsx(zf,{size:14})," ",a("account.sever_link")]})]}),h.jsxs("div",{className:"space-y-1 pt-4 border-t border-border/10",children:[h.jsx("label",{className:"text-[9px] font-bold uppercase tracking-widest text-fg/20 ml-1",children:a("account.anon_secret_fragment")}),h.jsxs("div",{className:"p-3 bg-surface/50 rounded-xl font-mono text-[11px] text-fg/30 break-all border border-border",children:[s.anonKey.substring(0,32),"..."]})]})]}):h.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center space-y-6",children:[h.jsx(ta,{size:48,className:"text-fg/10"}),h.jsxs("div",{className:"space-y-2",children:[h.jsx("p",{className:"font-bold italic uppercase tracking-tighter",children:a("account.no_resonance")}),h.jsx("p",{className:"text-xs text-fg/40 max-w-[240px]",children:a("account.no_resonance_desc")})]}),h.jsx("button",{onClick:()=>t(!0),className:"px-8 py-3 bg-primary text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-[1.02] transition-all uppercase tracking-widest text-xs",children:a("account.initiate_link")})]})})]}),h.jsx($w,{open:e,onComplete:()=>t(!1),canClose:!0})]})}function _h({active:e,icon:t,label:n,onClick:r}){return h.jsxs("button",{onClick:r,className:`w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all ${e?"glass bg-primary/10 text-primary border-primary/20 shadow-sm":"text-fg/40 hover:bg-surface hover:text-fg"}`,children:[e?ea.cloneElement(t,{className:"text-primary"}):t,h.jsx("span",{className:"font-semibold text-sm",children:n})]})}function bc({label:e,value:t,onChange:n,placeholder:r,type:s="text"}){return h.jsxs("div",{className:"space-y-1",children:[h.jsx("label",{className:"text-[10px] font-bold uppercase text-fg/30 ml-1",children:e}),h.jsx("input",{type:s,value:t,onChange:o=>n(o.target.value),className:"w-full bg-surface border border-border rounded-xl py-3 px-4 text-sm text-fg placeholder:text-fg/40 focus:border-[var(--border-hover)] outline-none transition-all",placeholder:r})]})}function NL({signal:e,onClose:t}){const{t:n}=Ze(),[r,s]=ea.useState(!1);if(!e)return null;const o=()=>{const u=`# ${e.title}
73
73
 
74
74
  **${n("discovery.category")}**: ${n(`common.categories.${e.category?.toLowerCase()||"other"}`,e.category||"Research")}
75
75
  **${n("discovery.intelligence_score")}**: ${e.score}/100
@@ -131,7 +131,7 @@ ${e.content}`:""}`,f=new Blob([u],{type:"text/markdown"}),p=URL.createObjectURL(
131
131
  `,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:y,table:a,tableCell:u,tableRow:c}};function a(v,b,w,k){return f(p(v,w,k),v.align)}function c(v,b,w,k){const j=g(v,w,k),C=f([j]);return C.slice(0,C.indexOf(`
132
132
  `))}function u(v,b,w,k){const j=w.enter("tableCell"),C=w.enter("phrasing"),S=w.containerPhrasing(v,{...k,before:o,after:o});return C(),j(),S}function f(v,b){return UM(v,{align:b,alignDelimiters:r,padding:n,stringLength:s})}function p(v,b,w){const k=v.children;let j=-1;const C=[],S=b.enter("table");for(;++j<k.length;)C[j]=g(k[j],b,w);return S(),C}function g(v,b,w){const k=v.children;let j=-1;const C=[],S=b.enter("tableRow");for(;++j<k.length;)C[j]=u(k[j],v,b,w);return S(),C}function y(v,b,w){let k=Bk.inlineCode(v,b,w);return w.stack.includes("tableCell")&&(k=k.replace(/\|/g,"\\$&")),k}}function T3(){return{exit:{taskListCheckValueChecked:n_,taskListCheckValueUnchecked:n_,paragraph:A3}}}function N3(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:R3}}}function n_(e){const t=this.stack[this.stack.length-2];t.type,t.checked=e.type==="taskListCheckValueChecked"}function A3(e){const t=this.stack[this.stack.length-2];if(t&&t.type==="listItem"&&typeof t.checked=="boolean"){const n=this.stack[this.stack.length-1];n.type;const r=n.children[0];if(r&&r.type==="text"){const s=t.children;let o=-1,a;for(;++o<s.length;){const c=s[o];if(c.type==="paragraph"){a=c;break}}a===n&&(r.value=r.value.slice(1),r.value.length===0?n.children.shift():n.position&&r.position&&typeof r.position.start.offset=="number"&&(r.position.start.column++,r.position.start.offset++,n.position.start=Object.assign({},r.position.start)))}}this.exit(e)}function R3(e,t,n,r){const s=e.children[0],o=typeof e.checked=="boolean"&&s&&s.type==="paragraph",a="["+(e.checked?"x":" ")+"] ",c=n.createTracker(r);o&&c.move(a);let u=Bk.listItem(e,t,n,{...r,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,f)),u;function f(p){return p+a}}function P3(){return[uM(),RM(),IM(),b3(),T3()]}function O3(e){return{extensions:[dM(),PM(e),DM(),C3(e),N3()]}}const L3={tokenize:$3,partial:!0},Vk={tokenize:U3,partial:!0},qk={tokenize:B3,partial:!0},Hk={tokenize:V3,partial:!0},I3={tokenize:q3,partial:!0},Kk={name:"wwwAutolink",tokenize:z3,previous:Gk},Wk={name:"protocolAutolink",tokenize:F3,previous:Jk},Er={name:"emailAutolink",tokenize:M3,previous:Xk},ur={};function D3(){return{text:ur}}let xs=48;for(;xs<123;)ur[xs]=Er,xs++,xs===58?xs=65:xs===91&&(xs=97);ur[43]=Er;ur[45]=Er;ur[46]=Er;ur[95]=Er;ur[72]=[Er,Wk];ur[104]=[Er,Wk];ur[87]=[Er,Kk];ur[119]=[Er,Kk];function M3(e,t,n){const r=this;let s,o;return a;function a(g){return!Lf(g)||!Xk.call(r,r.previous)||Xp(r.events)?n(g):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(g))}function c(g){return Lf(g)?(e.consume(g),c):g===64?(e.consume(g),u):n(g)}function u(g){return g===46?e.check(I3,p,f)(g):g===45||g===95||Jt(g)?(o=!0,e.consume(g),u):p(g)}function f(g){return e.consume(g),s=!0,u}function p(g){return o&&s&&tn(r.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),t(g)):n(g)}}function z3(e,t,n){const r=this;return s;function s(a){return a!==87&&a!==119||!Gk.call(r,r.previous)||Xp(r.events)?n(a):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(L3,e.attempt(Vk,e.attempt(qk,o),n),n)(a))}function o(a){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),t(a)}}function F3(e,t,n){const r=this;let s="",o=!1;return a;function a(g){return(g===72||g===104)&&Jk.call(r,r.previous)&&!Xp(r.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),s+=String.fromCodePoint(g),e.consume(g),c):n(g)}function c(g){if(tn(g)&&s.length<5)return s+=String.fromCodePoint(g),e.consume(g),c;if(g===58){const y=s.toLowerCase();if(y==="http"||y==="https")return e.consume(g),u}return n(g)}function u(g){return g===47?(e.consume(g),o?f:(o=!0,u)):n(g)}function f(g){return g===null||wc(g)||st(g)||Is(g)||Wc(g)?n(g):e.attempt(Vk,e.attempt(qk,p),n)(g)}function p(g){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),t(g)}}function $3(e,t,n){let r=0;return s;function s(a){return(a===87||a===119)&&r<3?(r++,e.consume(a),s):a===46&&r===3?(e.consume(a),o):n(a)}function o(a){return a===null?n(a):t(a)}}function U3(e,t,n){let r,s,o;return a;function a(f){return f===46||f===95?e.check(Hk,u,c)(f):f===null||st(f)||Is(f)||f!==45&&Wc(f)?u(f):(o=!0,e.consume(f),a)}function c(f){return f===95?r=!0:(s=r,r=void 0),e.consume(f),a}function u(f){return s||r||!o?n(f):t(f)}}function B3(e,t){let n=0,r=0;return s;function s(a){return a===40?(n++,e.consume(a),s):a===41&&r<n?o(a):a===33||a===34||a===38||a===39||a===41||a===42||a===44||a===46||a===58||a===59||a===60||a===63||a===93||a===95||a===126?e.check(Hk,t,o)(a):a===null||st(a)||Is(a)?t(a):(e.consume(a),s)}function o(a){return a===41&&r++,e.consume(a),s}}function V3(e,t,n){return r;function r(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),r):c===38?(e.consume(c),o):c===93?(e.consume(c),s):c===60||c===null||st(c)||Is(c)?t(c):n(c)}function s(c){return c===null||c===40||c===91||st(c)||Is(c)?t(c):r(c)}function o(c){return tn(c)?a(c):n(c)}function a(c){return c===59?(e.consume(c),r):tn(c)?(e.consume(c),a):n(c)}}function q3(e,t,n){return r;function r(o){return e.consume(o),s}function s(o){return Jt(o)?n(o):t(o)}}function Gk(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||st(e)}function Jk(e){return!tn(e)}function Xk(e){return!(e===47||Lf(e))}function Lf(e){return e===43||e===45||e===46||e===95||Jt(e)}function Xp(e){let t=e.length,n=!1;for(;t--;){const r=e[t][1];if((r.type==="labelLink"||r.type==="labelImage")&&!r._balanced){n=!0;break}if(r._gfmAutolinkLiteralWalkedInto){n=!1;break}}return e.length>0&&!n&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),n}const H3={tokenize:Z3,partial:!0};function K3(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:X3,continuation:{tokenize:Y3},exit:Q3}},text:{91:{name:"gfmFootnoteCall",tokenize:J3},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:W3,resolveTo:G3}}}}function W3(e,t,n){const r=this;let s=r.events.length;const o=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let a;for(;s--;){const u=r.events[s][1];if(u.type==="labelImage"){a=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!a||!a._balanced)return n(u);const f=Jn(r.sliceSerialize({start:a.end,end:r.now()}));return f.codePointAt(0)!==94||!o.includes(f.slice(1))?n(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),t(u))}}function G3(e,t){let n=e.length;for(;n--;)if(e[n][1].type==="labelImage"&&e[n][0]==="enter"){e[n][1];break}e[n+1][1].type="data",e[n+3][1].type="gfmFootnoteCallLabelMarker";const r={type:"gfmFootnoteCall",start:Object.assign({},e[n+3][1].start),end:Object.assign({},e[e.length-1][1].end)},s={type:"gfmFootnoteCallMarker",start:Object.assign({},e[n+3][1].end),end:Object.assign({},e[n+3][1].end)};s.end.column++,s.end.offset++,s.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},s.end),end:Object.assign({},e[e.length-1][1].start)},a={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[n+1],e[n+2],["enter",r,t],e[n+3],e[n+4],["enter",s,t],["exit",s,t],["enter",o,t],["enter",a,t],["exit",a,t],["exit",o,t],e[e.length-2],e[e.length-1],["exit",r,t]];return e.splice(n,e.length-n+1,...c),e}function J3(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o=0,a;return c;function c(g){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),u}function u(g){return g!==94?n(g):(e.enter("gfmFootnoteCallMarker"),e.consume(g),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",f)}function f(g){if(o>999||g===93&&!a||g===null||g===91||st(g))return n(g);if(g===93){e.exit("chunkString");const y=e.exit("gfmFootnoteCallString");return s.includes(Jn(r.sliceSerialize(y)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(g),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),t):n(g)}return st(g)||(a=!0),o++,e.consume(g),g===92?p:f}function p(g){return g===91||g===92||g===93?(e.consume(g),o++,f):f(g)}}function X3(e,t,n){const r=this,s=r.parser.gfmFootnotes||(r.parser.gfmFootnotes=[]);let o,a=0,c;return u;function u(b){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(b),e.exit("gfmFootnoteDefinitionLabelMarker"),f}function f(b){return b===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(b),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",p):n(b)}function p(b){if(a>999||b===93&&!c||b===null||b===91||st(b))return n(b);if(b===93){e.exit("chunkString");const w=e.exit("gfmFootnoteDefinitionLabelString");return o=Jn(r.sliceSerialize(w)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(b),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),y}return st(b)||(c=!0),a++,e.consume(b),b===92?g:p}function g(b){return b===91||b===92||b===93?(e.consume(b),a++,p):p(b)}function y(b){return b===58?(e.enter("definitionMarker"),e.consume(b),e.exit("definitionMarker"),s.includes(o)||s.push(o),Ge(e,v,"gfmFootnoteDefinitionWhitespace")):n(b)}function v(b){return t(b)}}function Y3(e,t,n){return e.check(Ea,t,e.attempt(H3,t,n))}function Q3(e){e.exit("gfmFootnoteDefinition")}function Z3(e,t,n){const r=this;return Ge(e,s,"gfmFootnoteDefinitionIndent",5);function s(o){const a=r.events[r.events.length-1];return a&&a[1].type==="gfmFootnoteDefinitionIndent"&&a[2].sliceSerialize(a[1],!0).length===4?t(o):n(o)}}function ez(e){let n=(e||{}).singleTilde;const r={name:"strikethrough",tokenize:o,resolveAll:s};return n==null&&(n=!0),{text:{126:r},insideSpan:{null:[r]},attentionMarkers:{null:[126]}};function s(a,c){let u=-1;for(;++u<a.length;)if(a[u][0]==="enter"&&a[u][1].type==="strikethroughSequenceTemporary"&&a[u][1]._close){let f=u;for(;f--;)if(a[f][0]==="exit"&&a[f][1].type==="strikethroughSequenceTemporary"&&a[f][1]._open&&a[u][1].end.offset-a[u][1].start.offset===a[f][1].end.offset-a[f][1].start.offset){a[u][1].type="strikethroughSequence",a[f][1].type="strikethroughSequence";const p={type:"strikethrough",start:Object.assign({},a[f][1].start),end:Object.assign({},a[u][1].end)},g={type:"strikethroughText",start:Object.assign({},a[f][1].end),end:Object.assign({},a[u][1].start)},y=[["enter",p,c],["enter",a[f][1],c],["exit",a[f][1],c],["enter",g,c]],v=c.parser.constructs.insideSpan.null;v&&En(y,y.length,0,Gc(v,a.slice(f+1,u),c)),En(y,y.length,0,[["exit",g,c],["enter",a[u][1],c],["exit",a[u][1],c],["exit",p,c]]),En(a,f-1,u-f+3,y),u=f+y.length-2;break}}for(u=-1;++u<a.length;)a[u][1].type==="strikethroughSequenceTemporary"&&(a[u][1].type="data");return a}function o(a,c,u){const f=this.previous,p=this.events;let g=0;return y;function y(b){return f===126&&p[p.length-1][1].type!=="characterEscape"?u(b):(a.enter("strikethroughSequenceTemporary"),v(b))}function v(b){const w=Fi(f);if(b===126)return g>1?u(b):(a.consume(b),g++,v);if(g<2&&!n)return u(b);const k=a.exit("strikethroughSequenceTemporary"),j=Fi(b);return k._open=!j||j===2&&!!w,k._close=!w||w===2&&!!j,c(b)}}}class tz{constructor(){this.map=[]}add(t,n,r){nz(this,t,n,r)}consume(t){if(this.map.sort(function(o,a){return o[0]-a[0]}),this.map.length===0)return;let n=this.map.length;const r=[];for(;n>0;)n-=1,r.push(t.slice(this.map[n][0]+this.map[n][1]),this.map[n][2]),t.length=this.map[n][0];r.push(t.slice()),t.length=0;let s=r.pop();for(;s;){for(const o of s)t.push(o);s=r.pop()}this.map.length=0}}function nz(e,t,n,r){let s=0;if(!(n===0&&r.length===0)){for(;s<e.map.length;){if(e.map[s][0]===t){e.map[s][1]+=n,e.map[s][2].push(...r);return}s+=1}e.map.push([t,n,r])}}function rz(e,t){let n=!1;const r=[];for(;t<e.length;){const s=e[t];if(n){if(s[0]==="enter")s[1].type==="tableContent"&&r.push(e[t+1][1].type==="tableDelimiterMarker"?"left":"none");else if(s[1].type==="tableContent"){if(e[t-1][1].type==="tableDelimiterMarker"){const o=r.length-1;r[o]=r[o]==="left"?"center":"right"}}else if(s[1].type==="tableDelimiterRow")break}else s[0]==="enter"&&s[1].type==="tableDelimiterRow"&&(n=!0);t+=1}return r}function sz(){return{flow:{null:{name:"table",tokenize:iz,resolveAll:oz}}}}function iz(e,t,n){const r=this;let s=0,o=0,a;return c;function c(L){let Y=r.events.length-1;for(;Y>-1;){const H=r.events[Y][1].type;if(H==="lineEnding"||H==="linePrefix")Y--;else break}const X=Y>-1?r.events[Y][1].type:null,de=X==="tableHead"||X==="tableRow"?A:u;return de===A&&r.parser.lazy[r.now().line]?n(L):de(L)}function u(L){return e.enter("tableHead"),e.enter("tableRow"),f(L)}function f(L){return L===124||(a=!0,o+=1),p(L)}function p(L){return L===null?n(L):Re(L)?o>1?(o=0,r.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(L),e.exit("lineEnding"),v):n(L):We(L)?Ge(e,p,"whitespace")(L):(o+=1,a&&(a=!1,s+=1),L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),a=!0,p):(e.enter("data"),g(L)))}function g(L){return L===null||L===124||st(L)?(e.exit("data"),p(L)):(e.consume(L),L===92?y:g)}function y(L){return L===92||L===124?(e.consume(L),g):g(L)}function v(L){return r.interrupt=!1,r.parser.lazy[r.now().line]?n(L):(e.enter("tableDelimiterRow"),a=!1,We(L)?Ge(e,b,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(L):b(L))}function b(L){return L===45||L===58?k(L):L===124?(a=!0,e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),w):N(L)}function w(L){return We(L)?Ge(e,k,"whitespace")(L):k(L)}function k(L){return L===58?(o+=1,a=!0,e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),j):L===45?(o+=1,j(L)):L===null||Re(L)?P(L):N(L)}function j(L){return L===45?(e.enter("tableDelimiterFiller"),C(L)):N(L)}function C(L){return L===45?(e.consume(L),C):L===58?(a=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(L),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(L))}function S(L){return We(L)?Ge(e,P,"whitespace")(L):P(L)}function P(L){return L===124?b(L):L===null||Re(L)?!a||s!==o?N(L):(e.exit("tableDelimiterRow"),e.exit("tableHead"),t(L)):N(L)}function N(L){return n(L)}function A(L){return e.enter("tableRow"),$(L)}function $(L){return L===124?(e.enter("tableCellDivider"),e.consume(L),e.exit("tableCellDivider"),$):L===null||Re(L)?(e.exit("tableRow"),t(L)):We(L)?Ge(e,$,"whitespace")(L):(e.enter("data"),G(L))}function G(L){return L===null||L===124||st(L)?(e.exit("data"),$(L)):(e.consume(L),L===92?B:G)}function B(L){return L===92||L===124?(e.consume(L),G):G(L)}}function oz(e,t){let n=-1,r=!0,s=0,o=[0,0,0,0],a=[0,0,0,0],c=!1,u=0,f,p,g;const y=new tz;for(;++n<e.length;){const v=e[n],b=v[1];v[0]==="enter"?b.type==="tableHead"?(c=!1,u!==0&&(r_(y,t,u,f,p),p=void 0,u=0),f={type:"table",start:Object.assign({},b.start),end:Object.assign({},b.end)},y.add(n,0,[["enter",f,t]])):b.type==="tableRow"||b.type==="tableDelimiterRow"?(r=!0,g=void 0,o=[0,0,0,0],a=[0,n+1,0,0],c&&(c=!1,p={type:"tableBody",start:Object.assign({},b.start),end:Object.assign({},b.end)},y.add(n,0,[["enter",p,t]])),s=b.type==="tableDelimiterRow"?2:p?3:1):s&&(b.type==="data"||b.type==="tableDelimiterMarker"||b.type==="tableDelimiterFiller")?(r=!1,a[2]===0&&(o[1]!==0&&(a[0]=a[1],g=Jl(y,t,o,s,void 0,g),o=[0,0,0,0]),a[2]=n)):b.type==="tableCellDivider"&&(r?r=!1:(o[1]!==0&&(a[0]=a[1],g=Jl(y,t,o,s,void 0,g)),o=a,a=[o[1],n,0,0])):b.type==="tableHead"?(c=!0,u=n):b.type==="tableRow"||b.type==="tableDelimiterRow"?(u=n,o[1]!==0?(a[0]=a[1],g=Jl(y,t,o,s,n,g)):a[1]!==0&&(g=Jl(y,t,a,s,n,g)),s=0):s&&(b.type==="data"||b.type==="tableDelimiterMarker"||b.type==="tableDelimiterFiller")&&(a[3]=n)}for(u!==0&&r_(y,t,u,f,p),y.consume(t.events),n=-1;++n<t.events.length;){const v=t.events[n];v[0]==="enter"&&v[1].type==="table"&&(v[1]._align=rz(t.events,n))}return e}function Jl(e,t,n,r,s,o){const a=r===1?"tableHeader":r===2?"tableDelimiter":"tableData",c="tableContent";n[0]!==0&&(o.end=Object.assign({},ki(t.events,n[0])),e.add(n[0],0,[["exit",o,t]]));const u=ki(t.events,n[1]);if(o={type:a,start:Object.assign({},u),end:Object.assign({},u)},e.add(n[1],0,[["enter",o,t]]),n[2]!==0){const f=ki(t.events,n[2]),p=ki(t.events,n[3]),g={type:c,start:Object.assign({},f),end:Object.assign({},p)};if(e.add(n[2],0,[["enter",g,t]]),r!==2){const y=t.events[n[2]],v=t.events[n[3]];if(y[1].end=Object.assign({},v[1].end),y[1].type="chunkText",y[1].contentType="text",n[3]>n[2]+1){const b=n[2]+1,w=n[3]-n[2]-1;e.add(b,w,[])}}e.add(n[3]+1,0,[["exit",g,t]])}return s!==void 0&&(o.end=Object.assign({},ki(t.events,s)),e.add(s,0,[["exit",o,t]]),o=void 0),o}function r_(e,t,n,r,s){const o=[],a=ki(t.events,n);s&&(s.end=Object.assign({},a),o.push(["exit",s,t])),r.end=Object.assign({},a),o.push(["exit",r,t]),e.add(n+1,0,o)}function ki(e,t){const n=e[t],r=n[0]==="enter"?"start":"end";return n[1][r]}const az={name:"tasklistCheck",tokenize:cz};function lz(){return{text:{91:az}}}function cz(e,t,n){const r=this;return s;function s(u){return r.previous!==null||!r._gfmTasklistFirstContentOfListItem?n(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return st(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),a):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),a):n(u)}function a(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):n(u)}function c(u){return Re(u)?t(u):We(u)?e.check({tokenize:uz},t,n)(u):n(u)}}function uz(e,t,n){return Ge(e,r,"whitespace");function r(s){return s===null?n(s):t(s)}}function dz(e){return ak([D3(),K3(),ez(e),sz(),lz()])}const hz={};function fz(e){const t=this,n=e||hz,r=t.data(),s=r.micromarkExtensions||(r.micromarkExtensions=[]),o=r.fromMarkdownExtensions||(r.fromMarkdownExtensions=[]),a=r.toMarkdownExtensions||(r.toMarkdownExtensions=[]);s.push(dz(n)),o.push(P3()),a.push(O3(n))}function pz({message:e}){const{t}=Ze(),n=e.role==="user",r={p:({node:s,...o})=>h.jsx("p",{className:"mb-2 last:mb-0",...o}),a:({node:s,...o})=>h.jsx("a",{className:"text-primary hover:underline",...o}),ul:({node:s,...o})=>h.jsx("ul",{className:"list-disc ml-4 mb-2",...o}),ol:({node:s,...o})=>h.jsx("ol",{className:"list-decimal ml-4 mb-2",...o}),blockquote:({node:s,...o})=>h.jsx("blockquote",{className:"border-l-2 border-border/50 pl-3 text-fg/70 italic mb-2",...o}),table:({node:s,...o})=>h.jsx("table",{className:"w-full text-xs border-collapse my-2",...o}),th:({node:s,...o})=>h.jsx("th",{className:"border border-border/20 bg-surface/50 px-2 py-1 text-left font-semibold",...o}),td:({node:s,...o})=>h.jsx("td",{className:"border border-border/20 px-2 py-1 align-top",...o}),code:({node:s,inline:o,className:a,...c})=>h.jsx("code",{className:o?"bg-black/20 rounded px-1 py-0.5 font-mono text-xs":"block bg-black/30 rounded-lg p-3 font-mono text-xs leading-relaxed overflow-x-auto",...c}),pre:({node:s,...o})=>h.jsx("pre",{className:"my-2",...o})};return h.jsx("div",{className:`flex w-full ${n?"justify-end":"justify-start"}`,children:h.jsxs("div",{className:`flex gap-3 max-w-[85%] ${n?"flex-row-reverse":"flex-row"}`,children:[h.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center shrink-0 ${n?"bg-primary text-white":"bg-gradient-to-br from-indigo-500 to-purple-600 text-white shadow-lg glow-primary"}`,children:n?h.jsx(Nc,{size:16}):h.jsx(cj,{size:16})}),h.jsxs("div",{className:`flex flex-col ${n?"items-end":"items-start"}`,children:[h.jsx("div",{className:`px-5 py-3.5 rounded-2xl text-sm leading-relaxed shadow-sm ${n?"bg-primary/15 text-fg rounded-tr-none":"bg-surface/70 backdrop-blur-md text-fg rounded-tl-none"}`,children:h.jsx("div",{className:"markdown-body",children:h.jsx(Wp,{remarkPlugins:[fz],components:r,children:e.content})})}),h.jsx("span",{className:"text-[10px] text-fg/30 mt-1 px-1",children:new Date(e.created_at).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})})]})]})})}function mz({sessionId:e,onContextUpdate:t,onNewSession:n,onSessionCreated:r}){const{t:s}=Ze(),[o,a]=R.useState([]),[c,u]=R.useState(""),[f,p]=R.useState(!1),[g,y]=R.useState(!1),v=R.useRef(null),b=R.useRef(null),w=R.useRef(!0),k=R.useRef(null);R.useEffect(()=>{e?C(e):(a([]),t([]))},[e,t]),R.useEffect(()=>{w.current&&v.current&&v.current.scrollIntoView({behavior:"smooth"})},[o,g]);const j=()=>{const N=b.current;if(!N)return;const A=N.scrollHeight-N.scrollTop-N.clientHeight;w.current=A<64},C=async N=>{try{const{data:{session:A}}=await oe.auth.getSession();if(!A)return;const $=await Qe.get(`/api/chat/sessions/${N}/messages`,{headers:{"x-user-id":A.user.id}});if($.data.success){a($.data.messages);const G=$.data.messages[$.data.messages.length-1];G&&G.role==="assistant"&&G.context_sources&&t(G.context_sources)}}catch(A){console.error("Failed to fetch messages",A)}},S=async N=>{if(N?.preventDefault(),!c.trim()||f)return;const A=c.trim();u(""),k.current&&(k.current.style.height="auto");const{data:{session:$}}=await oe.auth.getSession();if(!$)return;const G=$.user.id;p(!0),y(!0);try{let B=e;if(!B){const X=await Qe.post("/api/chat/sessions",{},{headers:{"x-user-id":G}});if(X.data.success)B=X.data.session.id,r(B);else throw new Error("Failed to create session")}const L={id:"temp-"+Date.now(),role:"user",content:A,created_at:new Date().toISOString()};a(X=>[...X,L]);const Y=await Qe.post("/api/chat/message",{sessionId:B,content:A},{headers:{"x-user-id":G}});if(Y.data.success){const X=Y.data.message;a(de=>[...de,X]),X.context_sources&&t(X.context_sources)}}catch(B){console.error("Message failed",B),a(L=>[...L,{id:"err-"+Date.now(),role:"assistant",content:s("chat.error_message"),created_at:new Date().toISOString()}])}finally{p(!1),y(!1)}},P=N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),S())};return h.jsxs(h.Fragment,{children:[h.jsxs("div",{ref:b,onScroll:j,className:"flex-1 overflow-y-auto p-5 space-y-6 scrollbar-on-hover",children:[o.length===0?h.jsxs("div",{className:"h-full flex flex-col items-center justify-center p-8 text-center opacity-70",children:[h.jsx("div",{className:"w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center mb-4 text-primary animate-pulse",children:h.jsx(Mj,{size:32})}),h.jsx("h3",{className:"text-xl font-bold mb-2",children:s("chat.title")}),h.jsx("p",{className:"text-sm max-w-md mx-auto mb-8",children:s("chat.desc")}),h.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3 max-w-lg w-full",children:[s("chat.suggestions.react"),s("chat.suggestions.ai"),s("chat.suggestions.finance"),s("chat.suggestions.performance")].map((N,A)=>h.jsx("button",{onClick:()=>u(N),className:"text-left p-3 text-xs bg-surface/30 hover:bg-surface/50 border border-border/20 rounded-xl transition-all hover:scale-[1.02]",children:N},A))})]}):h.jsxs(h.Fragment,{children:[o.map((N,A)=>h.jsx(pz,{message:N},N.id||A)),g&&h.jsx(Fe.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex justify-start w-full",children:h.jsxs("div",{className:"bg-surface/30 border border-border/10 rounded-2xl px-4 py-3 flex items-center gap-3",children:[h.jsxs("div",{className:"flex gap-1",children:[h.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0s"}}),h.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.1s"}}),h.jsx("span",{className:"w-1.5 h-1.5 bg-primary/60 rounded-full animate-bounce",style:{animationDelay:"0.2s"}})]}),h.jsx("span",{className:"text-xs text-fg/50 font-mono",children:s("chat.thinking")})]})})]}),h.jsx("div",{ref:v})]}),h.jsx("div",{className:"p-4 bg-surface/20 border-t border-border/10 backdrop-blur-md",children:h.jsx("form",{onSubmit:S,className:"relative max-w-4xl mx-auto",children:h.jsxs("div",{className:"relative flex items-end gap-2 bg-surface/55 border border-border/10 rounded-2xl px-2 py-2 shadow-sm focus-within:ring-2 focus-within:ring-primary/30 focus-within:border-primary/30 transition-all",children:[h.jsx("textarea",{ref:k,value:c,onChange:N=>{u(N.target.value),N.target.style.height="auto",N.target.style.height=N.target.scrollHeight+"px"},onKeyDown:P,placeholder:s("chat.placeholder"),rows:1,className:"w-full bg-transparent border-none focus:ring-0 focus:outline-none py-2 pl-2 text-fg resize-none min-h-[24px] max-h-[200px] placeholder:text-fg/40",disabled:f}),h.jsx("button",{type:"submit",disabled:!c.trim()||f,className:"p-2 mb-0.5 bg-primary text-white rounded-xl shadow-lg hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all shrink-0",children:f?h.jsx(Tc,{size:18,className:"animate-spin"}):h.jsx(Ij,{size:18})})]})})})]})}function gz({sources:e,onClose:t}){const{t:n}=Ze();return!e||e.length===0?null:h.jsxs(Fe.div,{initial:{opacity:0,x:20,width:0},animate:{opacity:1,x:0,width:300},exit:{opacity:0,x:20,width:0},className:"bg-surface/25 backdrop-blur-xl rounded-2xl border border-border/10 overflow-hidden flex flex-col shadow-[0_8px_24px_rgba(0,0,0,0.16)]",children:[h.jsxs("div",{className:"p-4 border-b border-border/10 flex items-center justify-between bg-surface/15",children:[h.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-fg/80",children:[h.jsx(u_,{size:16,className:"text-secondary"}),h.jsx("span",{children:n("chat.relevant_context")})]}),h.jsx("button",{onClick:t,className:"p-1 hover:bg-surface rounded-md text-fg/40 hover:text-fg transition-colors",children:h.jsx(Cn,{size:14})})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-3 space-y-3",children:e.map((r,s)=>h.jsxs("div",{className:"p-3 bg-surface/20 hover:bg-surface/35 border border-border/5 rounded-xl transition-all group",children:[h.jsxs("div",{className:"flex justify-between items-start mb-2",children:[h.jsxs("div",{className:"flex items-center gap-1.5",children:[h.jsx("span",{className:"flex items-center justify-center w-4 h-4 bg-primary/10 text-primary text-[10px] font-bold rounded",children:s+1}),h.jsx("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded border ${r.score>=80?"bg-yellow-500/10 text-yellow-500 border-yellow-500/20":"bg-blue-500/10 text-blue-400 border-blue-500/20"}`,children:n("chat.match_score",{score:r.score})})]}),h.jsx("a",{href:r.url,target:"_blank",rel:"noopener noreferrer",className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-fg/40 hover:text-primary transition-opacity focus-visible:ring-2 focus-visible:ring-primary/40 rounded",children:h.jsx($i,{size:12})})]}),h.jsx("a",{href:r.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs font-bold text-fg/90 block mb-1 hover:text-primary transition-colors line-clamp-2",children:r.title}),h.jsx("p",{className:"text-[10px] text-fg/50 line-clamp-3 leading-relaxed",children:r.summary})]},s))}),h.jsx("div",{className:"p-3 border-t border-border/10 bg-surface/20 text-[10px] text-center text-fg/30",children:n("chat.rag_attribution",{count:e.length})})]})}function yz(){const[e,t]=R.useState(null),[n,r]=R.useState([]),[s,o]=R.useState(!0);return h.jsxs("div",{className:"flex h-full gap-4 overflow-hidden",children:[h.jsx(qL,{activeSessionId:e,onSelectSession:t}),h.jsx("div",{className:"flex-1 flex flex-col min-w-0 bg-surface/60 rounded-2xl overflow-hidden border border-border/15 shadow-[0_12px_30px_rgba(0,0,0,0.22)] relative",children:h.jsx(mz,{sessionId:e,onContextUpdate:a=>{r(a),a.length>0&&o(!0)},onNewSession:()=>t(null),onSessionCreated:a=>t(a)})}),s&&h.jsx(gz,{sources:n,onClose:()=>o(!1)})]})}function xz({isOpen:e,onClose:t}){const{t:n}=Ze(),[r,s]=R.useState(""),[o,a]=R.useState(!0);R.useEffect(()=>{e&&c()},[e]);const c=async()=>{a(!0);try{const f=await(await fetch("/CHANGELOG.md")).text();s(f)}catch(u){console.error("Failed to load changelog:",u),s(`# ${n("common.error")}
133
133
 
134
- ${n("shell.changelog_error")}`)}finally{a(!1)}};return h.jsx(Pt,{children:e&&h.jsxs(h.Fragment,{children:[h.jsx(Fe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),h.jsx(Fe.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",damping:25,stiffness:300},className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:h.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[h.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(u_,{size:24,className:"text-primary"}),h.jsx("h2",{className:"text-xl font-bold",children:n("shell.release_notes")})]}),h.jsx("button",{onClick:t,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:h.jsx(Cn,{size:20,className:"text-fg/60"})})]}),h.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:o?h.jsx("div",{className:"flex items-center justify-center py-12",children:h.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):h.jsx(Wp,{components:{h1:({children:u})=>h.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:u}),h2:({children:u})=>h.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:u}),h3:({children:u})=>h.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:u}),p:({children:u})=>h.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:u}),ul:({children:u})=>h.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:u}),li:({children:u})=>h.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:u}),a:({href:u,children:f})=>h.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:f}),code:({children:u})=>h.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:u}),strong:({children:u})=>h.jsx("strong",{className:"font-bold text-fg",children:u})},children:r})})]})})]})})}function vz({asset:e,onClose:t}){const{t:n}=Ze(),r=()=>{e.content&&navigator.clipboard.writeText(e.content)},s=()=>{if(!e.content)return;const o=new Blob([e.content],{type:"text/markdown"}),a=URL.createObjectURL(o),c=document.createElement("a");c.href=a,c.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(a)};return h.jsx(Pt,{children:e&&h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400",children:e.type==="audio"?h.jsx($h,{className:"w-5 h-5"}):h.jsx(Oi,{className:"w-5 h-5"})}),h.jsxs("div",{children:[h.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),h.jsxs("p",{className:"text-xs text-gray-500",children:[new Date(e.created_at).toLocaleString()," • ",n("discovery.sources_count",{count:e.metadata?.source_signal_count||0})]})]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:r,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Copy Content",children:h.jsx(If,{className:"w-4 h-4"})}),h.jsx("button",{onClick:s,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Download File",children:h.jsx(zh,{className:"w-4 h-4"})}),h.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),h.jsx("button",{onClick:t,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:h.jsx(Cn,{className:"w-5 h-5"})})]})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?h.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[h.jsx(Rt,{className:"w-12 h-12 animate-spin text-purple-500"}),h.jsxs("div",{className:"text-center",children:[h.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?n("transmute.generating_asset"):n("transmute.queued_desktop")}),h.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:n("transmute.desktop_processing")})]})]}):e.type==="markdown"?h.jsx("div",{className:"prose dark:prose-invert max-w-none",children:h.jsx(Wp,{children:e.content||""})}):e.type==="audio"?h.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[h.jsx("div",{className:"w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center animate-pulse",children:h.jsx($h,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),h.jsx("p",{className:"text-gray-500",children:n("transmute.unsupported_type")}),h.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[h.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):h.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function s_({engine:e,onClose:t,onSave:n,onDelete:r}){const{t:s}=Ze(),{showToast:o}=Kc(),[a,c]=R.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[u,f]=R.useState(!1);R.useEffect(()=>{e&&c({title:e.title,type:e.type,status:e.status,config:{schedule:e.config.schedule||"",min_score:e.config.filters?.min_score||70,categories:Array.isArray(e.config.category)?e.config.category:e.config.category?[e.config.category]:[],custom_prompt:e.config.custom_prompt||"",max_signals:e.config.max_signals||10,execution_mode:e.config.execution_mode||"local"}})},[e]);const p=async()=>{try{const v={title:a.title,type:a.type,status:a.status,config:{schedule:a.config.schedule,filters:{min_score:a.config.min_score,category:a.config.category},custom_prompt:a.config.custom_prompt,max_signals:a.config.max_signals,execution_mode:a.config.execution_mode}};if(e){const{data:b,error:w}=await oe.from("engines").update(v).eq("id",e.id).select().single();if(w)throw w;n(b),o("Engine updated successfully","success")}else{const{data:{user:b}}=await oe.auth.getUser();if(!b)throw new Error("Not authenticated");const{data:w,error:k}=await oe.from("engines").insert({...v,user_id:b.id}).select().single();if(k)throw k;n(w),o("Engine created successfully","success")}t()}catch(v){console.error("Save error:",v),o(v.message||"Failed to save engine","error")}},g=async()=>{if(!(!e||!r))try{const{error:v}=await oe.from("engines").delete().eq("id",e.id);if(v)throw v;r(e.id),o("Engine deleted","success"),t()}catch(v){o(v.message||"Failed to delete engine","error")}},y=()=>{f(!1),t()};return!e&&!t?null:h.jsx(Pt,{children:h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[h.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:s(e?"transmute.edit_engine":"transmute.create_engine")}),h.jsx("button",{onClick:y,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:h.jsx(Cn,{className:"w-5 h-5"})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.engine_name")}),h.jsx("input",{type:"text",value:a.title,onChange:v=>c({...a,title:v.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g., Daily Tech Brief"})]}),h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.type")}),h.jsxs("select",{value:a.type,onChange:v=>c({...a,type:v.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[h.jsx("option",{value:"newsletter",children:s("transmute.newsletter")}),h.jsx("option",{value:"thread",children:s("transmute.thread")}),h.jsx("option",{value:"audio",children:"Audio Brief"}),h.jsx("option",{value:"report",children:"Report"})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.status")}),h.jsxs("select",{value:a.status,onChange:v=>c({...a,status:v.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[h.jsx("option",{value:"active",children:s("common.status_active")}),h.jsx("option",{value:"paused",children:s("common.status_paused")}),h.jsx("option",{value:"draft",children:"Draft"})]})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.execution_env")}),h.jsxs("select",{value:a.config.execution_mode,onChange:v=>c({...a,config:{...a.config,execution_mode:v.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[h.jsx("option",{value:"local",children:s("transmute.local_llm")}),h.jsx("option",{value:"desktop",children:s("transmute.desktop_swarm")})]}),h.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:a.config.execution_mode==="desktop"?s("transmute.env_desc_desktop"):s("transmute.env_desc_local")})]})]}),h.jsxs("div",{className:"space-y-4",children:[h.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.min_score")}),h.jsx("input",{type:"number",min:"0",max:"100",value:a.config.min_score,onChange:v=>c({...a,config:{...a.config,min_score:parseInt(v.target.value)||0}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.max_signals")}),h.jsx("input",{type:"number",min:"1",max:"50",value:a.config.max_signals,onChange:v=>c({...a,config:{...a.config,max_signals:parseInt(v.target.value)||10}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.category_filter")}),h.jsxs("select",{multiple:!0,value:a.config.categories,onChange:v=>{const b=Array.from(v.target.selectedOptions,w=>w.value);c({...a,config:{...a.config,categories:b}})},className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 min-h-[100px]",children:[h.jsx("option",{value:"AI & ML",children:"AI & ML"}),h.jsx("option",{value:"Technology",children:"Technology"}),h.jsx("option",{value:"Business",children:"Business"}),h.jsx("option",{value:"Finance",children:"Finance"}),h.jsx("option",{value:"Science",children:"Science"}),h.jsx("option",{value:"Politics",children:"Politics"})]}),h.jsx("p",{className:"text-xs text-gray-500 mt-1",children:s("transmute.multi_select_hint")})]})]}),h.jsxs("div",{children:[h.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[s("transmute.schedule")," (",s("common.optional"),")"]}),h.jsx("input",{type:"text",value:a.config.schedule,onChange:v=>c({...a,config:{...a.config,schedule:v.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",placeholder:"e.g., Daily @ 9am, Manual"}),h.jsx("p",{className:"text-xs text-gray-500 mt-1",children:s("transmute.schedule_hint")})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.prompt_override")}),h.jsx("textarea",{value:a.config.custom_prompt,onChange:v=>c({...a,config:{...a.config,custom_prompt:v.target.value}}),rows:4,className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 resize-none",placeholder:s("transmute.prompt_placeholder")})]})]}),h.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50",children:[e&&r?u?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-red-600 font-medium",children:s("transmute.delete_confirm")}),h.jsx("button",{onClick:g,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:s("transmute.confirm")}),h.jsx("button",{onClick:()=>f(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:s("common.cancel")})]}):h.jsxs("button",{onClick:()=>f(!0),className:"flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:[h.jsx(zf,{className:"w-4 h-4"}),s("common.delete")]}):h.jsx("div",{}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:y,className:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"Cancel"}),h.jsxs("button",{onClick:p,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[h.jsx(_r,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const _z=({engine:e,onRun:t,onEdit:n,onToggle:r,onViewBrief:s,isLoading:o})=>{const{t:a}=Ze(),c=!!e.config.tag,u={newsletter:c?h.jsx(Df,{className:"w-5 h-5 text-blue-500"}):h.jsx(Oi,{className:"w-5 h-5 text-emerald-500"}),thread:h.jsx(nn,{className:"w-5 h-5 text-blue-500"}),audio:h.jsx($h,{className:"w-5 h-5 text-purple-500"}),report:h.jsx(ic,{className:"w-5 h-5 text-orange-500"})};return h.jsxs(Fe.div,{layout:!0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`p-5 rounded-2xl border ${e.status==="active"?"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 shadow-sm":"bg-gray-50 dark:bg-gray-900 border-dashed border-gray-300 dark:border-gray-700 opacity-75"} transition-all hover:shadow-md group`,children:[h.jsxs("div",{className:"flex justify-between items-start mb-4",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:u[e.type]||h.jsx(Oi,{className:"w-5 h-5"})}),h.jsxs("div",{children:[h.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),h.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[c?a("transmute.topic"):a(`transmute.${e.type}`,e.type)," ",a("transmute.pipeline")]})]})]}),h.jsxs("div",{className:"flex gap-1",children:[h.jsx("button",{onClick:()=>r(e.id,e.status),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:e.status==="active"?h.jsx(Pj,{className:"w-4 h-4"}):h.jsx(Wy,{className:"w-4 h-4"})}),h.jsx("button",{onClick:()=>s(e.id),title:a("transmute.view_json"),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:h.jsx(f_,{className:"w-4 h-4"})}),h.jsx("button",{onClick:()=>n(e.id),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:h.jsx(ic,{className:"w-4 h-4"})})]})]}),h.jsxs("div",{className:"space-y-2 mb-4",children:[h.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[h.jsx("span",{children:a("transmute.last_run")}),h.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString(a("common.locale_code")):a("transmute.never")})]}),h.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[h.jsx("span",{children:a("transmute.schedule")}),h.jsx("span",{children:e.config.schedule||a("transmute.manual")})]})]}),h.jsxs("button",{onClick:()=>t(e.id),disabled:o||e.status!=="active",className:"w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-gray-900 dark:bg-white text-white dark:text-gray-900 font-medium hover:opacity-90 disabled:opacity-50 transition-all text-sm",children:[o?h.jsx(Rt,{className:"w-4 h-4 animate-spin"}):h.jsx(Wy,{className:"w-4 h-4"}),a(o?"transmute.running":"transmute.run_engine")]})]})};function bz(){const{t:e}=Ze(),[t,n]=R.useState([]),[r,s]=R.useState(!0),[o,a]=R.useState(new Set),[c,u]=R.useState(null),[f,p]=R.useState(null),[g,y]=R.useState(!1),[v,b]=R.useState(null),[w,k]=R.useState(!1),[j,C]=R.useState(!1),{showToast:S}=Kc();R.useEffect(()=>{(async()=>N())();const K=oe.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},te=>{const ne=te.new;u(J=>J?.id===ne.id?ne:J),ne.status==="completed"&&te.old.status!=="completed"&&S(e("transmute.asset_ready",{title:ne.title}),"success")}).subscribe();return()=>{oe.removeChannel(K)}},[]);const P=async()=>{if(!j)try{C(!0),S(e("transmute.scanning"),"info");const{data:{session:H}}=await oe.auth.getSession(),K=Rs(),te={"Content-Type":"application/json","x-user-id":H?.user?.id||""};if(H?.access_token&&(te.Authorization=`Bearer ${H.access_token}`),K&&(te["x-supabase-url"]=K.url,te["x-supabase-key"]=K.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:te})).ok)throw new Error("Failed to generate engines");S(e("transmute.discovery_complete"),"success"),await N()}catch(H){console.error("Failed to generate engines:",H),S(e("transmute.discovery_failed"),"error")}finally{C(!1)}},N=async()=>{try{s(!0);const{data:{user:H}}=await oe.auth.getUser();if(!H)return;const{data:K,error:te}=await oe.from("engines").select("*").eq("user_id",H.id).order("created_at",{ascending:!1});if(te)throw te;n(K)}catch(H){console.error("Error fetching engines:",H),S(e("transmute.load_failed"),"error")}finally{s(!1)}},A=async H=>{if(!o.has(H))try{a(D=>new Set(D).add(H)),S(e("transmute.starting_run"),"info");const{data:{session:K}}=await oe.auth.getSession(),te=K?.access_token,ne=Rs(),J={"Content-Type":"application/json","x-user-id":K?.user?.id||""};te&&(J.Authorization=`Bearer ${te}`),ne&&(J["x-supabase-url"]=ne.url,J["x-supabase-key"]=ne.anonKey);const le=await fetch(`/api/engines/${H}/run`,{method:"POST",headers:J});if(!le.ok){const D=await le.json();throw new Error(D.error||"Run failed")}const T=await le.json();T.status==="completed"?S(e("transmute.run_complete",{title:T.title}),"success"):S(e("transmute.run_started_desktop",{id:T.id}),"info"),u(T),n(D=>D.map(W=>W.id===H?{...W,last_run_at:new Date().toISOString()}:W))}catch(K){console.error("Engine run error:",K),S(K.message||e("transmute.run_failed"),"error")}finally{a(K=>{const te=new Set(K);return te.delete(H),te})}},$=async H=>{try{y(!0);const{data:{session:K}}=await oe.auth.getSession(),te=Rs(),ne={"Content-Type":"application/json","x-user-id":K?.user?.id||""};K?.access_token&&(ne.Authorization=`Bearer ${K.access_token}`),te&&(ne["x-supabase-url"]=te.url,ne["x-supabase-key"]=te.anonKey);const J=await fetch(`/api/engines/${H}/brief`,{headers:ne});if(!J.ok)throw new Error("Failed to fetch brief");const le=await J.json();p(le)}catch{S(e("transmute.brief_failed"),"error")}finally{y(!1)}},G=async(H,K)=>{const te=K==="active"?"paused":"active";n(ne=>ne.map(J=>J.id===H?{...J,status:te}:J));try{const{error:ne}=await oe.from("engines").update({status:te}).eq("id",H);if(ne)throw ne;S(e("transmute.status_updated",{status:te}),"success")}catch{n(J=>J.map(le=>le.id===H?{...le,status:K}:le)),S(e("common.error"),"error")}},B=()=>{k(!0)},L=H=>{const K=t.find(te=>te.id===H);K&&b(K)},Y=H=>{n(K=>K.find(ne=>ne.id===H.id)?K.map(ne=>ne.id===H.id?H:ne):[H,...K])},X=H=>{n(K=>K.filter(te=>te.id!==H))},de=()=>{b(null),k(!1)};return h.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[h.jsx("div",{className:"flex-none p-6 border-b border-gray-200 dark:border-gray-800 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 sticky top-0",children:h.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[h.jsxs("div",{children:[h.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:e("transmute.title")}),h.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:e("transmute.desc")})]}),h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsxs("button",{onClick:P,disabled:j,className:"flex items-center gap-2 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-xl font-medium hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-all border border-purple-200 dark:border-purple-800 disabled:opacity-50",children:[j?h.jsx(Rt,{className:"w-4 h-4 animate-spin"}):h.jsx(nn,{className:"w-4 h-4"}),e("transmute.generate_engines")]}),h.jsxs("button",{onClick:B,className:"flex items-center gap-2 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-medium hover:opacity-90 transition-opacity shadow-lg shadow-purple-500/10",children:[h.jsx(Mf,{className:"w-4 h-4"}),e("transmute.new_engine")]})]})]})}),h.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:h.jsx("div",{className:"max-w-7xl mx-auto w-full",children:r?h.jsx("div",{className:"flex items-center justify-center h-64",children:h.jsx(Rt,{className:"w-8 h-8 animate-spin text-purple-500"})}):t.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[h.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:h.jsx(nn,{className:"w-8 h-8 text-gray-400"})}),h.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e("transmute.no_engines")}),h.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:e("transmute.no_engines_desc")}),h.jsx("button",{onClick:B,className:"px-6 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:e("transmute.create_engine")})]}):h.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.jsx(Pt,{children:t.map(H=>h.jsx(_z,{engine:H,onRun:A,onEdit:L,onToggle:G,onViewBrief:$,isLoading:o.has(H.id)},H.id))})})})}),h.jsx(Pt,{children:f&&h.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:h.jsx(f_,{className:"w-5 h-5"})}),h.jsxs("div",{children:[h.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e("transmute.view_json")}),h.jsx("p",{className:"text-xs text-gray-500",children:e("transmute.json_contract")})]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(f,null,2)),S(e("transmute.copied_json"),"info")},className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",children:h.jsx(If,{className:"w-4 h-4"})}),h.jsx("button",{onClick:()=>p(null),className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:h.jsx(Cn,{className:"w-5 h-5"})})]})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:h.jsx("pre",{className:"text-blue-300",children:JSON.stringify(f,null,2)})}),h.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 text-[10px] text-gray-500 text-center",children:e("transmute.json_footer")})]})})}),g&&h.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:h.jsx(Rt,{className:"w-10 h-10 animate-spin text-white"})}),h.jsx(vz,{asset:c,onClose:()=>u(null)}),v&&h.jsx(s_,{engine:v,onClose:de,onSave:Y,onDelete:X}),w&&h.jsx(s_,{engine:null,onClose:de,onSave:Y})]})}class wz{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}playTone(t,n,r=.3){if(this.enabled)try{const s=this.getAudioContext(),o=s.createOscillator(),a=s.createGain();o.connect(a),a.connect(s.destination),o.frequency.value=t,o.type="sine",a.gain.setValueAtTime(r,s.currentTime),a.gain.exponentialRampToValueAtTime(.01,s.currentTime+n),o.start(s.currentTime),o.stop(s.currentTime+n)}catch(s){console.warn("[Sound] Failed to play tone:",s)}}playSequence(t,n=.3){if(!this.enabled)return;let r=0;t.forEach(s=>{setTimeout(()=>{this.playTone(s.freq,s.duration,n)},r),r+=s.delay})}syncStart(){this.playSequence([{freq:261.63,duration:.15,delay:0},{freq:329.63,duration:.15,delay:100},{freq:392,duration:.2,delay:100}],.2)}signalFound(){this.playSequence([{freq:392,duration:.1,delay:0},{freq:523.25,duration:.15,delay:80}],.25)}syncComplete(){this.playSequence([{freq:261.63,duration:.12,delay:0},{freq:329.63,duration:.12,delay:80},{freq:392,duration:.12,delay:80},{freq:523.25,duration:.2,delay:80}],.2)}error(){this.playSequence([{freq:329.63,duration:.15,delay:0},{freq:261.63,duration:.2,delay:100}],.3)}click(){this.playTone(440,.05,.15)}}const zo=new wz;function kz(){const{t:e}=Ze(),[t,n]=R.useState([]),[r,s]=R.useState([]),[o,a]=R.useState("discovery"),[c,u]=R.useState(!1),[f,p]=R.useState(null),[g,y]=R.useState(!0),[v,b]=R.useState(!pv),[w,k]=R.useState(!0),[j,C]=R.useState(!1),[S,P]=R.useState(!1),[N,A]=R.useState(null),[$,G]=R.useState(!1),[B,L]=R.useState(!1),[Y,X]=R.useState(!1),[de,H]=R.useState(!0),[K,te]=R.useState(()=>localStorage.getItem("theme")||"dark"),[ne,J]=R.useState(null),le=R.useRef(null);R.useMemo(()=>{const pe=r.length;let ge=0,Te=0,fe=null;for(const _t of r){ge+=_t.score,_t.score>Te&&(Te=_t.score);const Yn=new Date(_t.date);(!fe||Yn>new Date(fe.date))&&(fe=_t)}const $e=pe?Math.round(ge/pe):0,rt=fe?new Date(fe.date):null;return{total:pe,average:$e,top:Te,latestTimestamp:rt,latestTitle:fe?.title??fe?.category??null}},[r]),R.useEffect(()=>{(async()=>{if(!pv){b(!0),y(!1);return}try{const{data:Te,error:fe}=await oe.from("init_state").select("is_initialized").single();fe?(console.warn("[App] Init check error (might be fresh DB):",fe),fe.code==="42P01"&&k(!1)):k(Te.is_initialized>0);const{data:{session:$e}}=await oe.auth.getSession();p($e?.user??null)}catch(Te){console.error("[App] Status check failed:",Te)}finally{y(!1)}})();const{data:{subscription:ge}}=oe.auth.onAuthStateChange((Te,fe)=>{p(fe?.user??null)});return()=>ge.unsubscribe()},[]),R.useEffect(()=>{document.documentElement.setAttribute("data-theme",K),localStorage.setItem("theme",K)},[K]);const[T,D]=R.useState({});R.useEffect(()=>{(async()=>{if(!f)return;const{data:ge}=await oe.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",f.id).maybeSingle();ge&&D(ge)})()},[f,$]),R.useEffect(()=>{if(!f)return;(async()=>{const{data:Te}=await oe.from("alchemy_settings").select("sound_enabled").eq("user_id",f.id).maybeSingle();if(Te){const fe=Te.sound_enabled??!0;H(fe),zo.setEnabled(fe)}})();const ge=oe.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${f.id}`},Te=>{const fe=Te.new;fe.agent_state==="Mining"&&!B&&(L(!0),X(!0),de&&zo.syncStart()),fe.agent_state==="Signal"&&de&&zo.signalFound(),fe.agent_state==="Completed"&&(L(!1),de&&(fe.metadata?.errors>0?zo.error():zo.syncComplete()),setTimeout(()=>{X(!1)},5e3),W())}).subscribe();return()=>{oe.removeChannel(ge)}},[f,B,de]),R.useEffect(()=>{const pe=new EventSource("/events");return pe.onmessage=ge=>{const Te=JSON.parse(ge.data);Te.type==="history"?n(fe=>[...Te.data,...fe].slice(0,100)):n(fe=>[Te,...fe].slice(0,100))},W(),()=>pe.close()},[f]),R.useEffect(()=>{le.current&&le.current.scrollIntoView({behavior:"smooth"})},[t]);const W=async()=>{try{if(f){const{data:ge,error:Te}=await oe.from("signals").select("*").order("created_at",{ascending:!1});if(!Te&&ge){s(ge.map(fe=>({id:fe.id,title:fe.title,score:fe.score,summary:fe.summary,date:fe.created_at,category:fe.category,entities:fe.entities})));return}}const pe=await Qe.get("/api/signals");s(pe.data)}catch(pe){console.error("Failed to fetch signals",pe)}},O=async()=>{u(!0);try{await Qe.post("/api/mine"),W()}catch(pe){console.error("Mining failed:",pe)}finally{u(!1)}},ve=(pe,ge)=>{pe==="logs"?(J(ge),a("logs")):a(pe)};return g?h.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:h.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):v?h.jsx($w,{onComplete:()=>b(!1)}):f?h.jsx(mL,{children:h.jsx(vL,{children:h.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[h.jsxs(Fe.aside,{animate:{width:j?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[h.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${j?"justify-center":""}`,children:[h.jsx("div",{className:"w-10 h-10 min-w-[40px] bg-gradient-to-br from-primary to-accent rounded-xl flex items-center justify-center shadow-lg glow-primary",children:h.jsx(nn,{className:"text-white fill-current",size:24})}),!j&&h.jsx(Fe.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),h.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[h.jsx(yi,{active:o==="discovery",onClick:()=>a("discovery"),icon:h.jsx(Ej,{size:20}),label:e("tabs.discovery"),collapsed:j}),h.jsx(yi,{active:o==="chat",onClick:()=>a("chat"),icon:h.jsx(Fh,{size:20}),label:e("tabs.chat"),collapsed:j}),h.jsx(yi,{active:o==="transmute",onClick:()=>a("transmute"),icon:h.jsx(nn,{size:20}),label:e("tabs.transmute"),collapsed:j}),h.jsx(yi,{active:o==="engine",onClick:()=>a("engine"),icon:h.jsx(ic,{size:20}),label:e("common.settings"),collapsed:j}),h.jsx(yi,{active:o==="logs",onClick:()=>a("logs"),icon:h.jsx(oc,{size:20}),label:e("tabs.logs"),collapsed:j}),h.jsx(yi,{active:o==="account",onClick:()=>a("account"),icon:h.jsx(Nc,{size:20}),label:e("common.account"),collapsed:j})]}),h.jsx("div",{className:"px-3 pb-2 border-t border-white/5 pt-4 mt-2 relative z-[100]",children:h.jsx("div",{className:j?"flex justify-center":"px-1",children:h.jsx(Np,{collapsed:j})})}),h.jsx("div",{className:"px-3 pb-2",children:h.jsxs("button",{onClick:()=>te(K==="dark"?"light":"dark"),className:`w-full flex items-center ${j?"justify-center":"gap-3"} px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium`,title:j?e(K==="dark"?"shell.switch_light":"shell.switch_dark"):"",children:[h.jsx("div",{className:"min-w-[20px] flex justify-center",children:K==="dark"?h.jsx(Fj,{size:18}):h.jsx(Rj,{size:18})}),!j&&h.jsx(Fe.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:e(K==="dark"?"common.light_mode":"common.dark_mode")})]})}),h.jsxs("div",{className:"px-3 pb-3",children:[h.jsx("button",{onClick:()=>C(!j),className:`w-full flex items-center px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium ${j?"justify-center":"gap-3"}`,children:j?h.jsx(gj,{size:20}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"min-w-[20px] flex justify-center",children:h.jsx(mj,{size:20})}),h.jsx("span",{children:e("common.collapse")})]})}),h.jsxs("button",{onClick:()=>P(!0),className:"w-full flex items-center justify-center gap-2 px-3 py-2 mt-2 text-[10px] font-mono text-fg/30 hover:text-primary hover:bg-surface/30 rounded-lg transition-all group",title:e("shell.view_changelog"),children:[!j&&h.jsxs(h.Fragment,{children:[h.jsx(Uh,{size:12,className:"group-hover:text-primary transition-colors"}),h.jsxs("span",{children:["v","1.0.59"]})]}),j&&h.jsx(Uh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),h.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[o==="discovery"&&h.jsxs(h.Fragment,{children:[h.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[h.jsxs("div",{children:[h.jsx("h2",{className:"text-2xl font-bold",children:e("tabs.discovery")}),h.jsx("p",{className:"text-sm text-fg/50",children:e("setup.welcome_desc")})]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsxs("button",{onClick:()=>G(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[h.jsx(ic,{size:16}),h.jsxs("div",{className:"flex flex-col items-start",children:[h.jsx("span",{children:e("discovery.sync_settings")}),h.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:T.sync_start_date?`${e("discovery.from")}: ${new Date(T.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:T.last_sync_checkpoint?`${e("discovery.checkpoint")}: ${new Date(T.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:e("discovery.all_time")})]})]}),h.jsxs("button",{onClick:O,disabled:B,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[h.jsx(Tc,{size:18,className:B?"animate-spin":""}),e(B?"discovery.syncing":"discovery.sync_history")]})]})]}),h.jsx(VL,{onOpenUrl:pe=>window.open(pe,"_blank","noopener,noreferrer"),onCopyText:pe=>{navigator.clipboard.writeText(pe)}})]}),o==="chat"&&h.jsx(yz,{}),o==="transmute"&&h.jsx(bz,{}),o==="engine"&&h.jsx(xL,{}),o==="account"&&h.jsx(jL,{}),o==="logs"&&h.jsx(IL,{initialState:ne}),h.jsx(bL,{isExpanded:Y,onToggle:()=>X(!Y),onNavigate:ve,liftUp:o==="chat"})]}),h.jsx(NL,{signal:N,onClose:()=>A(null)}),h.jsx(AL,{isOpen:$,onClose:()=>G(!1)}),h.jsx(xz,{isOpen:S,onClose:()=>P(!1)})]})})}):h.jsx(dL,{onAuthSuccess:()=>W(),isInitialized:w})}function yi({active:e,icon:t,label:n,onClick:r,collapsed:s}){return h.jsx("button",{onClick:r,title:s?n:"",className:`w-full flex items-center ${s?"justify-center":"gap-3"} px-4 py-3 rounded-xl transition-all ${e?"bg-primary/10 text-primary shadow-sm":"text-fg/60 hover:bg-surface hover:text-fg"}`,children:s?ea.cloneElement(t,{className:e?"text-primary":""}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"min-w-[20px] flex justify-center",children:ea.cloneElement(t,{className:e?"text-primary":""})}),h.jsx(Fe.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:n})]})})}function Sz(){Qe.interceptors.request.use(async e=>{try{const{data:{session:t}}=await oe.auth.getSession();t?.access_token&&(e.headers.Authorization=`Bearer ${t.access_token}`);const n=Rs();n&&(e.headers["x-supabase-url"]=n.url,e.headers["x-supabase-key"]=n.anonKey)}catch(t){console.error("[Axios] Error injecting headers:",t)}return e})}const{slice:jz,forEach:Ez}=[];function Cz(e){return Ez.call(jz.call(arguments,1),t=>{if(t)for(const n in t)e[n]===void 0&&(e[n]=t[n])}),e}function Tz(e){return typeof e!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(e))}const i_=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Nz=function(e,t){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},s=encodeURIComponent(t);let o=`${e}=${s}`;if(r.maxAge>0){const a=r.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");o+=`; Max-Age=${Math.floor(a)}`}if(r.domain){if(!i_.test(r.domain))throw new TypeError("option domain is invalid");o+=`; Domain=${r.domain}`}if(r.path){if(!i_.test(r.path))throw new TypeError("option path is invalid");o+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");o+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(o+="; HttpOnly"),r.secure&&(o+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:o+="; SameSite=Strict";break;case"lax":o+="; SameSite=Lax";break;case"strict":o+="; SameSite=Strict";break;case"none":o+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(o+="; Partitioned"),o},o_={create(e,t,n,r){let s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(s.expires=new Date,s.expires.setTime(s.expires.getTime()+n*60*1e3)),r&&(s.domain=r),document.cookie=Nz(e,t,s)},read(e){const t=`${e}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let s=n[r];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return s.substring(t.length,s.length)}return null},remove(e,t){this.create(e,"",-1,t)}};var Az={name:"cookie",lookup(e){let{lookupCookie:t}=e;if(t&&typeof document<"u")return o_.read(t)||void 0},cacheUserLanguage(e,t){let{lookupCookie:n,cookieMinutes:r,cookieDomain:s,cookieOptions:o}=t;n&&typeof document<"u"&&o_.create(n,e,r,s,o)}},Rz={name:"querystring",lookup(e){let{lookupQuerystring:t}=e,n;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const o=r.substring(1).split("&");for(let a=0;a<o.length;a++){const c=o[a].indexOf("=");c>0&&o[a].substring(0,c)===t&&(n=o[a].substring(c+1))}}return n}},Pz={name:"hash",lookup(e){let{lookupHash:t,lookupFromHashIndex:n}=e,r;if(typeof window<"u"){const{hash:s}=window.location;if(s&&s.length>2){const o=s.substring(1);if(t){const a=o.split("&");for(let c=0;c<a.length;c++){const u=a[c].indexOf("=");u>0&&a[c].substring(0,u)===t&&(r=a[c].substring(u+1))}}if(r)return r;if(!r&&n>-1){const a=s.match(/\/([a-zA-Z-]*)/g);return Array.isArray(a)?a[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let xi=null;const a_=()=>{if(xi!==null)return xi;try{if(xi=typeof window<"u"&&window.localStorage!==null,!xi)return!1;const e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch{xi=!1}return xi};var Oz={name:"localStorage",lookup(e){let{lookupLocalStorage:t}=e;if(t&&a_())return window.localStorage.getItem(t)||void 0},cacheUserLanguage(e,t){let{lookupLocalStorage:n}=t;n&&a_()&&window.localStorage.setItem(n,e)}};let vi=null;const l_=()=>{if(vi!==null)return vi;try{if(vi=typeof window<"u"&&window.sessionStorage!==null,!vi)return!1;const e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch{vi=!1}return vi};var Lz={name:"sessionStorage",lookup(e){let{lookupSessionStorage:t}=e;if(t&&l_())return window.sessionStorage.getItem(t)||void 0},cacheUserLanguage(e,t){let{lookupSessionStorage:n}=t;n&&l_()&&window.sessionStorage.setItem(n,e)}},Iz={name:"navigator",lookup(e){const t=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:s}=navigator;if(n)for(let o=0;o<n.length;o++)t.push(n[o]);r&&t.push(r),s&&t.push(s)}return t.length>0?t:void 0}},Dz={name:"htmlTag",lookup(e){let{htmlTag:t}=e,n;const r=t||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},Mz={name:"path",lookup(e){let{lookupFromPathIndex:t}=e;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof t=="number"?t:0]?.replace("/",""):void 0}},zz={name:"subdomain",lookup(e){let{lookupFromSubdomainIndex:t}=e;const n=typeof t=="number"?t+1:1,r=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};let Yk=!1;try{document.cookie,Yk=!0}catch{}const Qk=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Yk||Qk.splice(1,1);const Fz=()=>({order:Qk,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:e=>e});class Zk{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(t,n)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=t,this.options=Cz(n,this.options||{},Fz()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=s=>s.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(Az),this.addDetector(Rz),this.addDetector(Oz),this.addDetector(Lz),this.addDetector(Iz),this.addDetector(Dz),this.addDetector(Mz),this.addDetector(zz),this.addDetector(Pz)}addDetector(t){return this.detectors[t.name]=t,this}detect(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return t.forEach(r=>{if(this.detectors[r]){let s=this.detectors[r].lookup(this.options);s&&typeof s=="string"&&(s=[s]),s&&(n=n.concat(s))}}),n=n.filter(r=>r!=null&&!Tz(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(t,this.options)}))}}Zk.type="languageDetector";const $z={save:"Save",cancel:"Cancel",loading:"Loading...",error:"Error",success:"Success",settings:"Settings",search:"Search",back:"Back",all:"All",delete:"Delete",update:"Update",edit:"Edit",close:"Close",complete:"Complete",skip:"Skip",begin:"Begin",connection:"Connection",setup:"Setup",project:"Project",account:"Account",logout:"Logout",welcome:"Welcome",dark_mode:"Dark Mode",light_mode:"Light Mode",collapse:"Collapse",just_now:"Just now",enabled:"Enabled",disabled:"Disabled",quick:"Quick (5)",balanced:"Balanced (50)",thorough:"Thorough (200)",resetting:"Resetting...",saving:"Saving...",locale_code:"en-US",categories:{ai_ml:"AI & ML",business:"Business",politics:"Politics",technology:"Technology",finance:"Finance",crypto:"Crypto",science:"Science",other:"Other"}},Uz={discovery:"Discovery",chat:"Chat",transmute:"Transmute",logs:"System Logs",history:"History"},Bz={welcome_title:"Assemble Your Engine",welcome_desc:"Alchemy requires a Supabase essence to store signal fragments and intelligence patterns.",requirements:"Requirements:",project_url:"Supabase Project URL",anon_key:"Anon Public API Key",db_password:"Database Password",project_url_placeholder:"https://xxx.supabase.co or project-id",anon_key_placeholder:"eyJ...",project_id_placeholder:"abcdefghijklm",access_token_placeholder:"sbp_...",begin_init:"BEGIN INITIALIZATION",connect_essence:"CONNECT ESSENCE",credentials_title:"Essence Coordinates",credentials_desc:"Link the alchemist engine to your cloud database",validating:"Validating Link",resonance:"Synchronizing Resonance...",init_schema:"Initialize Schema",schema_desc:"Run database migrations to set up required tables and functions.",project_id:"Project ID",access_token:"Access Token",run_migrations:"RUN MIGRATIONS",running_migrations:"Running Migrations",take_minute:"This may take a minute...",engine_aligned:"Engine Aligned",restarting:"Restarting Alchemist Subsystems...",forge_project:"Forge Project at Supabase",project_id_help:"Found in Supabase Dashboard → Project Settings → General",access_token_help:"Generate at",access_token_link:"supabase.com/dashboard/account/tokens",project_id_required:"Project ID is required",access_token_required:"Access token is required",migration_failed_logs:"Migration failed. Check logs for details.",stream_error:"Failed to read migration stream",back:"BACK",retry:"RETRY"},Vz={title_init:"INITIALIZE MASTER",title_join:"JOIN THE CIRCLE",title_mystic:"MYSTIC ACCESS",title_login:"ALCHEMIST LOGIN",desc_init:"Forge the prime alchemist account",desc_mystic_email:"Enter your essence email",desc_mystic_code:"Transmute the sacred code",desc_login:"Transmute your data into intelligence",first_name:"First Name",last_name:"Last Name",first_name_placeholder:"Zosimos",last_name_placeholder:"Panopolis",email_address:"Email Address",email_placeholder:"alchemist@example.com",complexity_key:"Complexity Key",password_placeholder:"••••••••",init_account:"INITIALIZE ACCOUNT",send_code:"SEND CODE",unseal_engine:"UNSEAL ENGINE",verify_code:"VERIFY CODE",change_email:"Change email address",sign_in_code:"Sign in with Code",sign_in_password:"Sign in with Password",already_alchemist:"Already an Alchemist?",new_to_alchemy:"New to Alchemy?",login_instead:"Login instead",create_account:"Create an account",session_failed:"Failed to create session",invalid_code:"Invalid code"},qz={filters:"Filters",category:"Category",intelligence_score:"Intelligence Score",no_signals_in_category:"No signals in {{category}} yet.",no_categories:"No categories yet.",discovery_hint:"Signals will be organized here once discovered.",loading_signals:"Loading signals...",dismiss_hint:"Dismiss (Not Interested)",signal_count_one:"{{count}} signal",signal_count_other:"{{count}} signals",time_min_ago:"{{count}}m ago",time_hour_ago:"{{count}}h ago",time_day_ago:"{{count}}d ago",add_note_title:"Add Note",target:"Target",note_placeholder:"Enter your thoughts, ideas, or action items regarding this signal...",save_note:"Save Note",view_all_sources:"View all sources",source_count_one:"{{count}} source",source_count_other:"{{count}} sources",source_found_in:"Found in {{count}} different sources",high_confidence:"High confidence - found in {{count}} sources",new_signals:"New Signals",smart_summary:"Smart Summary",entities:"Entities",sources:"Sources",last_sync:"Last Sync",syncnow:"Sync Now",all_time:"All time",checkpoint:"Checkpoint",from:"From",score_high:"HIGH",score_medium:"MEDIUM",score_low:"LOW",sources_count:"{{count}} sources",open_source:"Open",add_note:"Note",boost_topic:"Boost Topic",boosted:"Boosted",dismissed:"Dismissed",remove_favourite:"Remove from favourites",add_favourite:"Add to favourites",sync_history:"Sync History",syncing:"Syncing...",sync_settings:"Sync Settings",discovered:"Discovered",original_source:"Original Source",ai_summary:"AI Summary",full_content:"Full Content",copied:"Copied!",open_link:"Open",detail_title:"Signal Details",sync_from:"Sync From (Optional)",urls_per_sync:"URLs per Sync",sync_from_hint:"Leave empty to sync only new URLs since last sync (incremental). Set a date to process URLs from that point forward.",reset_checkpoint:"Reset Checkpoint",reset_checkpoint_hint:'Clear the sync checkpoint to force a full re-sync from your "Sync From" date',sync_info:'The Alchemist tracks your progress automatically. Use "Sync From" to backfill history or "Reset Checkpoint" to start fresh.',save_settings:"Save Settings",sync_saved:"Sync settings saved successfully",checkpoint_reset:"Checkpoint reset successfully",login_to_save:"Please log in to save settings",login_to_reset:"Please log in to reset checkpoint",status_updated:"Engine status updated to {{status}}",asset_ready:'Asset "{{title}}" is ready!',scanning:"Scanning for new categories and topics...",discovery_complete:"Engine discovery complete!",discovery_failed:"Discovery failed. Check settings.",load_failed:"Failed to load engines",starting_run:"Starting engine run...",run_complete:"Engine run complete! Created: {{title}}",run_started_desktop:"Engine run started on Desktop. Tracking as: {{id}}",run_failed:"Failed to run engine",brief_failed:"Failed to generate production brief",copied_json:"JSON copied to clipboard",json_footer:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",topic:"Topic",pipeline:"Pipeline"},Hz={history:"History",ask_anything:"Ask anything about your browsing history...",sources:"Sources",processing:"Processing your query...",new_chat:"New Chat",no_messages:"No messages yet. Start a conversation!",no_history:"No chat history yet.",title:"Ask Alchemist",desc:"I can help you recall information, summarize topics, and find insights from your browsing history.",thinking:"Exploring memory...",placeholder:"Ask about your history...",error_message:"Sorry, I encountered an error processing your request.",relevant_context:"Relevant Context",match_score:"{{score}}% Match",rag_attribution:"Alchemist used these {{count}} signals to answer",suggestions:{react:"What have I read about React recently?",ai:"Summarize the latest AI news I visited.",finance:"Do I have any notes on Finance?",performance:"Find articles about 'Performance'"}},Kz={engines:"Alchemist Engines",assets:"Generated Assets",newsletter:"Newsletter",thread:"Thread",audio:"Audio",report:"Report",title:"Transmute Engine",desc:"Active Generation Pipelines & Assets",generate:"Generate",processing_desktop:"Processing on Desktop...",ensure_defaults:"Ensure Default Engines",create_engine:"Create Engine",no_assets:"No assets generated yet.",generate_engines:"Generate Engines",new_engine:"New Engine",no_engines:"No Engines Configured",no_engines_desc:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs.",run_engine:"Run Engine",running:"Running...",last_run:"Last Run",never:"Never",schedule:"Schedule",manual:"Manual",topic:"Topic",pipeline:"Pipeline",pause:"Pause",resume:"Resume",view_json:"View Production Brief JSON",json_contract:"Stateless & Self-Contained Contract",json_desc:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",generating_asset:"Generating Asset...",queued_desktop:"Queued for Desktop...",desktop_processing:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished.",unsupported_type:"Unsupported asset type",edit_engine:"Edit Engine",engine_name:"Engine Name",type:"Type",status:"Status",execution_env:"Execution Environment",local_llm:"Local (Alchemy LLM)",desktop_swarm:"RealTimeX Desktop (Agent Swarm)",env_desc_desktop:"Delegates heavy tasks like Audio/Video to the desktop app.",env_desc_local:"Runs simple Markdown tasks directly in Alchemy.",min_score:"Min Score",max_signals:"Max Signals",category_filter:"Category Filter (multi-select)",multi_select_hint:"Hold Cmd/Ctrl to select multiple categories",schedule_hint:"Note: Scheduling is not yet automated",prompt_override:"Custom Prompt Override (optional)",prompt_placeholder:"Override the default prompt for this engine type...",delete_confirm:"Really delete?",confirm:"Confirm"},Wz={title:"Account Configuration",desc:"Manage your Alchemist profile and essence links.",profile:"Profile",security:"Security",supabase:"Supabase",first_name:"First Name",last_name:"Last Name",email_locked:"Email Address (Locked)",sound_effects:"Sound Effects",sound_desc:"Enable audio feedback for sync events and signal discoveries.",sign_out:"Sign Out",logout_desc:"End your current session and return to the login screen.",preserve_profile:"Preserve Profile",security_title:"Update Entropy Key",new_password:"New Password",confirm_password:"Confirm Password",password_mismatch:"Complexity keys do not match.",password_too_short:"Entropy too low. Minimum 8 characters.",password_rotate_success:"Key rotation successful.",rotate_key:"Rotate Key",essence_resonance:"Essence Resonance",byok_desc:"Bring Your Own Keys (BYOK) for intelligence persistence.",established_link:"Established Link",env_notice:"Active from environment variables. UI override enabled.",realign_link:"Realign Link",sever_link:"Sever Link",sever_confirm:"Sever connection to this essence? This will reset local resonance.",anon_secret_fragment:"Anon Secret Fragment",no_resonance:"No Essence Resonance",no_resonance_desc:"The Alchemist requires a cloud core to store intelligence fragments.",initiate_link:"Initiate Link",test_connection:"Test Connection"},Gz={title:"System Logs",desc:"Detailed history of sync runs, sources, and URL processing",blacklist_suggestion:"Potential Blacklist",blacklist_desc:"Candidates for blocking",recent_errors:"Recent Errors",errors_desc:"Failed URL processes",total_signals:"Total Signals",signals_desc:"Successfully mined",blacklist_modal_title:"Blacklist Suggestions",blacklist_modal_desc:"Review domains suggested for blacklisting based on low scores.",no_suggestions:"No suggestions right now",quality_good:"Your signal quality looks good!",signals_count:"{{count}} signals",avg_score:"Avg Score: {{score}}",low_quality:"Consistently Low Quality",repetitive:"Repetitive Pattern",blacklist_domain:"Blacklist Domain",errors_modal_title:"Recent Errors",errors_modal_desc:"Log of recent failures and issues.",no_recent_errors:"No recent errors found.",signals_modal_title:"Found Signals",signals_modal_desc:"Browse and manage your mined signals history.",search_placeholder:"Search signals...",any_score:"Any Score",high_score:"High (80%+)",medium_score:"Medium (50-79%)",low_score:"Low (<50%)",all_categories:"All Categories",page_x:"Page {{page}}"},Jz={title:"Alchemist Engine",live:"LIVE",clear:"Clear",idle:"Idle. Awaiting signal mining events...",run_completed:"Mining Run Completed",signals:"Signals",urls:"URLs",skipped:"Skipped",failed_to_process:"{{count}} URLs failed to process",view_logs:"View Logs",hide_details:"Hide Details",view_details:"View Details",engine_log:"Live Engine Log",state_reading:"Reading",state_thinking:"Thinking",state_signal:"Signal",state_skipped:"Skipped",state_error:"Error",state_completed:"Completed",msg_reading:"Reading content from: {{url}}",msg_thinking:"Analyzing relevance of: {{title}}",msg_found_signal:"Found signal: {{summary}} ({{score}}%)",msg_low_signal:"Low signal stored for review ({{score}}%): {{title}}",msg_failed:"Analysis failed for {{title}}: {{error}}",msg_sync_completed:"Sync completed: {{signals}} signals found, {{skipped}} skipped, {{errors}} errors"},Xz={switch_light:"Switch to Light Mode",switch_dark:"Switch to Dark Mode",view_changelog:"View Changelog",release_notes:"Release Notes",changelog_error:"Failed to load changelog."},Yz={title:"Signal Pulse",mining:"Mining",standing_by:"Standing by",idle:"Idle",tracked:"Signals tracked",avg_score:"Average score",top_signal:"Top signal",latest:"Latest",awaiting:"Awaiting mining",no_signals:"No signals yet"},Qz={title:"Intelligence Engine",subtitle:"Fine-tune the Alchemist's cognitive parameters and provider links.",configuration:"AI Configuration",test_connection:"Test Connection",save_config:"Save Configuration",llm_provider:"LLM Provider",embedding_provider:"Embedding Provider",sdk_connected:"SDK Connected",sdk_not_available:"SDK Not Available",provider:"Provider",intelligence_model:"Intelligence Model",embedding_model:"Embedding Model",loading_providers:"Loading providers...",sdk_info_success:"✓ Using RealTimeX configured provider",sdk_info_fail:"⚠️ RealTimeX SDK not detected. Configure in RealTimeX Desktop.",embedding_info_success:"✓ Embeddings are generated using your RealTimeX configured provider",embedding_info_fail:"⚠️ RealTimeX SDK not detected. Configure providers in RealTimeX Desktop.",persona_title:"Persona Memory",save_memory:"Save Memory",interests_title:"Active Interests",interests_priority:"High Priority",interests_desc:"The Alchemist prioritizes content matching these topics. Updated automatically based on Favorites & Boosts.",interests_placeholder:"e.g. User focuses on React performance, Rust backend systems, and AI Agent architecture...",antipatterns_title:"Anti-Patterns",antipatterns_priority:"Avoid",antipatterns_desc:"The Alchemist filters out or scores down content matching these patterns. Updated via Dismissals.",antipatterns_placeholder:"e.g. Dislikes marketing fluff, generic listicles, and crypto hype...",browser_sources:"Browser History Sources",save_browser:"Save Browser Sources",blacklist_title:"Blacklist Domains",blacklist_desc:"URLs containing these patterns will be skipped during mining. Enter one pattern per line.",blacklist_label:"Domain Patterns (one per line)",blacklist_placeholder:`google.com/search
134
+ ${n("shell.changelog_error")}`)}finally{a(!1)}};return h.jsx(Pt,{children:e&&h.jsxs(h.Fragment,{children:[h.jsx(Fe.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:t,className:"fixed inset-0 bg-black/60 backdrop-blur-sm z-50"}),h.jsx(Fe.div,{initial:{opacity:0,scale:.95,y:20},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.95,y:20},transition:{type:"spring",damping:25,stiffness:300},className:"fixed inset-0 z-50 flex items-center justify-center p-4 pointer-events-none",children:h.jsxs("div",{className:"glass w-full max-w-3xl max-h-[80vh] overflow-hidden pointer-events-auto shadow-2xl",children:[h.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx(u_,{size:24,className:"text-primary"}),h.jsx("h2",{className:"text-xl font-bold",children:n("shell.release_notes")})]}),h.jsx("button",{onClick:t,className:"p-2 hover:bg-surface rounded-lg transition-colors",children:h.jsx(Cn,{size:20,className:"text-fg/60"})})]}),h.jsx("div",{className:"p-6 overflow-y-auto custom-scrollbar max-h-[calc(80vh-88px)]",children:o?h.jsx("div",{className:"flex items-center justify-center py-12",children:h.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-primary border-t-transparent"})}):h.jsx(Wp,{components:{h1:({children:u})=>h.jsx("h1",{className:"text-2xl font-bold text-fg mb-6 mt-0",children:u}),h2:({children:u})=>h.jsx("h2",{className:"text-xl font-bold text-fg mt-8 mb-3 pb-2 border-b border-border first:mt-0",children:u}),h3:({children:u})=>h.jsx("h3",{className:"text-lg font-bold text-primary mt-6 mb-2",children:u}),p:({children:u})=>h.jsx("p",{className:"text-sm text-fg/70 mb-3 leading-relaxed",children:u}),ul:({children:u})=>h.jsx("ul",{className:"list-none space-y-1 mb-4 ml-0",children:u}),li:({children:u})=>h.jsx("li",{className:"text-sm text-fg/80 ml-4 mb-1 before:content-['•'] before:mr-2 before:text-primary",children:u}),a:({href:u,children:f})=>h.jsx("a",{href:u,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:text-primary/80 underline transition-colors",children:f}),code:({children:u})=>h.jsx("code",{className:"bg-surface/50 text-accent px-1.5 py-0.5 rounded text-xs font-mono border border-border",children:u}),strong:({children:u})=>h.jsx("strong",{className:"font-bold text-fg",children:u})},children:r})})]})})]})})}function vz({asset:e,onClose:t}){const{t:n}=Ze(),r=()=>{e.content&&navigator.clipboard.writeText(e.content)},s=()=>{if(!e.content)return;const o=new Blob([e.content],{type:"text/markdown"}),a=URL.createObjectURL(o),c=document.createElement("a");c.href=a,c.download=`${e.title.replace(/[^a-z0-9]/gi,"_").toLowerCase()}.md`,document.body.appendChild(c),c.click(),document.body.removeChild(c),URL.revokeObjectURL(a)};return h.jsx(Pt,{children:e&&h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 rounded-lg bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400",children:e.type==="audio"?h.jsx($h,{className:"w-5 h-5"}):h.jsx(Oi,{className:"w-5 h-5"})}),h.jsxs("div",{children:[h.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),h.jsxs("p",{className:"text-xs text-gray-500",children:[new Date(e.created_at).toLocaleString()," • ",n("discovery.sources_count",{count:e.metadata?.source_signal_count||0})]})]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:r,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Copy Content",children:h.jsx(If,{className:"w-4 h-4"})}),h.jsx("button",{onClick:s,className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"Download File",children:h.jsx(zh,{className:"w-4 h-4"})}),h.jsx("div",{className:"w-px h-6 bg-gray-200 dark:bg-gray-700 mx-1"}),h.jsx("button",{onClick:t,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:h.jsx(Cn,{className:"w-5 h-5"})})]})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-6 bg-white dark:bg-gray-950",children:e.status&&e.status!=="completed"?h.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[h.jsx(Rt,{className:"w-12 h-12 animate-spin text-purple-500"}),h.jsxs("div",{className:"text-center",children:[h.jsx("h4",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e.status==="processing"?n("transmute.generating_asset"):n("transmute.queued_desktop")}),h.jsx("p",{className:"text-sm text-gray-500 max-w-xs mt-1",children:n("transmute.desktop_processing")})]})]}):e.type==="markdown"?h.jsx("div",{className:"prose dark:prose-invert max-w-none",children:h.jsx(Wp,{children:e.content||""})}):e.type==="audio"?h.jsxs("div",{className:"flex flex-col items-center justify-center h-64 gap-4",children:[h.jsx("div",{className:"w-16 h-16 rounded-full bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center animate-pulse",children:h.jsx($h,{className:"w-8 h-8 text-purple-600 dark:text-purple-400"})}),h.jsx("p",{className:"text-gray-500",children:n("transmute.unsupported_type")}),h.jsxs("audio",{controls:!0,className:"w-full max-w-md mt-4",children:[h.jsx("source",{src:e.content||"",type:"audio/mpeg"}),"Your browser does not support the audio element."]})]}):h.jsx("div",{className:"text-gray-500 text-center py-10",children:"Unsupported asset type"})})]})})})}function s_({engine:e,onClose:t,onSave:n,onDelete:r}){const{t:s}=Ze(),{showToast:o}=Kc(),[a,c]=R.useState({title:"",type:"newsletter",status:"active",config:{schedule:"",min_score:70,categories:[],custom_prompt:"",max_signals:10,execution_mode:"local"}}),[u,f]=R.useState(!1);R.useEffect(()=>{e&&c({title:e.title,type:e.type,status:e.status,config:{schedule:e.config.schedule||"",min_score:e.config.filters?.min_score||70,categories:Array.isArray(e.config.category)?e.config.category:e.config.category?[e.config.category]:[],custom_prompt:e.config.custom_prompt||"",max_signals:e.config.max_signals||10,execution_mode:e.config.execution_mode||"local"}})},[e]);const p=async()=>{try{const v={title:a.title,type:a.type,status:a.status,config:{schedule:a.config.schedule,filters:{min_score:a.config.min_score,category:a.config.category},custom_prompt:a.config.custom_prompt,max_signals:a.config.max_signals,execution_mode:a.config.execution_mode}};if(e){const{data:b,error:w}=await oe.from("engines").update(v).eq("id",e.id).select().single();if(w)throw w;n(b),o("Engine updated successfully","success")}else{const{data:{user:b}}=await oe.auth.getUser();if(!b)throw new Error("Not authenticated");const{data:w,error:k}=await oe.from("engines").insert({...v,user_id:b.id}).select().single();if(k)throw k;n(w),o("Engine created successfully","success")}t()}catch(v){console.error("Save error:",v),o(v.message||"Failed to save engine","error")}},g=async()=>{if(!(!e||!r))try{const{error:v}=await oe.from("engines").delete().eq("id",e.id);if(v)throw v;r(e.id),o("Engine deleted","success"),t()}catch(v){o(v.message||"Failed to delete engine","error")}},y=()=>{f(!1),t()};return!e&&!t?null:h.jsx(Pt,{children:h.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-2xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800",children:[h.jsx("h3",{className:"text-lg font-semibold text-gray-900 dark:text-gray-100",children:s(e?"transmute.edit_engine":"transmute.create_engine")}),h.jsx("button",{onClick:y,className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:h.jsx(Cn,{className:"w-5 h-5"})})]}),h.jsxs("div",{className:"flex-1 overflow-y-auto p-6 space-y-6",children:[h.jsxs("div",{className:"space-y-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.engine_name")}),h.jsx("input",{type:"text",value:a.title,onChange:v=>c({...a,title:v.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 focus:ring-2 focus:ring-purple-500 focus:border-transparent",placeholder:"e.g., Daily Tech Brief"})]}),h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.type")}),h.jsxs("select",{value:a.type,onChange:v=>c({...a,type:v.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[h.jsx("option",{value:"newsletter",children:s("transmute.newsletter")}),h.jsx("option",{value:"thread",children:s("transmute.thread")}),h.jsx("option",{value:"audio",children:"Audio Brief"}),h.jsx("option",{value:"report",children:"Report"})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.status")}),h.jsxs("select",{value:a.status,onChange:v=>c({...a,status:v.target.value}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[h.jsx("option",{value:"active",children:s("common.status_active")}),h.jsx("option",{value:"paused",children:s("common.status_paused")}),h.jsx("option",{value:"draft",children:"Draft"})]})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.execution_env")}),h.jsxs("select",{value:a.config.execution_mode,onChange:v=>c({...a,config:{...a.config,execution_mode:v.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",children:[h.jsx("option",{value:"local",children:s("transmute.local_llm")}),h.jsx("option",{value:"desktop",children:s("transmute.desktop_swarm")})]}),h.jsx("p",{className:"text-[10px] text-gray-500 mt-1",children:a.config.execution_mode==="desktop"?s("transmute.env_desc_desktop"):s("transmute.env_desc_local")})]})]}),h.jsxs("div",{className:"space-y-4",children:[h.jsx("h4",{className:"font-medium text-gray-900 dark:text-gray-100",children:"Signal Filters"}),h.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.min_score")}),h.jsx("input",{type:"number",min:"0",max:"100",value:a.config.min_score,onChange:v=>c({...a,config:{...a.config,min_score:parseInt(v.target.value)||0}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.max_signals")}),h.jsx("input",{type:"number",min:"1",max:"50",value:a.config.max_signals,onChange:v=>c({...a,config:{...a.config,max_signals:parseInt(v.target.value)||10}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100"})]})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.category_filter")}),h.jsxs("select",{multiple:!0,value:a.config.categories,onChange:v=>{const b=Array.from(v.target.selectedOptions,w=>w.value);c({...a,config:{...a.config,categories:b}})},className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 min-h-[100px]",children:[h.jsx("option",{value:"AI & ML",children:"AI & ML"}),h.jsx("option",{value:"Technology",children:"Technology"}),h.jsx("option",{value:"Business",children:"Business"}),h.jsx("option",{value:"Finance",children:"Finance"}),h.jsx("option",{value:"Science",children:"Science"}),h.jsx("option",{value:"Politics",children:"Politics"})]}),h.jsx("p",{className:"text-xs text-gray-500 mt-1",children:s("transmute.multi_select_hint")})]})]}),h.jsxs("div",{children:[h.jsxs("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:[s("transmute.schedule")," (",s("common.optional"),")"]}),h.jsx("input",{type:"text",value:a.config.schedule,onChange:v=>c({...a,config:{...a.config,schedule:v.target.value}}),className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100",placeholder:"e.g., Daily @ 9am, Manual"}),h.jsx("p",{className:"text-xs text-gray-500 mt-1",children:s("transmute.schedule_hint")})]}),h.jsxs("div",{children:[h.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:s("transmute.prompt_override")}),h.jsx("textarea",{value:a.config.custom_prompt,onChange:v=>c({...a,config:{...a.config,custom_prompt:v.target.value}}),rows:4,className:"w-full px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 resize-none",placeholder:s("transmute.prompt_placeholder")})]})]}),h.jsxs("div",{className:"flex items-center justify-between p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50",children:[e&&r?u?h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("span",{className:"text-sm text-red-600 font-medium",children:s("transmute.delete_confirm")}),h.jsx("button",{onClick:g,className:"px-3 py-1.5 bg-red-600 text-white text-xs rounded-lg hover:bg-red-700 transition-colors",children:s("transmute.confirm")}),h.jsx("button",{onClick:()=>f(!1),className:"px-3 py-1.5 text-gray-500 hover:text-gray-700 text-xs rounded-lg",children:s("common.cancel")})]}):h.jsxs("button",{onClick:()=>f(!0),className:"flex items-center gap-2 px-4 py-2 text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:[h.jsx(zf,{className:"w-4 h-4"}),s("common.delete")]}):h.jsx("div",{}),h.jsxs("div",{className:"flex gap-2",children:[h.jsx("button",{onClick:y,className:"px-4 py-2 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:"Cancel"}),h.jsxs("button",{onClick:p,className:"flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors",children:[h.jsx(_r,{className:"w-4 h-4"}),"Save"]})]})]})]})})})}const _z=({engine:e,onRun:t,onEdit:n,onToggle:r,onViewBrief:s,isLoading:o})=>{const{t:a}=Ze(),c=!!e.config.tag,u={newsletter:c?h.jsx(Df,{className:"w-5 h-5 text-blue-500"}):h.jsx(Oi,{className:"w-5 h-5 text-emerald-500"}),thread:h.jsx(nn,{className:"w-5 h-5 text-blue-500"}),audio:h.jsx($h,{className:"w-5 h-5 text-purple-500"}),report:h.jsx(ic,{className:"w-5 h-5 text-orange-500"})};return h.jsxs(Fe.div,{layout:!0,initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},className:`p-5 rounded-2xl border ${e.status==="active"?"bg-white dark:bg-gray-800 border-gray-200 dark:border-gray-700 shadow-sm":"bg-gray-50 dark:bg-gray-900 border-dashed border-gray-300 dark:border-gray-700 opacity-75"} transition-all hover:shadow-md group`,children:[h.jsxs("div",{className:"flex justify-between items-start mb-4",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 rounded-xl bg-gray-100 dark:bg-gray-800",children:u[e.type]||h.jsx(Oi,{className:"w-5 h-5"})}),h.jsxs("div",{children:[h.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e.title}),h.jsxs("p",{className:"text-xs text-gray-500 capitalize",children:[c?a("transmute.topic"):a(`transmute.${e.type}`,e.type)," ",a("transmute.pipeline")]})]})]}),h.jsxs("div",{className:"flex gap-1",children:[h.jsx("button",{onClick:()=>r(e.id,e.status),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:e.status==="active"?h.jsx(Pj,{className:"w-4 h-4"}):h.jsx(Wy,{className:"w-4 h-4"})}),h.jsx("button",{onClick:()=>s(e.id),title:a("transmute.view_json"),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:h.jsx(f_,{className:"w-4 h-4"})}),h.jsx("button",{onClick:()=>n(e.id),className:"p-1.5 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors",children:h.jsx(ic,{className:"w-4 h-4"})})]})]}),h.jsxs("div",{className:"space-y-2 mb-4",children:[h.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[h.jsx("span",{children:a("transmute.last_run")}),h.jsx("span",{children:e.last_run_at?new Date(e.last_run_at).toLocaleDateString(a("common.locale_code")):a("transmute.never")})]}),h.jsxs("div",{className:"text-xs text-gray-500 flex justify-between",children:[h.jsx("span",{children:a("transmute.schedule")}),h.jsx("span",{children:e.config.schedule||a("transmute.manual")})]})]}),h.jsxs("button",{onClick:()=>t(e.id),disabled:o||e.status!=="active",className:"w-full flex items-center justify-center gap-2 py-2 rounded-xl bg-gray-900 dark:bg-white text-white dark:text-gray-900 font-medium hover:opacity-90 disabled:opacity-50 transition-all text-sm",children:[o?h.jsx(Rt,{className:"w-4 h-4 animate-spin"}):h.jsx(Wy,{className:"w-4 h-4"}),a(o?"transmute.running":"transmute.run_engine")]})]})};function bz(){const{t:e}=Ze(),[t,n]=R.useState([]),[r,s]=R.useState(!0),[o,a]=R.useState(new Set),[c,u]=R.useState(null),[f,p]=R.useState(null),[g,y]=R.useState(!1),[v,b]=R.useState(null),[w,k]=R.useState(!1),[j,C]=R.useState(!1),{showToast:S}=Kc();R.useEffect(()=>{(async()=>N())();const K=oe.channel("asset-updates").on("postgres_changes",{event:"UPDATE",schema:"public",table:"assets"},te=>{const ne=te.new;u(J=>J?.id===ne.id?ne:J),ne.status==="completed"&&te.old.status!=="completed"&&S(e("transmute.asset_ready",{title:ne.title}),"success")}).subscribe();return()=>{oe.removeChannel(K)}},[]);const P=async()=>{if(!j)try{C(!0),S(e("transmute.scanning"),"info");const{data:{session:H}}=await oe.auth.getSession(),K=Rs(),te={"Content-Type":"application/json","x-user-id":H?.user?.id||""};if(H?.access_token&&(te.Authorization=`Bearer ${H.access_token}`),K&&(te["x-supabase-url"]=K.url,te["x-supabase-key"]=K.anonKey),!(await fetch("/api/engines/ensure-defaults",{method:"POST",headers:te})).ok)throw new Error("Failed to generate engines");S(e("transmute.discovery_complete"),"success"),await N()}catch(H){console.error("Failed to generate engines:",H),S(e("transmute.discovery_failed"),"error")}finally{C(!1)}},N=async()=>{try{s(!0);const{data:{user:H}}=await oe.auth.getUser();if(!H)return;const{data:K,error:te}=await oe.from("engines").select("*").eq("user_id",H.id).order("created_at",{ascending:!1});if(te)throw te;n(K)}catch(H){console.error("Error fetching engines:",H),S(e("transmute.load_failed"),"error")}finally{s(!1)}},A=async H=>{if(!o.has(H))try{a(D=>new Set(D).add(H)),S(e("transmute.starting_run"),"info");const{data:{session:K}}=await oe.auth.getSession(),te=K?.access_token,ne=Rs(),J={"Content-Type":"application/json","x-user-id":K?.user?.id||""};te&&(J.Authorization=`Bearer ${te}`),ne&&(J["x-supabase-url"]=ne.url,J["x-supabase-key"]=ne.anonKey);const le=await fetch(`/api/engines/${H}/run`,{method:"POST",headers:J});if(!le.ok){const D=await le.json();throw new Error(D.error||"Run failed")}const T=await le.json();T.status==="completed"?S(e("transmute.run_complete",{title:T.title}),"success"):S(e("transmute.run_started_desktop",{id:T.id}),"info"),u(T),n(D=>D.map(W=>W.id===H?{...W,last_run_at:new Date().toISOString()}:W))}catch(K){console.error("Engine run error:",K),S(K.message||e("transmute.run_failed"),"error")}finally{a(K=>{const te=new Set(K);return te.delete(H),te})}},$=async H=>{try{y(!0);const{data:{session:K}}=await oe.auth.getSession(),te=Rs(),ne={"Content-Type":"application/json","x-user-id":K?.user?.id||""};K?.access_token&&(ne.Authorization=`Bearer ${K.access_token}`),te&&(ne["x-supabase-url"]=te.url,ne["x-supabase-key"]=te.anonKey);const J=await fetch(`/api/engines/${H}/brief`,{headers:ne});if(!J.ok)throw new Error("Failed to fetch brief");const le=await J.json();p(le)}catch{S(e("transmute.brief_failed"),"error")}finally{y(!1)}},G=async(H,K)=>{const te=K==="active"?"paused":"active";n(ne=>ne.map(J=>J.id===H?{...J,status:te}:J));try{const{error:ne}=await oe.from("engines").update({status:te}).eq("id",H);if(ne)throw ne;S(e("transmute.status_updated",{status:te}),"success")}catch{n(J=>J.map(le=>le.id===H?{...le,status:K}:le)),S(e("common.error"),"error")}},B=()=>{k(!0)},L=H=>{const K=t.find(te=>te.id===H);K&&b(K)},Y=H=>{n(K=>K.find(ne=>ne.id===H.id)?K.map(ne=>ne.id===H.id?H:ne):[H,...K])},X=H=>{n(K=>K.filter(te=>te.id!==H))},de=()=>{b(null),k(!1)};return h.jsxs("div",{className:"h-full flex flex-col bg-gray-50/50 dark:bg-[#0A0A0A]",children:[h.jsx("div",{className:"flex-none p-6 border-b border-gray-200 dark:border-gray-800 bg-white/50 dark:bg-gray-900/50 backdrop-blur-sm z-10 sticky top-0",children:h.jsxs("div",{className:"flex justify-between items-center max-w-7xl mx-auto w-full",children:[h.jsxs("div",{children:[h.jsx("h2",{className:"text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-purple-500 to-blue-500",children:e("transmute.title")}),h.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400 mt-1",children:e("transmute.desc")})]}),h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsxs("button",{onClick:P,disabled:j,className:"flex items-center gap-2 px-4 py-2 bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 rounded-xl font-medium hover:bg-purple-100 dark:hover:bg-purple-900/40 transition-all border border-purple-200 dark:border-purple-800 disabled:opacity-50",children:[j?h.jsx(Rt,{className:"w-4 h-4 animate-spin"}):h.jsx(nn,{className:"w-4 h-4"}),e("transmute.generate_engines")]}),h.jsxs("button",{onClick:B,className:"flex items-center gap-2 px-4 py-2 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-xl font-medium hover:opacity-90 transition-opacity shadow-lg shadow-purple-500/10",children:[h.jsx(Mf,{className:"w-4 h-4"}),e("transmute.new_engine")]})]})]})}),h.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:h.jsx("div",{className:"max-w-7xl mx-auto w-full",children:r?h.jsx("div",{className:"flex items-center justify-center h-64",children:h.jsx(Rt,{className:"w-8 h-8 animate-spin text-purple-500"})}):t.length===0?h.jsxs("div",{className:"flex flex-col items-center justify-center h-96 text-center",children:[h.jsx("div",{className:"w-16 h-16 rounded-2xl bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4",children:h.jsx(nn,{className:"w-8 h-8 text-gray-400"})}),h.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-gray-100",children:e("transmute.no_engines")}),h.jsx("p",{className:"text-gray-500 max-w-sm mt-2 mb-6",children:e("transmute.no_engines_desc")}),h.jsx("button",{onClick:B,className:"px-6 py-2.5 rounded-xl border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:e("transmute.create_engine")})]}):h.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.jsx(Pt,{children:t.map(H=>h.jsx(_z,{engine:H,onRun:A,onEdit:L,onToggle:G,onViewBrief:$,isLoading:o.has(H.id)},H.id))})})})}),h.jsx(Pt,{children:f&&h.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center p-4 bg-black/60 backdrop-blur-md",children:h.jsxs(Fe.div,{initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},exit:{opacity:0,scale:.95},className:"bg-white dark:bg-gray-900 rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden border border-gray-200 dark:border-gray-700",children:[h.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-800 bg-gray-50/50 dark:bg-gray-800/50",children:[h.jsxs("div",{className:"flex items-center gap-3",children:[h.jsx("div",{className:"p-2 rounded-lg bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400",children:h.jsx(f_,{className:"w-5 h-5"})}),h.jsxs("div",{children:[h.jsx("h3",{className:"font-semibold text-gray-900 dark:text-gray-100",children:e("transmute.view_json")}),h.jsx("p",{className:"text-xs text-gray-500",children:e("transmute.json_contract")})]})]}),h.jsxs("div",{className:"flex items-center gap-2",children:[h.jsx("button",{onClick:()=>{navigator.clipboard.writeText(JSON.stringify(f,null,2)),S(e("transmute.copied_json"),"info")},className:"p-2 text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",children:h.jsx(If,{className:"w-4 h-4"})}),h.jsx("button",{onClick:()=>p(null),className:"p-2 text-gray-500 hover:text-red-500 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors",children:h.jsx(Cn,{className:"w-5 h-5"})})]})]}),h.jsx("div",{className:"flex-1 overflow-y-auto p-4 bg-[#0D1117] font-mono text-sm",children:h.jsx("pre",{className:"text-blue-300",children:JSON.stringify(f,null,2)})}),h.jsx("div",{className:"p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800/50 text-[10px] text-gray-500 text-center",children:e("transmute.json_footer")})]})})}),g&&h.jsx("div",{className:"fixed inset-0 z-[70] flex items-center justify-center bg-black/20 backdrop-blur-sm",children:h.jsx(Rt,{className:"w-10 h-10 animate-spin text-white"})}),h.jsx(vz,{asset:c,onClose:()=>u(null)}),v&&h.jsx(s_,{engine:v,onClose:de,onSave:Y,onDelete:X}),w&&h.jsx(s_,{engine:null,onClose:de,onSave:Y})]})}class wz{audioContext=null;enabled=!0;constructor(){}getAudioContext(){return this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext)),this.audioContext}setEnabled(t){this.enabled=t}isEnabled(){return this.enabled}playTone(t,n,r=.3){if(this.enabled)try{const s=this.getAudioContext(),o=s.createOscillator(),a=s.createGain();o.connect(a),a.connect(s.destination),o.frequency.value=t,o.type="sine",a.gain.setValueAtTime(r,s.currentTime),a.gain.exponentialRampToValueAtTime(.01,s.currentTime+n),o.start(s.currentTime),o.stop(s.currentTime+n)}catch(s){console.warn("[Sound] Failed to play tone:",s)}}playSequence(t,n=.3){if(!this.enabled)return;let r=0;t.forEach(s=>{setTimeout(()=>{this.playTone(s.freq,s.duration,n)},r),r+=s.delay})}syncStart(){this.playSequence([{freq:261.63,duration:.15,delay:0},{freq:329.63,duration:.15,delay:100},{freq:392,duration:.2,delay:100}],.2)}signalFound(){this.playSequence([{freq:392,duration:.1,delay:0},{freq:523.25,duration:.15,delay:80}],.25)}syncComplete(){this.playSequence([{freq:261.63,duration:.12,delay:0},{freq:329.63,duration:.12,delay:80},{freq:392,duration:.12,delay:80},{freq:523.25,duration:.2,delay:80}],.2)}error(){this.playSequence([{freq:329.63,duration:.15,delay:0},{freq:261.63,duration:.2,delay:100}],.3)}click(){this.playTone(440,.05,.15)}}const zo=new wz;function kz(){const{t:e}=Ze(),[t,n]=R.useState([]),[r,s]=R.useState([]),[o,a]=R.useState("discovery"),[c,u]=R.useState(!1),[f,p]=R.useState(null),[g,y]=R.useState(!0),[v,b]=R.useState(!pv),[w,k]=R.useState(!0),[j,C]=R.useState(!1),[S,P]=R.useState(!1),[N,A]=R.useState(null),[$,G]=R.useState(!1),[B,L]=R.useState(!1),[Y,X]=R.useState(!1),[de,H]=R.useState(!0),[K,te]=R.useState(()=>localStorage.getItem("theme")||"dark"),[ne,J]=R.useState(null),le=R.useRef(null);R.useMemo(()=>{const pe=r.length;let ge=0,Te=0,fe=null;for(const _t of r){ge+=_t.score,_t.score>Te&&(Te=_t.score);const Yn=new Date(_t.date);(!fe||Yn>new Date(fe.date))&&(fe=_t)}const $e=pe?Math.round(ge/pe):0,rt=fe?new Date(fe.date):null;return{total:pe,average:$e,top:Te,latestTimestamp:rt,latestTitle:fe?.title??fe?.category??null}},[r]),R.useEffect(()=>{(async()=>{if(!pv){b(!0),y(!1);return}try{const{data:Te,error:fe}=await oe.from("init_state").select("is_initialized").single();fe?(console.warn("[App] Init check error (might be fresh DB):",fe),fe.code==="42P01"&&k(!1)):k(Te.is_initialized>0);const{data:{session:$e}}=await oe.auth.getSession();p($e?.user??null)}catch(Te){console.error("[App] Status check failed:",Te)}finally{y(!1)}})();const{data:{subscription:ge}}=oe.auth.onAuthStateChange((Te,fe)=>{p(fe?.user??null)});return()=>ge.unsubscribe()},[]),R.useEffect(()=>{document.documentElement.setAttribute("data-theme",K),localStorage.setItem("theme",K)},[K]);const[T,D]=R.useState({});R.useEffect(()=>{(async()=>{if(!f)return;const{data:ge}=await oe.from("alchemy_settings").select("sync_start_date, last_sync_checkpoint").eq("user_id",f.id).maybeSingle();ge&&D(ge)})()},[f,$]),R.useEffect(()=>{if(!f)return;(async()=>{const{data:Te}=await oe.from("alchemy_settings").select("sound_enabled").eq("user_id",f.id).maybeSingle();if(Te){const fe=Te.sound_enabled??!0;H(fe),zo.setEnabled(fe)}})();const ge=oe.channel("processing_events").on("postgres_changes",{event:"INSERT",schema:"public",table:"processing_events",filter:`user_id=eq.${f.id}`},Te=>{const fe=Te.new;fe.agent_state==="Mining"&&!B&&(L(!0),X(!0),de&&zo.syncStart()),fe.agent_state==="Signal"&&de&&zo.signalFound(),fe.agent_state==="Completed"&&(L(!1),de&&(fe.metadata?.errors>0?zo.error():zo.syncComplete()),setTimeout(()=>{X(!1)},5e3),W())}).subscribe();return()=>{oe.removeChannel(ge)}},[f,B,de]),R.useEffect(()=>{const pe=new EventSource("/events");return pe.onmessage=ge=>{const Te=JSON.parse(ge.data);Te.type==="history"?n(fe=>[...Te.data,...fe].slice(0,100)):n(fe=>[Te,...fe].slice(0,100))},W(),()=>pe.close()},[f]),R.useEffect(()=>{le.current&&le.current.scrollIntoView({behavior:"smooth"})},[t]);const W=async()=>{try{if(f){const{data:ge,error:Te}=await oe.from("signals").select("*").order("created_at",{ascending:!1});if(!Te&&ge){s(ge.map(fe=>({id:fe.id,title:fe.title,score:fe.score,summary:fe.summary,date:fe.created_at,category:fe.category,entities:fe.entities})));return}}const pe=await Qe.get("/api/signals");s(pe.data)}catch(pe){console.error("Failed to fetch signals",pe)}},O=async()=>{u(!0);try{await Qe.post("/api/mine"),W()}catch(pe){console.error("Mining failed:",pe)}finally{u(!1)}},ve=(pe,ge)=>{pe==="logs"?(J(ge),a("logs")):a(pe)};return g?h.jsx("div",{className:"flex items-center justify-center h-screen bg-bg",children:h.jsx("div",{className:"w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin"})}):v?h.jsx($w,{onComplete:()=>b(!1)}):f?h.jsx(mL,{children:h.jsx(vL,{children:h.jsxs("div",{className:"flex h-screen w-screen overflow-hidden bg-bg text-fg",children:[h.jsxs(Fe.aside,{animate:{width:j?72:240},className:"glass m-4 mr-0 flex flex-col relative",children:[h.jsxs("div",{className:`px-4 py-3 pb-4 flex items-center gap-3 ${j?"justify-center":""}`,children:[h.jsx("div",{className:"w-10 h-10 min-w-[40px] bg-gradient-to-br from-primary to-accent rounded-xl flex items-center justify-center shadow-lg glow-primary",children:h.jsx(nn,{className:"text-white fill-current",size:24})}),!j&&h.jsx(Fe.h1,{initial:{opacity:0},animate:{opacity:1},className:"text-xl font-bold tracking-tight",children:"Alchemist"})]}),h.jsxs("nav",{className:"flex-1 flex flex-col gap-1 px-3",children:[h.jsx(yi,{active:o==="discovery",onClick:()=>a("discovery"),icon:h.jsx(Ej,{size:20}),label:e("tabs.discovery"),collapsed:j}),h.jsx(yi,{active:o==="chat",onClick:()=>a("chat"),icon:h.jsx(Fh,{size:20}),label:e("tabs.chat"),collapsed:j}),h.jsx(yi,{active:o==="transmute",onClick:()=>a("transmute"),icon:h.jsx(nn,{size:20}),label:e("tabs.transmute"),collapsed:j}),h.jsx(yi,{active:o==="engine",onClick:()=>a("engine"),icon:h.jsx(ic,{size:20}),label:e("common.settings"),collapsed:j}),h.jsx(yi,{active:o==="logs",onClick:()=>a("logs"),icon:h.jsx(oc,{size:20}),label:e("tabs.logs"),collapsed:j}),h.jsx(yi,{active:o==="account",onClick:()=>a("account"),icon:h.jsx(Nc,{size:20}),label:e("common.account"),collapsed:j})]}),h.jsx("div",{className:"px-3 pb-2 border-t border-white/5 pt-4 mt-2 relative z-[100]",children:h.jsx("div",{className:j?"flex justify-center":"px-1",children:h.jsx(Np,{collapsed:j})})}),h.jsx("div",{className:"px-3 pb-2",children:h.jsxs("button",{onClick:()=>te(K==="dark"?"light":"dark"),className:`w-full flex items-center ${j?"justify-center":"gap-3"} px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium`,title:j?e(K==="dark"?"shell.switch_light":"shell.switch_dark"):"",children:[h.jsx("div",{className:"min-w-[20px] flex justify-center",children:K==="dark"?h.jsx(Fj,{size:18}):h.jsx(Rj,{size:18})}),!j&&h.jsx(Fe.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"whitespace-nowrap",children:e(K==="dark"?"common.light_mode":"common.dark_mode")})]})}),h.jsxs("div",{className:"px-3 pb-3",children:[h.jsx("button",{onClick:()=>C(!j),className:`w-full flex items-center px-4 py-2.5 rounded-lg text-fg/40 hover:text-fg hover:bg-surface/50 transition-all text-xs font-medium ${j?"justify-center":"gap-3"}`,children:j?h.jsx(gj,{size:20}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"min-w-[20px] flex justify-center",children:h.jsx(mj,{size:20})}),h.jsx("span",{children:e("common.collapse")})]})}),h.jsxs("button",{onClick:()=>P(!0),className:"w-full flex items-center justify-center gap-2 px-3 py-2 mt-2 text-[10px] font-mono text-fg/30 hover:text-primary hover:bg-surface/30 rounded-lg transition-all group",title:e("shell.view_changelog"),children:[!j&&h.jsxs(h.Fragment,{children:[h.jsx(Uh,{size:12,className:"group-hover:text-primary transition-colors"}),h.jsxs("span",{children:["v","1.0.61"]})]}),j&&h.jsx(Uh,{size:14,className:"group-hover:text-primary transition-colors"})]})]})]}),h.jsxs("main",{className:"flex-1 flex flex-col p-4 gap-4 overflow-hidden relative",children:[o==="discovery"&&h.jsxs(h.Fragment,{children:[h.jsxs("header",{className:"flex justify-between items-center px-4 py-2",children:[h.jsxs("div",{children:[h.jsx("h2",{className:"text-2xl font-bold",children:e("tabs.discovery")}),h.jsx("p",{className:"text-sm text-fg/50",children:e("setup.welcome_desc")})]}),h.jsxs("div",{className:"flex gap-2",children:[h.jsxs("button",{onClick:()=>G(!0),className:"px-6 py-3 glass hover:bg-surface transition-colors flex items-center gap-2 text-sm font-medium",children:[h.jsx(ic,{size:16}),h.jsxs("div",{className:"flex flex-col items-start",children:[h.jsx("span",{children:e("discovery.sync_settings")}),h.jsx("span",{className:"text-[10px] text-fg/40 font-mono",children:T.sync_start_date?`${e("discovery.from")}: ${new Date(T.sync_start_date).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:T.last_sync_checkpoint?`${e("discovery.checkpoint")}: ${new Date(T.last_sync_checkpoint).toLocaleString([],{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`:e("discovery.all_time")})]})]}),h.jsxs("button",{onClick:O,disabled:B,className:"px-6 py-3 bg-gradient-to-r from-primary to-accent text-white font-bold rounded-xl shadow-lg glow-primary hover:scale-105 active:scale-95 transition-all flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100",children:[h.jsx(Tc,{size:18,className:B?"animate-spin":""}),e(B?"discovery.syncing":"discovery.sync_history")]})]})]}),h.jsx(VL,{onOpenUrl:pe=>window.open(pe,"_blank","noopener,noreferrer"),onCopyText:pe=>{navigator.clipboard.writeText(pe)}})]}),o==="chat"&&h.jsx(yz,{}),o==="transmute"&&h.jsx(bz,{}),o==="engine"&&h.jsx(xL,{}),o==="account"&&h.jsx(jL,{}),o==="logs"&&h.jsx(IL,{initialState:ne}),h.jsx(bL,{isExpanded:Y,onToggle:()=>X(!Y),onNavigate:ve,liftUp:o==="chat"})]}),h.jsx(NL,{signal:N,onClose:()=>A(null)}),h.jsx(AL,{isOpen:$,onClose:()=>G(!1)}),h.jsx(xz,{isOpen:S,onClose:()=>P(!1)})]})})}):h.jsx(dL,{onAuthSuccess:()=>W(),isInitialized:w})}function yi({active:e,icon:t,label:n,onClick:r,collapsed:s}){return h.jsx("button",{onClick:r,title:s?n:"",className:`w-full flex items-center ${s?"justify-center":"gap-3"} px-4 py-3 rounded-xl transition-all ${e?"bg-primary/10 text-primary shadow-sm":"text-fg/60 hover:bg-surface hover:text-fg"}`,children:s?ea.cloneElement(t,{className:e?"text-primary":""}):h.jsxs(h.Fragment,{children:[h.jsx("div",{className:"min-w-[20px] flex justify-center",children:ea.cloneElement(t,{className:e?"text-primary":""})}),h.jsx(Fe.span,{initial:{opacity:0,x:-10},animate:{opacity:1,x:0},className:"font-semibold text-sm whitespace-nowrap",children:n})]})})}function Sz(){Qe.interceptors.request.use(async e=>{try{const{data:{session:t}}=await oe.auth.getSession();t?.access_token&&(e.headers.Authorization=`Bearer ${t.access_token}`);const n=Rs();n&&(e.headers["x-supabase-url"]=n.url,e.headers["x-supabase-key"]=n.anonKey)}catch(t){console.error("[Axios] Error injecting headers:",t)}return e})}const{slice:jz,forEach:Ez}=[];function Cz(e){return Ez.call(jz.call(arguments,1),t=>{if(t)for(const n in t)e[n]===void 0&&(e[n]=t[n])}),e}function Tz(e){return typeof e!="string"?!1:[/<\s*script.*?>/i,/<\s*\/\s*script\s*>/i,/<\s*img.*?on\w+\s*=/i,/<\s*\w+\s*on\w+\s*=.*?>/i,/javascript\s*:/i,/vbscript\s*:/i,/expression\s*\(/i,/eval\s*\(/i,/alert\s*\(/i,/document\.cookie/i,/document\.write\s*\(/i,/window\.location/i,/innerHTML/i].some(n=>n.test(e))}const i_=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Nz=function(e,t){const r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{path:"/"},s=encodeURIComponent(t);let o=`${e}=${s}`;if(r.maxAge>0){const a=r.maxAge-0;if(Number.isNaN(a))throw new Error("maxAge should be a Number");o+=`; Max-Age=${Math.floor(a)}`}if(r.domain){if(!i_.test(r.domain))throw new TypeError("option domain is invalid");o+=`; Domain=${r.domain}`}if(r.path){if(!i_.test(r.path))throw new TypeError("option path is invalid");o+=`; Path=${r.path}`}if(r.expires){if(typeof r.expires.toUTCString!="function")throw new TypeError("option expires is invalid");o+=`; Expires=${r.expires.toUTCString()}`}if(r.httpOnly&&(o+="; HttpOnly"),r.secure&&(o+="; Secure"),r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:o+="; SameSite=Strict";break;case"lax":o+="; SameSite=Lax";break;case"strict":o+="; SameSite=Strict";break;case"none":o+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return r.partitioned&&(o+="; Partitioned"),o},o_={create(e,t,n,r){let s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};n&&(s.expires=new Date,s.expires.setTime(s.expires.getTime()+n*60*1e3)),r&&(s.domain=r),document.cookie=Nz(e,t,s)},read(e){const t=`${e}=`,n=document.cookie.split(";");for(let r=0;r<n.length;r++){let s=n[r];for(;s.charAt(0)===" ";)s=s.substring(1,s.length);if(s.indexOf(t)===0)return s.substring(t.length,s.length)}return null},remove(e,t){this.create(e,"",-1,t)}};var Az={name:"cookie",lookup(e){let{lookupCookie:t}=e;if(t&&typeof document<"u")return o_.read(t)||void 0},cacheUserLanguage(e,t){let{lookupCookie:n,cookieMinutes:r,cookieDomain:s,cookieOptions:o}=t;n&&typeof document<"u"&&o_.create(n,e,r,s,o)}},Rz={name:"querystring",lookup(e){let{lookupQuerystring:t}=e,n;if(typeof window<"u"){let{search:r}=window.location;!window.location.search&&window.location.hash?.indexOf("?")>-1&&(r=window.location.hash.substring(window.location.hash.indexOf("?")));const o=r.substring(1).split("&");for(let a=0;a<o.length;a++){const c=o[a].indexOf("=");c>0&&o[a].substring(0,c)===t&&(n=o[a].substring(c+1))}}return n}},Pz={name:"hash",lookup(e){let{lookupHash:t,lookupFromHashIndex:n}=e,r;if(typeof window<"u"){const{hash:s}=window.location;if(s&&s.length>2){const o=s.substring(1);if(t){const a=o.split("&");for(let c=0;c<a.length;c++){const u=a[c].indexOf("=");u>0&&a[c].substring(0,u)===t&&(r=a[c].substring(u+1))}}if(r)return r;if(!r&&n>-1){const a=s.match(/\/([a-zA-Z-]*)/g);return Array.isArray(a)?a[typeof n=="number"?n:0]?.replace("/",""):void 0}}}return r}};let xi=null;const a_=()=>{if(xi!==null)return xi;try{if(xi=typeof window<"u"&&window.localStorage!==null,!xi)return!1;const e="i18next.translate.boo";window.localStorage.setItem(e,"foo"),window.localStorage.removeItem(e)}catch{xi=!1}return xi};var Oz={name:"localStorage",lookup(e){let{lookupLocalStorage:t}=e;if(t&&a_())return window.localStorage.getItem(t)||void 0},cacheUserLanguage(e,t){let{lookupLocalStorage:n}=t;n&&a_()&&window.localStorage.setItem(n,e)}};let vi=null;const l_=()=>{if(vi!==null)return vi;try{if(vi=typeof window<"u"&&window.sessionStorage!==null,!vi)return!1;const e="i18next.translate.boo";window.sessionStorage.setItem(e,"foo"),window.sessionStorage.removeItem(e)}catch{vi=!1}return vi};var Lz={name:"sessionStorage",lookup(e){let{lookupSessionStorage:t}=e;if(t&&l_())return window.sessionStorage.getItem(t)||void 0},cacheUserLanguage(e,t){let{lookupSessionStorage:n}=t;n&&l_()&&window.sessionStorage.setItem(n,e)}},Iz={name:"navigator",lookup(e){const t=[];if(typeof navigator<"u"){const{languages:n,userLanguage:r,language:s}=navigator;if(n)for(let o=0;o<n.length;o++)t.push(n[o]);r&&t.push(r),s&&t.push(s)}return t.length>0?t:void 0}},Dz={name:"htmlTag",lookup(e){let{htmlTag:t}=e,n;const r=t||(typeof document<"u"?document.documentElement:null);return r&&typeof r.getAttribute=="function"&&(n=r.getAttribute("lang")),n}},Mz={name:"path",lookup(e){let{lookupFromPathIndex:t}=e;if(typeof window>"u")return;const n=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(n)?n[typeof t=="number"?t:0]?.replace("/",""):void 0}},zz={name:"subdomain",lookup(e){let{lookupFromSubdomainIndex:t}=e;const n=typeof t=="number"?t+1:1,r=typeof window<"u"&&window.location?.hostname?.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i);if(r)return r[n]}};let Yk=!1;try{document.cookie,Yk=!0}catch{}const Qk=["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"];Yk||Qk.splice(1,1);const Fz=()=>({order:Qk,lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:e=>e});class Zk{constructor(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(t,n)}init(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{languageUtils:{}},n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=t,this.options=Cz(n,this.options||{},Fz()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=s=>s.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=r,this.addDetector(Az),this.addDetector(Rz),this.addDetector(Oz),this.addDetector(Lz),this.addDetector(Iz),this.addDetector(Dz),this.addDetector(Mz),this.addDetector(zz),this.addDetector(Pz)}addDetector(t){return this.detectors[t.name]=t,this}detect(){let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:this.options.order,n=[];return t.forEach(r=>{if(this.detectors[r]){let s=this.detectors[r].lookup(this.options);s&&typeof s=="string"&&(s=[s]),s&&(n=n.concat(s))}}),n=n.filter(r=>r!=null&&!Tz(r)).map(r=>this.options.convertDetectedLanguage(r)),this.services&&this.services.languageUtils&&this.services.languageUtils.getBestMatchFromCodes?n:n.length>0?n[0]:null}cacheUserLanguage(t){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.options.caches;n&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(t)>-1||n.forEach(r=>{this.detectors[r]&&this.detectors[r].cacheUserLanguage(t,this.options)}))}}Zk.type="languageDetector";const $z={save:"Save",cancel:"Cancel",loading:"Loading...",error:"Error",success:"Success",settings:"Settings",search:"Search",back:"Back",all:"All",delete:"Delete",update:"Update",edit:"Edit",close:"Close",complete:"Complete",skip:"Skip",begin:"Begin",connection:"Connection",setup:"Setup",project:"Project",account:"Account",logout:"Logout",welcome:"Welcome",dark_mode:"Dark Mode",light_mode:"Light Mode",collapse:"Collapse",just_now:"Just now",enabled:"Enabled",disabled:"Disabled",quick:"Quick (5)",balanced:"Balanced (50)",thorough:"Thorough (200)",resetting:"Resetting...",saving:"Saving...",locale_code:"en-US",categories:{ai_ml:"AI & ML",business:"Business",politics:"Politics",technology:"Technology",finance:"Finance",crypto:"Crypto",science:"Science",other:"Other"}},Uz={discovery:"Discovery",chat:"Chat",transmute:"Transmute",logs:"System Logs",history:"History"},Bz={welcome_title:"Assemble Your Engine",welcome_desc:"Alchemy requires a Supabase essence to store signal fragments and intelligence patterns.",requirements:"Requirements:",project_url:"Supabase Project URL",anon_key:"Anon Public API Key",db_password:"Database Password",project_url_placeholder:"https://xxx.supabase.co or project-id",anon_key_placeholder:"eyJ...",project_id_placeholder:"abcdefghijklm",access_token_placeholder:"sbp_...",begin_init:"BEGIN INITIALIZATION",connect_essence:"CONNECT ESSENCE",credentials_title:"Essence Coordinates",credentials_desc:"Link the alchemist engine to your cloud database",validating:"Validating Link",resonance:"Synchronizing Resonance...",init_schema:"Initialize Schema",schema_desc:"Run database migrations to set up required tables and functions.",project_id:"Project ID",access_token:"Access Token",run_migrations:"RUN MIGRATIONS",running_migrations:"Running Migrations",take_minute:"This may take a minute...",engine_aligned:"Engine Aligned",restarting:"Restarting Alchemist Subsystems...",forge_project:"Forge Project at Supabase",project_id_help:"Found in Supabase Dashboard → Project Settings → General",access_token_help:"Generate at",access_token_link:"supabase.com/dashboard/account/tokens",project_id_required:"Project ID is required",access_token_required:"Access token is required",migration_failed_logs:"Migration failed. Check logs for details.",stream_error:"Failed to read migration stream",back:"BACK",retry:"RETRY"},Vz={title_init:"INITIALIZE MASTER",title_join:"JOIN THE CIRCLE",title_mystic:"MYSTIC ACCESS",title_login:"ALCHEMIST LOGIN",desc_init:"Forge the prime alchemist account",desc_mystic_email:"Enter your essence email",desc_mystic_code:"Transmute the sacred code",desc_login:"Transmute your data into intelligence",first_name:"First Name",last_name:"Last Name",first_name_placeholder:"Zosimos",last_name_placeholder:"Panopolis",email_address:"Email Address",email_placeholder:"alchemist@example.com",complexity_key:"Complexity Key",password_placeholder:"••••••••",init_account:"INITIALIZE ACCOUNT",send_code:"SEND CODE",unseal_engine:"UNSEAL ENGINE",verify_code:"VERIFY CODE",change_email:"Change email address",sign_in_code:"Sign in with Code",sign_in_password:"Sign in with Password",already_alchemist:"Already an Alchemist?",new_to_alchemy:"New to Alchemy?",login_instead:"Login instead",create_account:"Create an account",session_failed:"Failed to create session",invalid_code:"Invalid code"},qz={filters:"Filters",category:"Category",intelligence_score:"Intelligence Score",no_signals_in_category:"No signals in {{category}} yet.",no_categories:"No categories yet.",discovery_hint:"Signals will be organized here once discovered.",loading_signals:"Loading signals...",dismiss_hint:"Dismiss (Not Interested)",signal_count_one:"{{count}} signal",signal_count_other:"{{count}} signals",time_min_ago:"{{count}}m ago",time_hour_ago:"{{count}}h ago",time_day_ago:"{{count}}d ago",add_note_title:"Add Note",target:"Target",note_placeholder:"Enter your thoughts, ideas, or action items regarding this signal...",save_note:"Save Note",view_all_sources:"View all sources",source_count_one:"{{count}} source",source_count_other:"{{count}} sources",source_found_in:"Found in {{count}} different sources",high_confidence:"High confidence - found in {{count}} sources",new_signals:"New Signals",smart_summary:"Smart Summary",entities:"Entities",sources:"Sources",last_sync:"Last Sync",syncnow:"Sync Now",all_time:"All time",checkpoint:"Checkpoint",from:"From",score_high:"HIGH",score_medium:"MEDIUM",score_low:"LOW",sources_count:"{{count}} sources",open_source:"Open",add_note:"Note",boost_topic:"Boost Topic",boosted:"Boosted",dismissed:"Dismissed",remove_favourite:"Remove from favourites",add_favourite:"Add to favourites",sync_history:"Sync History",syncing:"Syncing...",sync_settings:"Sync Settings",discovered:"Discovered",original_source:"Original Source",ai_summary:"AI Summary",full_content:"Full Content",copied:"Copied!",open_link:"Open",detail_title:"Signal Details",sync_from:"Sync From (Optional)",urls_per_sync:"URLs per Sync",sync_from_hint:"Leave empty to sync only new URLs since last sync (incremental). Set a date to process URLs from that point forward.",reset_checkpoint:"Reset Checkpoint",reset_checkpoint_hint:'Clear the sync checkpoint to force a full re-sync from your "Sync From" date',sync_info:'The Alchemist tracks your progress automatically. Use "Sync From" to backfill history or "Reset Checkpoint" to start fresh.',save_settings:"Save Settings",sync_saved:"Sync settings saved successfully",checkpoint_reset:"Checkpoint reset successfully",login_to_save:"Please log in to save settings",login_to_reset:"Please log in to reset checkpoint",status_updated:"Engine status updated to {{status}}",asset_ready:'Asset "{{title}}" is ready!',scanning:"Scanning for new categories and topics...",discovery_complete:"Engine discovery complete!",discovery_failed:"Discovery failed. Check settings.",load_failed:"Failed to load engines",starting_run:"Starting engine run...",run_complete:"Engine run complete! Created: {{title}}",run_started_desktop:"Engine run started on Desktop. Tracking as: {{id}}",run_failed:"Failed to run engine",brief_failed:"Failed to generate production brief",copied_json:"JSON copied to clipboard",json_footer:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",topic:"Topic",pipeline:"Pipeline"},Hz={history:"History",ask_anything:"Ask anything about your browsing history...",sources:"Sources",processing:"Processing your query...",new_chat:"New Chat",no_messages:"No messages yet. Start a conversation!",no_history:"No chat history yet.",title:"Ask Alchemist",desc:"I can help you recall information, summarize topics, and find insights from your browsing history.",thinking:"Exploring memory...",placeholder:"Ask about your history...",error_message:"Sorry, I encountered an error processing your request.",relevant_context:"Relevant Context",match_score:"{{score}}% Match",rag_attribution:"Alchemist used these {{count}} signals to answer",suggestions:{react:"What have I read about React recently?",ai:"Summarize the latest AI news I visited.",finance:"Do I have any notes on Finance?",performance:"Find articles about 'Performance'"}},Kz={engines:"Alchemist Engines",assets:"Generated Assets",newsletter:"Newsletter",thread:"Thread",audio:"Audio",report:"Report",title:"Transmute Engine",desc:"Active Generation Pipelines & Assets",generate:"Generate",processing_desktop:"Processing on Desktop...",ensure_defaults:"Ensure Default Engines",create_engine:"Create Engine",no_assets:"No assets generated yet.",generate_engines:"Generate Engines",new_engine:"New Engine",no_engines:"No Engines Configured",no_engines_desc:"Create your first pipeline to automatically turn signals into newsletters, threads, or audio briefs.",run_engine:"Run Engine",running:"Running...",last_run:"Last Run",never:"Never",schedule:"Schedule",manual:"Manual",topic:"Topic",pipeline:"Pipeline",pause:"Pause",resume:"Resume",view_json:"View Production Brief JSON",json_contract:"Stateless & Self-Contained Contract",json_desc:"This JSON contains the full context (Signals + User Persona) required for the Desktop Studio.",generating_asset:"Generating Asset...",queued_desktop:"Queued for Desktop...",desktop_processing:"The RealTimeX Desktop app is processing this request. This modal will update automatically once finished.",unsupported_type:"Unsupported asset type",edit_engine:"Edit Engine",engine_name:"Engine Name",type:"Type",status:"Status",execution_env:"Execution Environment",local_llm:"Local (Alchemy LLM)",desktop_swarm:"RealTimeX Desktop (Agent Swarm)",env_desc_desktop:"Delegates heavy tasks like Audio/Video to the desktop app.",env_desc_local:"Runs simple Markdown tasks directly in Alchemy.",min_score:"Min Score",max_signals:"Max Signals",category_filter:"Category Filter (multi-select)",multi_select_hint:"Hold Cmd/Ctrl to select multiple categories",schedule_hint:"Note: Scheduling is not yet automated",prompt_override:"Custom Prompt Override (optional)",prompt_placeholder:"Override the default prompt for this engine type...",delete_confirm:"Really delete?",confirm:"Confirm"},Wz={title:"Account Configuration",desc:"Manage your Alchemist profile and essence links.",profile:"Profile",security:"Security",supabase:"Supabase",first_name:"First Name",last_name:"Last Name",email_locked:"Email Address (Locked)",sound_effects:"Sound Effects",sound_desc:"Enable audio feedback for sync events and signal discoveries.",sign_out:"Sign Out",logout_desc:"End your current session and return to the login screen.",preserve_profile:"Preserve Profile",security_title:"Update Entropy Key",new_password:"New Password",confirm_password:"Confirm Password",password_mismatch:"Complexity keys do not match.",password_too_short:"Entropy too low. Minimum 8 characters.",password_rotate_success:"Key rotation successful.",rotate_key:"Rotate Key",essence_resonance:"Essence Resonance",byok_desc:"Bring Your Own Keys (BYOK) for intelligence persistence.",established_link:"Established Link",env_notice:"Active from environment variables. UI override enabled.",realign_link:"Realign Link",sever_link:"Sever Link",sever_confirm:"Sever connection to this essence? This will reset local resonance.",anon_secret_fragment:"Anon Secret Fragment",no_resonance:"No Essence Resonance",no_resonance_desc:"The Alchemist requires a cloud core to store intelligence fragments.",initiate_link:"Initiate Link",test_connection:"Test Connection"},Gz={title:"System Logs",desc:"Detailed history of sync runs, sources, and URL processing",blacklist_suggestion:"Potential Blacklist",blacklist_desc:"Candidates for blocking",recent_errors:"Recent Errors",errors_desc:"Failed URL processes",total_signals:"Total Signals",signals_desc:"Successfully mined",blacklist_modal_title:"Blacklist Suggestions",blacklist_modal_desc:"Review domains suggested for blacklisting based on low scores.",no_suggestions:"No suggestions right now",quality_good:"Your signal quality looks good!",signals_count:"{{count}} signals",avg_score:"Avg Score: {{score}}",low_quality:"Consistently Low Quality",repetitive:"Repetitive Pattern",blacklist_domain:"Blacklist Domain",errors_modal_title:"Recent Errors",errors_modal_desc:"Log of recent failures and issues.",no_recent_errors:"No recent errors found.",signals_modal_title:"Found Signals",signals_modal_desc:"Browse and manage your mined signals history.",search_placeholder:"Search signals...",any_score:"Any Score",high_score:"High (80%+)",medium_score:"Medium (50-79%)",low_score:"Low (<50%)",all_categories:"All Categories",page_x:"Page {{page}}"},Jz={title:"Alchemist Engine",live:"LIVE",clear:"Clear",idle:"Idle. Awaiting signal mining events...",run_completed:"Mining Run Completed",signals:"Signals",urls:"URLs",skipped:"Skipped",failed_to_process:"{{count}} URLs failed to process",view_logs:"View Logs",hide_details:"Hide Details",view_details:"View Details",engine_log:"Live Engine Log",state_reading:"Reading",state_thinking:"Thinking",state_signal:"Signal",state_skipped:"Skipped",state_error:"Error",state_completed:"Completed",msg_reading:"Reading content from: {{url}}",msg_thinking:"Analyzing relevance of: {{title}}",msg_found_signal:"Found signal: {{summary}} ({{score}}%)",msg_low_signal:"Low signal stored for review ({{score}}%): {{title}}",msg_failed:"Analysis failed for {{title}}: {{error}}",msg_sync_completed:"Sync completed: {{signals}} signals found, {{skipped}} skipped, {{errors}} errors"},Xz={switch_light:"Switch to Light Mode",switch_dark:"Switch to Dark Mode",view_changelog:"View Changelog",release_notes:"Release Notes",changelog_error:"Failed to load changelog."},Yz={title:"Signal Pulse",mining:"Mining",standing_by:"Standing by",idle:"Idle",tracked:"Signals tracked",avg_score:"Average score",top_signal:"Top signal",latest:"Latest",awaiting:"Awaiting mining",no_signals:"No signals yet"},Qz={title:"Intelligence Engine",subtitle:"Fine-tune the Alchemist's cognitive parameters and provider links.",configuration:"AI Configuration",test_connection:"Test Connection",save_config:"Save Configuration",llm_provider:"LLM Provider",embedding_provider:"Embedding Provider",sdk_connected:"SDK Connected",sdk_not_available:"SDK Not Available",provider:"Provider",intelligence_model:"Intelligence Model",embedding_model:"Embedding Model",loading_providers:"Loading providers...",sdk_info_success:"✓ Using RealTimeX configured provider",sdk_info_fail:"⚠️ RealTimeX SDK not detected. Configure in RealTimeX Desktop.",embedding_info_success:"✓ Embeddings are generated using your RealTimeX configured provider",embedding_info_fail:"⚠️ RealTimeX SDK not detected. Configure providers in RealTimeX Desktop.",persona_title:"Persona Memory",save_memory:"Save Memory",interests_title:"Active Interests",interests_priority:"High Priority",interests_desc:"The Alchemist prioritizes content matching these topics. Updated automatically based on Favorites & Boosts.",interests_placeholder:"e.g. User focuses on React performance, Rust backend systems, and AI Agent architecture...",antipatterns_title:"Anti-Patterns",antipatterns_priority:"Avoid",antipatterns_desc:"The Alchemist filters out or scores down content matching these patterns. Updated via Dismissals.",antipatterns_placeholder:"e.g. Dislikes marketing fluff, generic listicles, and crypto hype...",browser_sources:"Browser History Sources",save_browser:"Save Browser Sources",blacklist_title:"Blacklist Domains",blacklist_desc:"URLs containing these patterns will be skipped during mining. Enter one pattern per line.",blacklist_label:"Domain Patterns (one per line)",blacklist_placeholder:`google.com/search
135
135
  localhost:
136
136
  127.0.0.1
137
137
  facebook.com
package/dist/index.html CHANGED
@@ -9,7 +9,7 @@
9
9
  <link rel="preconnect" href="https://fonts.googleapis.com">
10
10
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
11
11
  <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;700&family=Outfit:wght@300;400;600;800&display=swap" rel="stylesheet">
12
- <script type="module" crossorigin src="/assets/index-Rkp02lca.js"></script>
12
+ <script type="module" crossorigin src="/assets/index-C4HJN6HA.js"></script>
13
13
  <link rel="stylesheet" crossorigin href="/assets/index-uuNKpKqf.css">
14
14
  </head>
15
15
  <body>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@realtimex/realtimex-alchemy",
3
- "version": "1.0.59",
3
+ "version": "1.0.61",
4
4
  "description": "Passive Intelligence engine for RealTimeX Alchemy. Transmute your reading time into high-density insights.",
5
5
  "type": "module",
6
6
  "main": "dist/api/index.js",
@@ -0,0 +1,25 @@
1
+ -- Sync names and email from auth.users (metadata) to public.profiles during signup
2
+ CREATE OR REPLACE FUNCTION handle_new_user()
3
+ RETURNS TRIGGER AS $$
4
+ BEGIN
5
+ INSERT INTO public.profiles (id, first_name, last_name, full_name, email)
6
+ VALUES (
7
+ NEW.id,
8
+ NEW.raw_user_meta_data->>'first_name',
9
+ NEW.raw_user_meta_data->>'last_name',
10
+ NEW.raw_user_meta_data->>'full_name',
11
+ NEW.email
12
+ )
13
+ ON CONFLICT (id) DO UPDATE SET
14
+ first_name = EXCLUDED.first_name,
15
+ last_name = EXCLUDED.last_name,
16
+ full_name = EXCLUDED.full_name,
17
+ email = EXCLUDED.email;
18
+
19
+ INSERT INTO public.alchemy_settings (user_id)
20
+ VALUES (NEW.id)
21
+ ON CONFLICT (user_id) DO NOTHING;
22
+
23
+ RETURN NEW;
24
+ END;
25
+ $$ LANGUAGE plpgsql SECURITY DEFINER;