Elffuss BraidHub

kikocis/osiris public

master · 33.7 KiBRawPermalink
1'use client';
2
3import { useState, useRef, useEffect, useCallback } from 'react';
4import { motion, AnimatePresence } from 'framer-motion';
5import {
6 Brain,
7 Send,
8 Sparkles,
9 Settings,
10 X,
11 Bot,
12 User,
13 AlertTriangle,
14 Shield,
15 ChevronDown,
16 Loader2,
17 Key,
18 Check,
19 Trash2,
20} from 'lucide-react';
21import type { IntelligenceContext } from '@/lib/ai-engine';
22
23/* ═══════════════════════════════════════════════════════════════
24 OSIRIS — AI Intelligence Analyst Panel
25 Premium glass-panel chat interface for real-time intelligence
26 analysis powered by Gemini 2.0 Flash
27 ═══════════════════════════════════════════════════════════════ */
28
29/* ─────────────────────────────────────────────────────────────
30 Interfaces
31 ───────────────────────────────────────────────────────────── */
32
33interface DashboardData {
34 earthquakes?: EarthquakeItem[];
35 news?: NewsItem[];
36 gdelt?: GdeltEvent[];
37 markets?: MarketData;
38 [key: string]: unknown;
39}
40
41interface EarthquakeItem {
42 id: string;
43 magnitude: number;
44 location: string;
45 lat: number;
46 lng: number;
47 depth: number;
48 time: string;
49 tsunami: boolean;
50 felt: number | null;
51 alert: string | null;
52}
53
54interface NewsItem {
55 id: string;
56 title: string;
57 description: string;
58 link: string;
59 published: string;
60 source: string;
61 risk_score: number;
62 coords: [number, number] | null;
63 machine_assessment: string | null;
64}
65
66interface GdeltEvent {
67 title: string;
68 type: string;
69 lat: number;
70 lng: number;
71 date: string;
72 source: string;
73 tone: number;
74}
75
76interface MarketData {
77 indices?: MarketIndex[];
78 commodities?: MarketCommodity[];
79}
80
81interface MarketIndex {
82 name: string;
83 value: number;
84 change: number;
85 changePercent: number;
86}
87
88interface MarketCommodity {
89 name: string;
90 price: number;
91 change: number;
92}
93
94interface ChatMessage {
95 id: string;
96 role: 'user' | 'analyst';
97 content: string;
98 timestamp: string;
99 isError?: boolean;
100}
101
102interface AiAnalystProps {
103 data: DashboardData;
104}
105
106/* ─────────────────────────────────────────────────────────────
107 Helpers
108 ───────────────────────────────────────────────────────────── */
109
110function generateId(): string {
111 return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
112}
113
114function buildContext(data: DashboardData): IntelligenceContext {
115 const earthquakes = (data.earthquakes || []).slice(0, 20).map((eq) => ({
116 id: eq.id || generateId(),
117 magnitude: eq.magnitude,
118 location: eq.location,
119 latitude: eq.lat,
120 longitude: eq.lng,
121 depth: eq.depth,
122 timestamp: eq.time,
123 tsunami: eq.tsunami ?? false,
124 felt: eq.felt ?? null,
125 alert: eq.alert ?? null,
126 }));
127
128 const news = (data.news || []).slice(0, 15).map((item) => ({
129 id: item.id || generateId(),
130 title: item.title,
131 description: item.description || '',
132 link: item.link || '',
133 published: item.published,
134 source: item.source,
135 risk_score: item.risk_score,
136 coords: item.coords,
137 machine_assessment: item.machine_assessment,
138 }));
139
140 const threats = (data.gdelt || []).slice(0, 15).map((ev) => ({
141 id: generateId(),
142 type: ev.type || 'INCIDENT',
143 title: ev.title,
144 description: ev.title,
145 severity: (ev.tone < -5 ? 'CRITICAL' : ev.tone < -2 ? 'HIGH' : ev.tone < 0 ? 'ELEVATED' : 'LOW') as
146 | 'CRITICAL'
147 | 'HIGH'
148 | 'ELEVATED'
149 | 'LOW',
150 region: ev.source || 'Unknown',
151 latitude: ev.lat,
152 longitude: ev.lng,
153 timestamp: ev.date,
154 source: ev.source || 'GDELT',
155 }));
156
157 return {
158 earthquakes,
159 news,
160 threats,
161 cyberAlerts: [],
162 timestamp: new Date().toISOString(),
163 };
164}
165
166/** Render markdown-lite: bold, headers, bullet points */
167function renderMarkdown(text: string): string {
168 return text
169 .replace(/### (.+)/g, '<h4 class="text-[11px] font-bold text-[var(--gold-primary)] mt-3 mb-1 tracking-wider uppercase font-mono">$1</h4>')
170 .replace(/## (.+)/g, '<h3 class="text-[12px] font-bold text-[var(--gold-primary)] mt-3 mb-1.5 tracking-wider uppercase font-mono border-b border-[var(--border-secondary)] pb-1">$1</h3>')
171 .replace(/# (.+)/g, '<h2 class="text-[13px] font-bold text-[var(--gold-primary)] mt-3 mb-1.5 tracking-wider uppercase font-mono">$1</h2>')
172 .replace(/\*\*(.+?)\*\*/g, '<strong class="text-[var(--text-heading)] font-semibold">$1</strong>')
173 .replace(/\*(.+?)\*/g, '<em class="text-[var(--text-secondary)] italic">$1</em>')
174 .replace(/^- (.+)/gm, '<div class="flex items-start gap-1.5 ml-1 my-0.5"><span class="text-[var(--gold-dim)] mt-[3px] text-[8px]">◆</span><span>$1</span></div>')
175 .replace(/\n/g, '<br />');
176}
177
178/* ─────────────────────────────────────────────────────────────
179 Component
180 ───────────────────────────────────────────────────────────── */
181
182export default function AiAnalyst({ data }: AiAnalystProps) {
183 const [isOpen, setIsOpen] = useState(false);
184 const [messages, setMessages] = useState<ChatMessage[]>([]);
185 const [inputText, setInputText] = useState('');
186 const [isLoading, setIsLoading] = useState(false);
187 const [showSettings, setShowSettings] = useState(false);
188 const [apiKeyInput, setApiKeyInput] = useState('');
189 const [keySaved, setKeySaved] = useState(false);
190
191 const messagesEndRef = useRef<HTMLDivElement>(null);
192 const inputRef = useRef<HTMLTextAreaElement>(null);
193
194 // Load saved key on mount
195 useEffect(() => {
196 const saved = localStorage.getItem('osiris-gemini-key');
197 if (saved) {
198 setApiKeyInput(saved);
199 setKeySaved(true);
200 }
201 }, []);
202
203 // Auto-scroll to bottom
204 useEffect(() => {
205 messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
206 }, [messages]);
207
208 // Focus input when opened
209 useEffect(() => {
210 if (isOpen && !showSettings) {
211 setTimeout(() => inputRef.current?.focus(), 300);
212 }
213 }, [isOpen, showSettings]);
214
215 const getHeaders = useCallback((): Record<string, string> => {
216 const headers: Record<string, string> = { 'Content-Type': 'application/json' };
217 const savedKey = localStorage.getItem('osiris-gemini-key');
218 if (savedKey) {
219 headers['x-gemini-key'] = savedKey;
220 }
221 return headers;
222 }, []);
223
224 const handleSend = useCallback(async () => {
225 const query = inputText.trim();
226 if (!query || isLoading) return;
227
228 const userMsg: ChatMessage = {
229 id: generateId(),
230 role: 'user',
231 content: query,
232 timestamp: new Date().toISOString(),
233 };
234 setMessages((prev) => [...prev, userMsg]);
235 setInputText('');
236 setIsLoading(true);
237
238 try {
239 const context = buildContext(data);
240 const res = await fetch('/api/ai/analyze', {
241 method: 'POST',
242 headers: getHeaders(),
243 body: JSON.stringify({ query, context }),
244 });
245
246 const json = await res.json();
247
248 if (!res.ok) {
249 const errorBody = json as { error: string; code: string; retryAfter?: number };
250 throw new Error(errorBody.error || `HTTP ${res.status}`);
251 }
252
253 const responseBody = json as { analysis: string; model: string; timestamp: string };
254
255 const analystMsg: ChatMessage = {
256 id: generateId(),
257 role: 'analyst',
258 content: responseBody.analysis,
259 timestamp: responseBody.timestamp,
260 };
261 setMessages((prev) => [...prev, analystMsg]);
262 } catch (err: unknown) {
263 const message = err instanceof Error ? err.message : 'Analysis failed';
264 const errorMsg: ChatMessage = {
265 id: generateId(),
266 role: 'analyst',
267 content: `⚠ INTELLIGENCE ANALYSIS ERROR\n\n${message}`,
268 timestamp: new Date().toISOString(),
269 isError: true,
270 };
271 setMessages((prev) => [...prev, errorMsg]);
272 } finally {
273 setIsLoading(false);
274 }
275 }, [inputText, isLoading, data, getHeaders]);
276
277 const handleBriefing = useCallback(async () => {
278 if (isLoading) return;
279
280 const userMsg: ChatMessage = {
281 id: generateId(),
282 role: 'user',
283 content: '📋 Generate full intelligence briefing from current operational data',
284 timestamp: new Date().toISOString(),
285 };
286 setMessages((prev) => [...prev, userMsg]);
287 setIsLoading(true);
288
289 try {
290 const context = buildContext(data);
291 const res = await fetch('/api/ai/briefing', {
292 method: 'POST',
293 headers: getHeaders(),
294 body: JSON.stringify({ context }),
295 });
296
297 const json = await res.json();
298
299 if (!res.ok) {
300 const errorBody = json as { error: string; code: string };
301 throw new Error(errorBody.error || `HTTP ${res.status}`);
302 }
303
304 const responseBody = json as { briefing: string; generatedAt: string };
305
306 const analystMsg: ChatMessage = {
307 id: generateId(),
308 role: 'analyst',
309 content: responseBody.briefing,
310 timestamp: responseBody.generatedAt,
311 };
312 setMessages((prev) => [...prev, analystMsg]);
313 } catch (err: unknown) {
314 const message = err instanceof Error ? err.message : 'Briefing generation failed';
315 const errorMsg: ChatMessage = {
316 id: generateId(),
317 role: 'analyst',
318 content: `⚠ BRIEFING GENERATION ERROR\n\n${message}`,
319 timestamp: new Date().toISOString(),
320 isError: true,
321 };
322 setMessages((prev) => [...prev, errorMsg]);
323 } finally {
324 setIsLoading(false);
325 }
326 }, [isLoading, data, getHeaders]);
327
328 const handleKeyDown = useCallback(
329 (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
330 if (e.key === 'Enter' && !e.shiftKey) {
331 e.preventDefault();
332 handleSend();
333 }
334 },
335 [handleSend]
336 );
337
338 const saveApiKey = useCallback(() => {
339 const key = apiKeyInput.trim();
340 if (key) {
341 localStorage.setItem('osiris-gemini-key', key);
342 setKeySaved(true);
343 setTimeout(() => setShowSettings(false), 600);
344 }
345 }, [apiKeyInput]);
346
347 const clearApiKey = useCallback(() => {
348 localStorage.removeItem('osiris-gemini-key');
349 setApiKeyInput('');
350 setKeySaved(false);
351 }, []);
352
353 const clearMessages = useCallback(() => {
354 setMessages([]);
355 }, []);
356
357 /* ── Floating Trigger Button ── */
358 const triggerButton = (
359 <motion.button
360 initial={{ scale: 0, opacity: 0 }}
361 animate={{ scale: 1, opacity: 1 }}
362 transition={{ delay: 3, type: 'spring', stiffness: 200, damping: 15 }}
363 whileHover={{ scale: 1.1 }}
364 whileTap={{ scale: 0.95 }}
365 onClick={() => setIsOpen(true)}
366 className="fixed bottom-[90px] right-5 md:bottom-8 md:right-8 z-[500] w-14 h-14 rounded-full flex items-center justify-center cursor-pointer border-0"
367 style={{
368 background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.2) 0%, rgba(212, 175, 55, 0.08) 100%)',
369 border: '1px solid rgba(212, 175, 55, 0.4)',
370 boxShadow:
371 '0 0 30px rgba(212, 175, 55, 0.2), 0 0 60px rgba(212, 175, 55, 0.1), 0 4px 20px rgba(0, 0, 0, 0.5)',
372 }}
373 aria-label="Open AI Intelligence Analyst"
374 >
375 <Brain className="w-6 h-6 text-[var(--gold-primary)]" />
376 {/* Pulse rings */}
377 <div className="absolute inset-0 rounded-full animate-glow-pulse" />
378 <motion.div
379 className="absolute inset-[-4px] rounded-full border border-[var(--gold-primary)]"
380 animate={{ opacity: [0.3, 0.6, 0.3], scale: [1, 1.1, 1] }}
381 transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }}
382 style={{ opacity: 0.3 }}
383 />
384 </motion.button>
385 );
386
387 /* ── Panel ── */
388 return (
389 <>
390 {/* Trigger — only show when panel is closed */}
391 <AnimatePresence>{!isOpen && triggerButton}</AnimatePresence>
392
393 {/* Panel */}
394 <AnimatePresence>
395 {isOpen && (
396 <>
397 {/* Backdrop on mobile */}
398 <motion.div
399 initial={{ opacity: 0 }}
400 animate={{ opacity: 1 }}
401 exit={{ opacity: 0 }}
402 className="fixed inset-0 bg-black/40 backdrop-blur-sm z-[600] md:hidden"
403 onClick={() => setIsOpen(false)}
404 />
405
406 {/* Main Panel */}
407 <motion.div
408 initial={{ opacity: 0, y: 40, scale: 0.95 }}
409 animate={{ opacity: 1, y: 0, scale: 1 }}
410 exit={{ opacity: 0, y: 40, scale: 0.95 }}
411 transition={{ type: 'spring', stiffness: 300, damping: 25 }}
412 className="fixed bottom-0 right-0 md:bottom-6 md:right-6 z-[700] w-full md:w-[440px] h-[85vh] md:h-[680px] md:max-h-[85vh] flex flex-col md:rounded-2xl overflow-hidden"
413 style={{
414 background: 'linear-gradient(180deg, rgba(8, 10, 20, 0.96) 0%, rgba(6, 6, 12, 0.98) 100%)',
415 border: '1px solid rgba(212, 175, 55, 0.2)',
416 boxShadow:
417 '0 0 60px rgba(0, 0, 0, 0.8), 0 0 30px rgba(212, 175, 55, 0.08), 0 1px 0 rgba(212, 175, 55, 0.1) inset',
418 backdropFilter: 'blur(40px) saturate(1.5)',
419 }}
420 >
421 {/* ── Header ── */}
422 <div
423 className="relative flex items-center justify-between px-4 py-3 shrink-0"
424 style={{
425 background: 'linear-gradient(90deg, rgba(212, 175, 55, 0.06) 0%, transparent 50%, rgba(0, 229, 255, 0.04) 100%)',
426 borderBottom: '1px solid rgba(212, 175, 55, 0.15)',
427 }}
428 >
429 {/* Scan line accent */}
430 <motion.div
431 className="absolute bottom-0 left-0 right-0 h-[1px]"
432 style={{ background: 'linear-gradient(90deg, transparent, var(--gold-primary), transparent)' }}
433 animate={{ opacity: [0.3, 0.7, 0.3] }}
434 transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }}
435 />
436
437 <div className="flex items-center gap-2.5">
438 <div className="relative">
439 <Shield className="w-4.5 h-4.5 text-[var(--gold-primary)]" />
440 <div className="absolute -top-0.5 -right-0.5 w-1.5 h-1.5 rounded-full bg-[var(--alert-green)] animate-osiris-pulse" />
441 </div>
442 <div className="flex flex-col">
443 <span className="hud-text text-[11px] text-[var(--text-heading)]">OSIRIS ANALYST</span>
444 <span className="text-[7px] font-mono tracking-[0.2em] text-[var(--text-muted)]">
445 GEMINI 2.0 FLASH • ONLINE
446 </span>
447 </div>
448 </div>
449
450 <div className="flex items-center gap-1">
451 {messages.length > 0 && (
452 <button
453 onClick={clearMessages}
454 className="p-1.5 rounded-lg hover:bg-[var(--hover-accent)] transition-colors group"
455 title="Clear conversation"
456 >
457 <Trash2 className="w-3.5 h-3.5 text-[var(--text-muted)] group-hover:text-[var(--alert-red)]" />
458 </button>
459 )}
460 <button
461 onClick={() => setShowSettings(!showSettings)}
462 className="p-1.5 rounded-lg hover:bg-[var(--hover-accent)] transition-colors group"
463 title="Settings"
464 >
465 <Settings
466 className={`w-3.5 h-3.5 transition-colors ${
467 showSettings ? 'text-[var(--gold-primary)]' : 'text-[var(--text-muted)] group-hover:text-[var(--text-primary)]'
468 }`}
469 />
470 </button>
471 <button
472 onClick={() => setIsOpen(false)}
473 className="p-1.5 rounded-lg hover:bg-[var(--hover-accent)] transition-colors group"
474 title="Close"
475 >
476 <X className="w-3.5 h-3.5 text-[var(--text-muted)] group-hover:text-[var(--text-primary)]" />
477 </button>
478 </div>
479 </div>
480
481 {/* ── Settings Panel ── */}
482 <AnimatePresence>
483 {showSettings && (
484 <motion.div
485 initial={{ height: 0, opacity: 0 }}
486 animate={{ height: 'auto', opacity: 1 }}
487 exit={{ height: 0, opacity: 0 }}
488 transition={{ duration: 0.2 }}
489 className="overflow-hidden shrink-0"
490 >
491 <div
492 className="px-4 py-3 space-y-2.5"
493 style={{
494 background: 'rgba(212, 175, 55, 0.03)',
495 borderBottom: '1px solid rgba(212, 175, 55, 0.1)',
496 }}
497 >
498 <div className="flex items-center gap-2">
499 <Key className="w-3 h-3 text-[var(--gold-dim)]" />
500 <span className="hud-label" style={{ fontSize: '8px' }}>
501 GEMINI API KEY (OPTIONAL)
502 </span>
503 </div>
504 <div className="flex gap-2">
505 <input
506 type="password"
507 value={apiKeyInput}
508 onChange={(e) => {
509 setApiKeyInput(e.target.value);
510 setKeySaved(false);
511 }}
512 placeholder="AIza..."
513 className="flex-1 bg-[var(--bg-tertiary)] border border-[var(--border-secondary)] rounded-lg px-3 py-2 text-[11px] font-mono text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:outline-none focus:border-[var(--gold-dim)] transition-colors"
514 />
515 {apiKeyInput.trim() && (
516 <>
517 <button
518 onClick={saveApiKey}
519 className="px-3 rounded-lg text-[9px] font-mono tracking-wider transition-all"
520 style={{
521 background: keySaved ? 'rgba(0, 230, 118, 0.15)' : 'rgba(212, 175, 55, 0.1)',
522 border: `1px solid ${keySaved ? 'rgba(0, 230, 118, 0.3)' : 'rgba(212, 175, 55, 0.2)'}`,
523 color: keySaved ? 'var(--alert-green)' : 'var(--gold-primary)',
524 }}
525 >
526 {keySaved ? <Check className="w-3 h-3" /> : 'SAVE'}
527 </button>
528 <button
529 onClick={clearApiKey}
530 className="px-2 rounded-lg text-[9px] font-mono tracking-wider transition-all hover:bg-red-500/10"
531 style={{
532 border: '1px solid rgba(255, 61, 61, 0.2)',
533 color: 'var(--alert-red)',
534 }}
535 >
536 <X className="w-3 h-3" />
537 </button>
538 </>
539 )}
540 </div>
541 <p className="text-[8px] font-mono text-[var(--text-muted)] leading-relaxed">
542 Your key is stored locally and sent only to the OSIRIS server. Get a free key at{' '}
543 <a
544 href="https://aistudio.google.com/apikey"
545 target="_blank"
546 rel="noopener noreferrer"
547 className="text-[var(--cyan-primary)] hover:underline"
548 >
549 aistudio.google.com
550 </a>
551 </p>
552 </div>
553 </motion.div>
554 )}
555 </AnimatePresence>
556
557 {/* ── Messages Area ── */}
558 <div className="flex-1 overflow-y-auto styled-scrollbar px-4 py-3 space-y-3">
559 {/* Empty state */}
560 {messages.length === 0 && !isLoading && (
561 <div className="h-full flex flex-col items-center justify-center text-center px-6 gap-5">
562 {/* Animated brain icon */}
563 <div className="relative">
564 <motion.div
565 animate={{ rotate: [0, 360] }}
566 transition={{ duration: 20, repeat: Infinity, ease: 'linear' }}
567 className="absolute inset-[-10px] rounded-full border border-[var(--gold-primary)]"
568 style={{ opacity: 0.15 }}
569 />
570 <motion.div
571 animate={{ rotate: [0, -360] }}
572 transition={{ duration: 14, repeat: Infinity, ease: 'linear' }}
573 className="absolute inset-[-20px] rounded-full border border-[var(--cyan-primary)]"
574 style={{ opacity: 0.08 }}
575 />
576 <div
577 className="w-16 h-16 rounded-2xl flex items-center justify-center"
578 style={{
579 background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.1) 0%, rgba(0, 229, 255, 0.05) 100%)',
580 border: '1px solid rgba(212, 175, 55, 0.2)',
581 }}
582 >
583 <Brain className="w-7 h-7 text-[var(--gold-primary)]" />
584 </div>
585 </div>
586
587 <div className="space-y-2">
588 <h3 className="hud-text text-[12px] text-[var(--text-heading)]">
589 INTELLIGENCE ANALYST READY
590 </h3>
591 <p className="text-[10px] font-mono text-[var(--text-muted)] leading-relaxed max-w-[280px]">
592 I correlate live seismic, OSINT, threat, and cyber data to deliver actionable intelligence assessments.
593 </p>
594 </div>
595
596 {/* Quick prompts */}
597 <div className="w-full space-y-1.5">
598 <span className="hud-label block text-center mb-2" style={{ fontSize: '7px' }}>
599 SUGGESTED QUERIES
600 </span>
601 {[
602 'What are the top 3 threats right now?',
603 'Are there seismic patterns correlating with conflicts?',
604 'Assess cyber risks to critical infrastructure',
605 ].map((prompt) => (
606 <button
607 key={prompt}
608 onClick={() => {
609 setInputText(prompt);
610 setTimeout(() => inputRef.current?.focus(), 50);
611 }}
612 className="w-full text-left px-3 py-2 rounded-lg text-[10px] font-mono text-[var(--text-secondary)] transition-all hover:text-[var(--text-primary)] hover:bg-[var(--hover-accent)]"
613 style={{
614 border: '1px solid rgba(212, 175, 55, 0.08)',
615 }}
616 >
617 <span className="text-[var(--gold-dim)] mr-1.5">›</span>
618 {prompt}
619 </button>
620 ))}
621 </div>
622 </div>
623 )}
624
625 {/* Messages */}
626 {messages.map((msg) => (
627 <motion.div
628 key={msg.id}
629 initial={{ opacity: 0, y: 10 }}
630 animate={{ opacity: 1, y: 0 }}
631 transition={{ duration: 0.3 }}
632 className={`flex ${msg.role === 'user' ? 'justify-end' : 'justify-start'}`}
633 >
634 <div
635 className={`max-w-[90%] rounded-xl px-3.5 py-2.5 ${
636 msg.role === 'user' ? 'rounded-br-sm' : 'rounded-bl-sm'
637 }`}
638 style={
639 msg.role === 'user'
640 ? {
641 background: 'linear-gradient(135deg, rgba(0, 229, 255, 0.12) 0%, rgba(0, 229, 255, 0.06) 100%)',
642 border: '1px solid rgba(0, 229, 255, 0.2)',
643 }
644 : msg.isError
645 ? {
646 background: 'linear-gradient(135deg, rgba(255, 61, 61, 0.1) 0%, rgba(255, 61, 61, 0.05) 100%)',
647 border: '1px solid rgba(255, 61, 61, 0.2)',
648 }
649 : {
650 background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.08) 0%, rgba(212, 175, 55, 0.03) 100%)',
651 border: '1px solid rgba(212, 175, 55, 0.12)',
652 }
653 }
654 >
655 {/* Message header */}
656 <div className="flex items-center gap-1.5 mb-1.5">
657 {msg.role === 'user' ? (
658 <User className="w-3 h-3 text-[var(--cyan-primary)]" />
659 ) : msg.isError ? (
660 <AlertTriangle className="w-3 h-3 text-[var(--alert-red)]" />
661 ) : (
662 <Bot className="w-3 h-3 text-[var(--gold-primary)]" />
663 )}
664 <span
665 className="text-[8px] font-mono tracking-[0.15em] uppercase"
666 style={{
667 color: msg.role === 'user'
668 ? 'var(--cyan-primary)'
669 : msg.isError
670 ? 'var(--alert-red)'
671 : 'var(--gold-primary)',
672 }}
673 >
674 {msg.role === 'user' ? 'OPERATOR' : 'OSIRIS ANALYST'}
675 </span>
676 <span className="text-[7px] font-mono text-[var(--text-muted)] ml-auto">
677 {new Date(msg.timestamp).toLocaleTimeString([], {
678 hour: '2-digit',
679 minute: '2-digit',
680 })}
681 </span>
682 </div>
683
684 {/* Message content */}
685 {msg.role === 'analyst' && !msg.isError ? (
686 <div
687 className="text-[11px] font-mono text-[var(--text-primary)] leading-relaxed whitespace-pre-wrap break-words"
688 dangerouslySetInnerHTML={{ __html: renderMarkdown(msg.content) }}
689 />
690 ) : (
691 <p className="text-[11px] font-mono text-[var(--text-primary)] leading-relaxed whitespace-pre-wrap break-words">
692 {msg.content}
693 </p>
694 )}
695 </div>
696 </motion.div>
697 ))}
698
699 {/* Loading indicator */}
700 {isLoading && (
701 <motion.div
702 initial={{ opacity: 0, y: 10 }}
703 animate={{ opacity: 1, y: 0 }}
704 className="flex justify-start"
705 >
706 <div
707 className="rounded-xl rounded-bl-sm px-4 py-3 flex items-center gap-2.5"
708 style={{
709 background: 'linear-gradient(135deg, rgba(212, 175, 55, 0.08) 0%, rgba(212, 175, 55, 0.03) 100%)',
710 border: '1px solid rgba(212, 175, 55, 0.12)',
711 }}
712 >
713 <Loader2 className="w-3.5 h-3.5 text-[var(--gold-primary)] animate-spin" />
714 <div className="flex items-center gap-1">
715 <span className="text-[9px] font-mono tracking-[0.15em] text-[var(--gold-primary)] uppercase">
716 Analyzing intelligence
717 </span>
718 <motion.span
719 animate={{ opacity: [0, 1, 0] }}
720 transition={{ duration: 1.5, repeat: Infinity }}
721 className="text-[var(--gold-primary)]"
722 >
723 ...
724 </motion.span>
725 </div>
726 </div>
727 </motion.div>
728 )}
729
730 <div ref={messagesEndRef} />
731 </div>
732
733 {/* ── Input Area ── */}
734 <div
735 className="shrink-0 px-3 py-2.5"
736 style={{
737 borderTop: '1px solid rgba(212, 175, 55, 0.1)',
738 background: 'rgba(6, 6, 12, 0.8)',
739 }}
740 >
741 {/* Quick action */}
742 <div className="flex gap-2 mb-2">
743 <button
744 onClick={handleBriefing}
745 disabled={isLoading}
746 className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[9px] font-mono tracking-[0.1em] uppercase transition-all disabled:opacity-40"
747 style={{
748 background: 'rgba(212, 175, 55, 0.08)',
749 border: '1px solid rgba(212, 175, 55, 0.2)',
750 color: 'var(--gold-primary)',
751 }}
752 >
753 <Sparkles className="w-3 h-3" />
754 GENERATE BRIEFING
755 </button>
756 <div className="flex-1" />
757 <span className="flex items-center text-[7px] font-mono text-[var(--text-muted)] tracking-wider">
758 <ChevronDown className="w-2.5 h-2.5 mr-0.5" />
759 SHIFT+ENTER FOR NEWLINE
760 </span>
761 </div>
762
763 {/* Input row */}
764 <div className="flex gap-2 items-end">
765 <div
766 className="flex-1 rounded-xl overflow-hidden transition-colors"
767 style={{
768 background: 'var(--bg-tertiary)',
769 border: '1px solid rgba(212, 175, 55, 0.1)',
770 }}
771 >
772 <textarea
773 ref={inputRef}
774 value={inputText}
775 onChange={(e) => setInputText(e.target.value)}
776 onKeyDown={handleKeyDown}
777 placeholder="Query the intelligence analyst..."
778 rows={1}
779 className="w-full bg-transparent px-3 py-2.5 text-[11px] font-mono text-[var(--text-primary)] placeholder:text-[var(--text-muted)] focus:outline-none resize-none"
780 style={{ maxHeight: '120px', minHeight: '36px' }}
781 disabled={isLoading}
782 onInput={(e) => {
783 const target = e.target as HTMLTextAreaElement;
784 target.style.height = 'auto';
785 target.style.height = Math.min(target.scrollHeight, 120) + 'px';
786 }}
787 />
788 </div>
789
790 <motion.button
791 whileHover={{ scale: 1.05 }}
792 whileTap={{ scale: 0.95 }}
793 onClick={handleSend}
794 disabled={!inputText.trim() || isLoading}
795 className="shrink-0 w-9 h-9 rounded-xl flex items-center justify-center transition-all disabled:opacity-30"
796 style={{
797 background:
798 inputText.trim() && !isLoading
799 ? 'linear-gradient(135deg, rgba(0, 229, 255, 0.2) 0%, rgba(0, 229, 255, 0.1) 100%)'
800 : 'rgba(255, 255, 255, 0.03)',
801 border: `1px solid ${
802 inputText.trim() && !isLoading ? 'rgba(0, 229, 255, 0.3)' : 'rgba(255, 255, 255, 0.06)'
803 }`,
804 }}
805 >
806 <Send
807 className="w-3.5 h-3.5"
808 style={{
809 color: inputText.trim() && !isLoading ? 'var(--cyan-primary)' : 'var(--text-muted)',
810 }}
811 />
812 </motion.button>
813 </div>
814
815 {/* Footer */}
816 <div className="flex items-center justify-between mt-1.5 px-1">
817 <span className="text-[7px] font-mono text-[var(--text-muted)] tracking-wider">
818 {keySaved ? '🔑 CUSTOM KEY' : '🔧 SERVER KEY'} • {messages.filter((m) => m.role === 'user').length} QUERIES
819 </span>
820 <span className="text-[7px] font-mono text-[var(--text-muted)] tracking-wider">
821 FEEDS: {(data.earthquakes?.length || 0) + (data.news?.length || 0) + (data.gdelt?.length || 0)} ITEMS
822 </span>
823 </div>
824 </div>
825 </motion.div>
826 </>
827 )}
828 </AnimatePresence>
829 </>
830 );
831}