File size: 31,043 Bytes
dc436d6
6df60a2
17b60d4
d27a461
17b60d4
 
 
 
98e205f
463943e
 
ce0ea5d
d27a461
 
17b60d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef213b3
 
d27a461
fbe8e04
 
17b60d4
d27a461
17b60d4
dc436d6
 
 
98e205f
 
 
 
 
 
 
 
 
 
dc436d6
 
 
 
 
 
 
 
 
ef213b3
1773826
 
 
98e205f
ef213b3
98e205f
fbe8e04
 
ef213b3
 
fbe8e04
98e205f
fbe8e04
 
 
 
 
98e205f
6df60a2
ef213b3
98e205f
 
 
 
 
 
 
 
 
 
 
1773826
98e205f
 
 
 
ef213b3
98e205f
 
 
ef213b3
e53ab95
 
98e205f
e53ab95
 
 
1773826
 
 
 
 
 
 
dc436d6
 
17b60d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dc436d6
17b60d4
dc436d6
17b60d4
 
 
 
d27a461
17b60d4
ef213b3
dc436d6
 
 
 
 
17b60d4
 
 
 
 
1773826
17b60d4
1773826
17b60d4
 
 
 
 
 
1773826
17b60d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbe8e04
98e205f
fbe8e04
 
 
 
 
 
ef213b3
98e205f
 
17b60d4
 
 
 
 
ef213b3
98e205f
 
 
 
 
 
 
17b60d4
 
 
 
 
 
 
 
 
fbe8e04
 
 
 
 
17b60d4
fbe8e04
 
17b60d4
 
 
 
 
 
 
dc436d6
17b60d4
 
dc436d6
17b60d4
 
dc436d6
17b60d4
 
 
 
 
 
463943e
 
 
 
 
e30da63
463943e
 
 
 
ef213b3
463943e
 
 
 
 
 
 
17b60d4
98e205f
 
ce0ea5d
17b60d4
 
 
 
 
 
 
 
dc436d6
 
ef213b3
dc436d6
 
 
 
 
 
 
ef213b3
dc436d6
 
 
 
 
 
 
17b60d4
 
dc436d6
17b60d4
 
 
 
 
 
 
 
ef213b3
 
 
9bffd74
ef213b3
9bffd74
17b60d4
 
98e205f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef213b3
98e205f
 
 
 
 
ef213b3
98e205f
 
 
 
 
 
 
 
ef213b3
98e205f
 
 
 
 
 
 
 
 
 
 
ef213b3
 
98e205f
 
ef213b3
98e205f
 
 
 
 
 
 
 
 
 
 
 
ef213b3
98e205f
 
 
 
 
 
 
 
 
 
 
ef213b3
98e205f
 
 
 
 
 
 
 
 
 
 
 
ef213b3
98e205f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ef213b3
98e205f
 
 
 
 
ef213b3
98e205f
9fda4b9
 
1b1fb7e
 
9fda4b9
 
ef213b3
 
 
9fda4b9
 
6aefcc0
ef213b3
9fda4b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1b1fb7e
9fda4b9
 
 
 
 
 
 
98e205f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b60d4
 
 
 
 
 
 
 
 
 
 
 
 
dc436d6
17b60d4
 
dc436d6
17b60d4
 
1b1fb7e
 
 
 
 
 
 
 
 
 
 
 
17b60d4
d27a461
 
 
ef213b3
d27a461
 
 
ef213b3
 
 
 
 
 
d27a461
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17b60d4
ef213b3
d27a461
 
 
 
 
 
 
fbe8e04
d27a461
 
 
 
 
 
 
 
 
 
 
 
 
17b60d4
 
 
 
 
 
 
 
 
 
 
 
ce0ea5d
17b60d4
 
ce0ea5d
ef213b3
ce0ea5d
 
 
17b60d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
import React, { useState, useEffect } from 'react';
import { ChevronDown, Plus, Info, MessageSquare, BookOpen, LogOut, PanelLeftClose, MessageCircle, Menu, PanelRightClose, RefreshCw } from 'lucide-react';
import SimulationGraph from './SimulationGraph';
import { GradioService } from '../services/gradioService';

interface SimulationPageProps {
  onBack: () => void;
  onOpenChat: () => void;
  onOpenGuide: () => void;
  user?: any;
  onLogin?: () => void;
  onLogout?: () => void;
  simulationResult: any;
  setSimulationResult: (res: any) => void;
}

// Define the data structure for filters
const VIEW_FILTERS: Record<string, Array<{ label: string; color: string }>> = {
  'Country': [
    { label: "United States", color: "bg-blue-600" },
    { label: "United Kingdom", color: "bg-purple-600" },
    { label: "Netherlands", color: "bg-teal-600" },
    { label: "France", color: "bg-orange-600" },
    { label: "India", color: "bg-pink-600" }
  ],
  'Job Title': [
    { label: "Founder", color: "bg-indigo-500" },
    { label: "Product Manager", color: "bg-emerald-500" },
    { label: "Engineer", color: "bg-rose-500" },
    { label: "Investor", color: "bg-amber-500" },
    { label: "Designer", color: "bg-fuchsia-500" }
  ],
  'Sentiment': [
    { label: "Positive", color: "bg-green-500" },
    { label: "Neutral", color: "bg-gray-500" },
    { label: "Negative", color: "bg-red-500" },
    { label: "Mixed", color: "bg-yellow-500" }
  ],
  'Activity Level': [
    { label: "Power User", color: "bg-red-600" },
    { label: "Daily Active", color: "bg-orange-500" },
    { label: "Weekly Active", color: "bg-blue-500" },
    { label: "Lurker", color: "bg-slate-600" }
  ]
};

const SimulationPage: React.FC<SimulationPageProps> = ({
  onBack, onOpenChat, onOpenGuide, user, onLogin, onLogout, simulationResult, setSimulationResult
}) => {
  const [society, setSociety] = useState('');
  const [societies, setSocieties] = useState<string[]>([]);
  const [viewMode, setViewMode] = useState('Job Title');
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isBuilding, setIsBuilding] = useState(false);
  const [isRightPanelOpen, setIsRightPanelOpen] = useState(window.innerWidth > 1200);
  const [isLeftPanelOpen, setIsLeftPanelOpen] = useState(window.innerWidth > 768);

  const [activeModal, setActiveModal] = useState<'none' | 'assemble' | 'feedback' | 'context' | 'test'>('none');
  const [formData, setFormData] = useState({
    customerProfile: '',
    companyInfo: '',
    personaScale: 50,
    feedback: '',
    context: '',
    testName: ''
  });

  // Handle window resize for mobile responsiveness
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth < 768) {
        setIsLeftPanelOpen(false);
        setIsRightPanelOpen(false);
      }
    };
    window.addEventListener('resize', handleResize);

    // Fetch real focus groups
    const fetchSocieties = async () => {
        try {
            let names: string[] = [];

            // 1. Fetch from Gradio (Templates/Global)
            const result = await GradioService.listSimulations();
            const list = Array.isArray(result) ? result : (result?.data?.[0] || []);
            // GradioService now returns the array of focus group objects directly

            if (Array.isArray(list)) {
                const gradioNames = list
                    .map((s: any) => {
                        if (typeof s === 'string') return s;
                        if (typeof s === 'object' && s !== null) return s.id || s.name || '';
                        return '';
                    })
                    // Filter out non-user groups as requested
                    .filter(name => name.length > 0 && !name.toLowerCase().includes('default') && !name.toLowerCase().includes('template') && !name.toLowerCase().includes('current'));

                names = [...gradioNames];
            }

            // 2. Fetch User-created groups from local storage
            if (user?.preferred_username) {
              try {
                const localResp = await fetch(`/api/list-data?type=assemble&user=${user.preferred_username}`);
                if (localResp.ok) {
                  const localData = await localResp.json();
                  const localNames = localData.map((d: any) => d.data.customerProfile.substring(0, 20) + '...');
                  names = [...names, ...localNames];
                }
              } catch (e) {
                console.error("Failed to fetch local groups", e);
              }
            }

            // Remove duplicates
            const uniqueNames = Array.from(new Set(names));
            setSocieties(uniqueNames);

            if (uniqueNames.length > 0) {
              if (!society || !uniqueNames.includes(society)) {
                setSociety(uniqueNames[0]);
              }
            } else {
              setSociety('Standard Example');
            }
        } catch (e) {
            console.error("Failed to fetch focus groups", e);
        }
    };
    fetchSocieties();

    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Function to simulate rebuilding the graph when settings change
  const handleSettingChange = (setter: (val: string) => void, value: string) => {
    if (value === society || (value === viewMode && setter === setViewMode)) return; // No change
    
    setter(value);
    setIsBuilding(true);
    // Simulate network delay
    setTimeout(() => {
        setIsBuilding(false);
    }, 1500);
  };

  const currentFilters = VIEW_FILTERS[viewMode] || VIEW_FILTERS['Country'];

  return (
    <div className="flex h-screen w-screen overflow-hidden bg-black text-white font-sans relative">
      {/* Sidebar */}
      <aside className={`fixed md:relative w-[300px] h-full flex-shrink-0 border-r border-gray-800 flex flex-col bg-[#0a0a0a] z-40 transition-all duration-300 ${isLeftPanelOpen ? 'translate-x-0' : '-translate-x-full md:-ml-[300px]'}`}>
        {/* Header */}
        <div className="p-4 h-16 border-b border-gray-800 flex items-center justify-between">
           <div className="flex items-center gap-2 cursor-pointer" onClick={onBack}>
              <div className="w-6 h-6 flex items-center justify-center font-bold text-white">Λ</div>
              <span className="font-semibold tracking-tight text-xs">Branding Content Testing</span>
           </div>
           <button
             onClick={() => setIsLeftPanelOpen(false)}
             className="text-gray-500 hover:text-white"
           >
             <PanelLeftClose size={18}/>
           </button>
        </div>

        {/* Scrollable Content */}
        <div className="flex-1 overflow-y-auto p-4 space-y-6">
           
           {/* Focus Group Control */}
           <div className="space-y-2">
              <label className="text-xs text-gray-500 font-medium uppercase tracking-wider">Focus Group</label>
              <div className="relative group">
                <select 
                  value={society}
                  onChange={(e) => handleSettingChange(setSociety, e.target.value)}
                  className="w-full appearance-none bg-[#111] border border-gray-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-teal-500 cursor-pointer"
                >
                  {societies.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
                <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none w-4 h-4" />
              </div>
           </div>

           {/* Current View Control */}
           <div className="space-y-2">
              <label className="text-xs text-gray-500 font-medium uppercase tracking-wider">Current View</label>
              <div className="relative">
                <select 
                  value={viewMode}
                  onChange={(e) => handleSettingChange(setViewMode, e.target.value)}
                  className="w-full appearance-none bg-[#111] border border-gray-700 text-white rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:border-teal-500 cursor-pointer"
                >
                  <option>Country</option>
                  <option>Job Title</option>
                  <option>Sentiment</option>
                  <option>Activity Level</option>
                </select>
                <ChevronDown className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 pointer-events-none w-4 h-4" />
              </div>
           </div>

           <div className="h-px bg-gray-800 my-4" />

           {/* Actions */}
           <button 
             onClick={() => setActiveModal('assemble')}
             className="w-full flex items-center justify-between text-left text-sm text-gray-300 hover:text-white group py-2 border-b border-gray-800/50 mb-1"
           >
              <span>Assemble new group</span>
              <Plus size={18} className="text-gray-500 group-hover:text-white" />
           </button>

           <button
             onClick={() => setActiveModal('test')}
             className="w-full flex items-center justify-between text-left text-sm text-gray-300 hover:text-white group py-2 border-b border-gray-800/50 mb-1"
           >
              <span>Create a new test</span>
              <Plus size={18} className="text-gray-500 group-hover:text-white" />
           </button>

           <button
             onClick={() => setActiveModal('context')}
             className="w-full flex items-center justify-between text-left text-sm text-gray-300 hover:text-white group py-2"
           >
              <span>Request new context</span>
              <Plus size={18} className="text-gray-500 group-hover:text-white" />
           </button>

           {/* Global Chat Button (Sidebar) */}
           <button 
             onClick={onOpenChat}
             className="w-full flex items-center gap-3 px-4 py-3 bg-gray-800 hover:bg-gray-700 text-white rounded-lg transition-colors border border-gray-700"
           >
              <MessageCircle size={18} />
              <span className="font-medium text-sm">Open Global Chat</span>
           </button>

           {/* Setup Warning / Info Box */}
           <div className="bg-blue-900/30 border border-blue-700/50 rounded-xl p-4 mt-4">
              <div className="flex items-center gap-2 text-blue-200 font-bold text-xs mb-1">
                 <Info size={14}/>
                 <span>Configuration Required</span>
              </div>
              <p className="text-blue-200/70 text-[10px] leading-relaxed">
                Assemble new group and create a new test are required to be configured first before using any chat.
              </p>
           </div>

           {/* History List */}
           <div className="space-y-1 pt-4">
             <label className="text-xs text-gray-500 font-medium uppercase tracking-wider mb-2 block">Recent Tests</label>
             <div className="text-sm text-gray-400 py-2 px-2 hover:bg-gray-800/50 rounded cursor-pointer truncate">
               Sustainable Luxury Narrative
             </div>
             <div className="text-sm text-gray-400 py-2 px-2 hover:bg-gray-800/50 rounded cursor-pointer truncate">
               Radical Transparency Voice
             </div>
             <div className="text-sm text-gray-400 py-2 px-2 hover:bg-gray-800/50 rounded cursor-pointer truncate">
               Gen-Z Greenwash Perception
             </div>
           </div>
        </div>

        {/* Footer */}
        <div className="border-t border-gray-800 p-4 space-y-1 bg-[#0a0a0a]">
           {user ? (
             <div className="flex items-center gap-3 py-3 border-b border-gray-800 mb-2">
                {user.avatarUrl && <img src={user.avatarUrl} alt={user.preferred_username} className="w-8 h-8 rounded-full border border-gray-700" />}
                <div className="flex flex-col">
                  <span className="text-xs font-semibold text-gray-200">{user.preferred_username}</span>
                  <span className="text-[10px] text-gray-500">Credits: Unlimited</span>
                </div>
             </div>
           ) : (
             <div className="py-2 border-b border-gray-800 mb-2">
                <button
                  onClick={onLogin}
                  className="w-full py-2 bg-white text-black rounded-lg text-xs font-bold hover:bg-gray-200 transition-colors"
                >
                  Sign in with Hugging Face
                </button>
             </div>
           )}

           <MenuItem icon={<MessageSquare size={16}/>} label="Leave Feedback" onClick={() => setActiveModal('feedback')} />
           <MenuItem icon={<BookOpen size={16}/>} label="Product Guide" onClick={onOpenGuide} />
           {user && <MenuItem icon={<LogOut size={16}/>} label="Log Out" onClick={onLogout} />}
           
           <div className="pt-4 text-[10px] text-gray-600">Version 2.1</div>
        </div>
      </aside>

      {/* Main Content Area */}
      <main className="flex-1 flex flex-col relative bg-black overflow-hidden">
         {/* Top Navigation Overlay */}
         <div className="absolute top-4 left-4 right-4 z-30 flex justify-between items-center pointer-events-none">
             {/* Left Toggle (when sidebar closed) */}
             <button
               onClick={() => setIsLeftPanelOpen(true)}
               className={`pointer-events-auto p-2 bg-gray-900/80 border border-gray-700 rounded-lg text-gray-400 hover:text-white transition-opacity ${isLeftPanelOpen ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}
             >
                <Menu size={20} />
             </button>

             {/* Right Toggle (when output closed) */}
             <button
               onClick={() => setIsRightPanelOpen(true)}
               className={`pointer-events-auto p-2 bg-gray-900/80 border border-gray-700 rounded-lg text-gray-400 hover:text-white transition-opacity ml-auto ${isRightPanelOpen ? 'opacity-0 pointer-events-none' : 'opacity-100'}`}
             >
                <PanelRightClose size={20} className="rotate-180" />
             </button>
         </div>

         <div className="absolute top-6 left-6 right-6 z-10 flex justify-center pointer-events-none">
             {/* Legend / Filter Chips */}
             <div className="flex flex-wrap justify-center gap-2 pointer-events-auto max-w-[60%]">
                {currentFilters.map((filter, idx) => (
                   <FilterChip key={idx} color={filter.color} label={filter.label} />
                ))}
             </div>
         </div>

         {/* Graph Container */}
         <div className="flex-1 w-full h-full">
            <SimulationGraph
              isBuilding={isBuilding}
              societyType={society}
              viewMode={viewMode}
              onStartChat={onOpenChat}
            />
         </div>

         {/* Modals */}
         {activeModal !== 'none' && (
           <div className="absolute inset-0 z-[60] flex items-center justify-center p-6 bg-black/60 backdrop-blur-sm">
             <div className="bg-[#111] border border-gray-800 rounded-2xl w-full max-w-md overflow-hidden shadow-2xl">
               <div className="p-6 border-b border-gray-800 flex items-center justify-between">
                 <h3 className="font-semibold text-lg">
                   {activeModal === 'assemble' && "Assemble New Group"}
                   {activeModal === 'feedback' && "Leave Feedback"}
                   {activeModal === 'context' && "Request New Context"}
                   {activeModal === 'test' && "Create New Test"}
                 </h3>
                 <button onClick={() => setActiveModal('none')} className="text-gray-500 hover:text-white">
                   <PanelRightClose size={20} />
                 </button>
               </div>

               <div className="p-6 space-y-4">
                 {activeModal === 'assemble' && (
                   <>
                     <div className="space-y-1.5">
                       <label className="text-xs text-gray-400 font-medium">Customer Profile</label>
                       <textarea
                         value={formData.customerProfile}
                         onChange={(e) => setFormData({...formData, customerProfile: e.target.value})}
                         className="w-full bg-black border border-gray-800 rounded-lg p-3 text-sm focus:border-teal-500 outline-none h-24 resize-none"
                         placeholder="Describe your ideal audience..."
                       />
                     </div>
                     <div className="space-y-1.5">
                       <label className="text-xs text-gray-400 font-medium">Company Info</label>
                       <textarea
                         value={formData.companyInfo}
                         onChange={(e) => setFormData({...formData, companyInfo: e.target.value})}
                         className="w-full bg-black border border-gray-800 rounded-lg p-3 text-sm focus:border-teal-500 outline-none h-24 resize-none"
                         placeholder="Tell us about your brand..."
                       />
                     </div>
                     <div className="space-y-1.5">
                       <div className="flex justify-between">
                         <label className="text-xs text-gray-400 font-medium">Persona Scale</label>
                         <span className="text-xs text-teal-500 font-bold">{formData.personaScale}</span>
                       </div>
                       <input
                         type="range" min="1" max="100"
                         value={formData.personaScale}
                         onChange={(e) => setFormData({...formData, personaScale: parseInt(e.target.value)})}
                         className="w-full accent-teal-500"
                       />
                       <div className="flex justify-between text-[10px] text-gray-600 uppercase font-bold">
                         <span>Conservative</span>
                         <span>Radical</span>
                       </div>
                     </div>
                   </>
                 )}

                 {activeModal === 'feedback' && (
                   <div className="space-y-1.5">
                     <label className="text-xs text-gray-400 font-medium">Your Feedback</label>
                     <textarea
                       value={formData.feedback}
                       onChange={(e) => setFormData({...formData, feedback: e.target.value})}
                       className="w-full bg-black border border-gray-800 rounded-lg p-3 text-sm focus:border-teal-500 outline-none h-40 resize-none"
                       placeholder="How can we improve?"
                     />
                   </div>
                 )}

                 {activeModal === 'context' && (
                   <div className="space-y-1.5">
                     <label className="text-xs text-gray-400 font-medium">New Context / Fuse Box</label>
                     <textarea
                       value={formData.context}
                       onChange={(e) => setFormData({...formData, context: e.target.value})}
                       className="w-full bg-black border border-gray-800 rounded-lg p-3 text-sm focus:border-teal-500 outline-none h-40 resize-none"
                       placeholder="Specify the testing environment or scenario..."
                     />
                   </div>
                 )}

                 {activeModal === 'test' && (
                   <>
                     <div className="space-y-1.5">
                       <label className="text-xs text-gray-400 font-medium">Test Name</label>
                       <input
                         type="text"
                         value={formData.testName}
                         onChange={(e) => setFormData({...formData, testName: e.target.value})}
                         className="w-full bg-black border border-gray-800 rounded-lg p-3 text-sm focus:border-teal-500 outline-none"
                         placeholder="Campaign Launch 2024..."
                       />
                     </div>
                     <div className="space-y-1.5">
                        <label className="text-xs text-gray-400 font-medium">Brand Asset for Testing</label>
                        <div className="flex items-center justify-center w-full">
                            <label className="flex flex-col items-center justify-center w-full h-32 border-2 border-gray-800 border-dashed rounded-lg cursor-pointer bg-black hover:bg-gray-900 transition-colors">
                                <div className="flex flex-col items-center justify-center pt-5 pb-6">
                                    <Plus className="w-8 h-8 mb-4 text-gray-500" />
                                    <p className="mb-2 text-sm text-gray-500"><span className="font-semibold">Click to upload</span> or drag and drop</p>
                                    <p className="text-xs text-gray-500">SVG, PNG, JPG (MAX. 800x400px)</p>
                                </div>
                                <input type="file" className="hidden" multiple accept="image/*" />
                            </label>
                        </div>
                     </div>
                   </>
                 )}
               </div>

               <div className="p-6 border-t border-gray-800 flex gap-3">
                 <button
                   onClick={() => setActiveModal('none')}
                   className="flex-1 py-2.5 rounded-xl border border-gray-800 text-sm font-medium hover:bg-gray-900 transition-colors"
                 >
                   Cancel
                 </button>
                 <button
                   onClick={async () => {
                     if (activeModal === 'assemble') {
                       setIsBuilding(true);
                       setIsRightPanelOpen(true);
                       setActiveModal('none');
                       try {
                         // 1. Generate personas based on profile and company info
                         const jobRes = await GradioService.generatePersonas(formData.companyInfo, formData.customerProfile, Math.ceil(formData.personaScale / 20));
                         const personas = [jobRes.job_id];

                         // 2. Generate social network for these personas
                         const groupName = formData.customerProfile.substring(0, 20);
                         await GradioService.generateSocialNetwork(groupName, formData.personaScale, 'scale_free', groupName);

                         // 3. Save to backend
                         await fetch('/api/save-data', {
                           method: 'POST',
                           headers: { 'Content-Type': 'application/json' },
                           body: JSON.stringify({
                             type: 'assemble',
                             data: { ...formData, generatedPersonas: personas },
                             user: user?.preferred_username || 'anonymous'
                           })
                         });

                         // 4. Update UI
                         setSocieties(prev => [groupName, ...prev]);
                         setSociety(groupName);
                         alert('Focus group assembled and selected!');
                       } catch (e) {
                         console.error(e);
                         alert('Failed to assemble group via API.');
                       } finally {
                         setIsBuilding(false);
                       }
                       return;
                     }

                     // Save to backend logic for other modals
                     try {
                        const response = await fetch('/api/save-data', {
                          method: 'POST',
                          headers: { 'Content-Type': 'application/json' },
                          body: JSON.stringify({
                            type: activeModal,
                            data: formData,
                            user: user?.preferred_username || 'anonymous'
                          })
                        });
                        if (response.ok) {
                          alert('Successfully saved!');
                          setActiveModal('none');
                        }
                     } catch (e) {
                       console.error(e);
                       alert('Successfully submitted (Local simulation)');
                       setActiveModal('none');
                     }
                   }}
                   className="flex-1 py-2.5 rounded-xl bg-teal-600 text-white text-sm font-bold hover:bg-teal-500 transition-colors shadow-lg shadow-teal-900/20"
                 >
                   Confirm
                 </button>
               </div>
             </div>
           </div>
         )}

         {/* Floating Chat Button (Bottom) */}
         <div className="absolute bottom-8 left-1/2 -translate-x-1/2 z-30">
            <button 
              onClick={onOpenChat}
              className="flex items-center gap-2 bg-black/80 backdrop-blur-md border border-gray-700 text-white px-6 py-3 rounded-full shadow-2xl hover:bg-gray-900 transition-all hover:scale-105"
            >
              <MessageCircle size={20} />
              <span className="font-medium">Open Simulation Chat</span>
            </button>
         </div>
      </main>

      {/* Right Sidebar (Output) */}
      <aside className={`fixed right-0 md:relative w-[300px] h-full flex-shrink-0 border-l border-gray-800 flex flex-col bg-[#0a0a0a] z-40 transition-all duration-300 ${isRightPanelOpen ? 'translate-x-0' : 'translate-x-full md:-mr-[300px]'}`}>
        <div className="p-4 h-16 border-b border-gray-800 flex items-center justify-between">
           <span className="font-semibold tracking-tight uppercase text-xs text-gray-500">Output</span>
           <button onClick={() => setIsRightPanelOpen(false)} className="text-gray-500 hover:text-white"><PanelRightClose size={18}/></button>
        </div>
        <div className="flex-1 overflow-y-auto p-4 space-y-4">
           {isBuilding && (
             <div className="bg-teal-900/20 border border-teal-500/30 rounded-xl p-4 mb-4 animate-in fade-in slide-in-from-top-2">
                <div className="flex items-center gap-3">
                   <RefreshCw className="w-4 h-4 text-teal-400 animate-spin" />
                   <div className="flex flex-col">
                      <span className="text-xs font-bold text-teal-400">Assembling...</span>
                      <span className="text-[10px] text-teal-400/60 font-mono">Constructing network mesh</span>
                   </div>
                </div>
             </div>
           )}

           <div className="bg-gray-900/50 border border-gray-800 rounded-xl p-4">
              <div className="flex items-center justify-between mb-2">
                <p className="text-xs text-gray-500">Simulation Results</p>
                {simulationResult && (
                  <button
                    onClick={async () => {
                      setIsRefreshing(true);
                      try {
                        // In SimulationPage we don't track the running simulation's job ID.
                        // To get the status, we would need the job ID returned by startSimulation.
                        // If we are polling for the group assembly job, we might need to store it.
                        // For now we try to poll with the group name, though it may fail if it's not a job ID.
                        // Ensure that we poll only if society contains a job ID. If it is a group name, getSimulationStatus will fail on the new API.
                        const status = await GradioService.getSimulationStatus(simulationResult?.job_id || society);
                        setSimulationResult({
                          status: "Updated",
                          message: "Latest status gathered from API.",
                          data: status
                        });
                      } catch (e) {
                        console.error(e);
                      } finally {
                        setIsRefreshing(false);
                      }
                    }}
                    className="p-1 hover:bg-gray-800 rounded text-gray-500 hover:text-white"
                    title="Refresh Status"
                  >
                    <RefreshCw size={12} className={isRefreshing ? "animate-spin" : ""} />
                  </button>
                )}
              </div>

              {!simulationResult ? (
                <div className="text-sm text-gray-400 italic text-center py-8">
                  Results will appear here after running a simulation.
                </div>
              ) : (
                <div className="space-y-3">
                  <div className="flex items-center gap-2 text-xs font-medium text-green-400">
                    <div className="w-1.5 h-1.5 rounded-full bg-green-500"></div>
                    {simulationResult.status}
                  </div>
                  <p className="text-[11px] text-gray-400">{simulationResult.message}</p>
                  {simulationResult.data && (
                    <pre className="text-[10px] bg-black/50 p-2 rounded max-h-96 overflow-y-auto custom-scrollbar whitespace-pre-wrap text-gray-300 border border-gray-800">
                      {JSON.stringify(simulationResult.data, null, 2)}
                    </pre>
                  )}
                  <p className="text-[10px] text-gray-600 mt-4 italic">
                    Note: Complete simulation results can take up to 30 minutes to be fully processed by the API.
                  </p>
                </div>
              )}
           </div>
        </div>
      </aside>
    </div>
  );
};

// Helper Components
interface MenuItemProps {
  icon: React.ReactNode;
  label: string;
  highlight?: boolean;
  onClick?: () => void;
}

const MenuItem: React.FC<MenuItemProps> = ({ icon, label, highlight = false, onClick }) => (
  <button
    onClick={onClick}
    className={`w-full flex items-center gap-3 px-2 py-2.5 rounded-md text-sm transition-colors ${highlight ? 'text-teal-400 hover:bg-teal-950/30' : 'text-gray-400 hover:bg-gray-800 hover:text-white'}`}
  >
    {icon}
    <span>{label}</span>
  </button>
);

interface FilterChipProps {
  color: string;
  label: string;
}

const FilterChip: React.FC<FilterChipProps> = ({ color, label }) => (
  <button className="flex items-center gap-2 bg-gray-900/80 backdrop-blur border border-gray-700 rounded-full pl-2 pr-4 py-1.5 hover:border-gray-500 transition-colors">
     <span className={`w-2.5 h-2.5 rounded-full ${color}`}></span>
     <span className="text-xs font-medium text-gray-300">{label}</span>
  </button>
);

export default SimulationPage;