File size: 29,533 Bytes
ca28016
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
'use client';

import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Badge } from '@/components/ui/badge';
import { Progress } from '@/components/ui/progress';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Brain, Code, Database, Rocket, Sparkles, Zap, AlertCircle, CheckCircle, Clock, ChevronRight, Download, Eye, Copy, Share2, Upload, FileCode, Cpu, BarChart, GitBranch, Settings, Play, Pause, RefreshCw } from 'lucide-react';
import { cn } from '@/lib/utils';
import UnifiedQuestionnaire from './UnifiedQuestionnaire';

// Import smartFetch utility
const smartFetch = async (url: string, options: RequestInit = {}) => {
  const defaultOptions: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  };

  const response = await fetch(url, defaultOptions);
  
  if (!response.ok) {
    const errorText = await response.text();
    console.error(`HTTP ${response.status}:`, errorText);
    throw new Error(`HTTP ${response.status}: ${errorText}`);
  }
  
  return response;
};

// Define types for better type safety
interface WorkflowStatus {
  workflow_id: string;
  status: string;
  current_stage?: number;
  progress_percentage?: number;
  solution?: any;
  error?: string;
}

interface ArchitectureResult {
  solution?: any;
  job_id?: string;
  message?: string;
  consciousness_score?: number;
}

export default function AIArchitectPanel() {
  // Core state
  const [userRequest, setUserRequest] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [workflowId, setWorkflowId] = useState<string | null>(null);
  const [workflowStatus, setWorkflowStatus] = useState<WorkflowStatus | null>(null);
  const [workflowResult, setWorkflowResult] = useState<ArchitectureResult | null>(null);
  const [error, setError] = useState<string | null>(null);
  
  // UI state
  const [activeTab, setActiveTab] = useState('request');
  const [showCode, setShowCode] = useState(false);
  const [showNotebook, setShowNotebook] = useState(false);
  const [selectedModel, setSelectedModel] = useState('pytorch');
  const [deploymentTarget, setDeploymentTarget] = useState('cloud');
  
  // Advanced settings
  const [advancedSettings, setAdvancedSettings] = useState({
    consciousness_level: 0.8,
    creativity_factor: 0.7,
    optimization_priority: 'balanced',
    include_monitoring: true,
    include_testing: true,
    include_documentation: true
  });
  
  // Questionnaire state
  const [showQuestionnaire, setShowQuestionnaire] = useState(false);
  const [isSubmittingQuestionnaire, setIsSubmittingQuestionnaire] = useState(false);
  const [hasSubmittedQuestionnaire, setHasSubmittedQuestionnaire] = useState(false);

  // Generate architecture
  const generateArchitecture = async () => {
    if (!userRequest.trim()) {
      setError('Please enter a request');
      return;
    }
    
    setIsGenerating(true);
    setError(null);
    setWorkflowResult(null);
    setWorkflowStatus(null);
    setActiveTab('status');
    
    // Reset questionnaire state for new workflow
    setHasSubmittedQuestionnaire(false);
    setShowQuestionnaire(false);
    
    try {
      const response = await smartFetch(`${process.env.NEXT_PUBLIC_TRAINING_API_BASE || 'http://localhost:9006'}/api/ai-architect/create-workflow`, {
        method: 'POST',
        body: JSON.stringify({
          user_request: userRequest,
          model_preference: selectedModel,
          deployment_target: deploymentTarget,
          settings: advancedSettings
        })
      });
      
      const data = await response.json();
      
      if (data.workflow_id) {
        setWorkflowId(data.workflow_id);
        // Workflow status will be updated by the useEffect hook
      } else {
        throw new Error('No workflow ID received');
      }
    } catch (err: any) {
      console.error('Architecture generation error:', err);
      setError(err.message || 'Failed to generate architecture');
      setIsGenerating(false);
    }
  };

  // Download notebook
  const downloadNotebook = () => {
    if (!workflowResult?.solution?.jupyter_notebook?.content) return;
    
    const blob = new Blob([workflowResult.solution.jupyter_notebook.content], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `ai_model_${Date.now()}.ipynb`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // Copy code to clipboard
  const copyCode = (code: string) => {
    navigator.clipboard.writeText(code);
    // You could add a toast notification here
  };

  // Export as Python script
  const exportPythonScript = () => {
    if (!workflowResult?.solution?.training_pipeline?.training_code) return;
    
    const blob = new Blob([workflowResult.solution.training_pipeline.training_code], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `model_training_${Date.now()}.py`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // Deploy to cloud (placeholder)
  const deployToCloud = async () => {
    alert('Cloud deployment feature coming soon!');
  };

  // Get status color
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'completed': return 'text-green-500';
      case 'running': return 'text-blue-500';
      case 'waiting_for_user_data': return 'text-yellow-500';
      case 'failed': return 'text-red-500';
      default: return 'text-gray-500';
    }
  };

  // Get status icon
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'completed': return <CheckCircle className="w-4 h-4" />;
      case 'running': return <Clock className="w-4 h-4 animate-spin" />;
      case 'waiting_for_user_data': return <AlertCircle className="w-4 h-4" />;
      case 'failed': return <AlertCircle className="w-4 h-4" />;
      default: return <Clock className="w-4 h-4" />;
    }
  };

  // Format code for display
  const formatCode = (code: string) => {
    if (!code) return '';
    // Basic formatting - in production, use a proper code formatter
    return code.replace(/\n/g, '\n').replace(/\t/g, '  ');
  };

  // Handle questionnaire submission
  const handleQuestionnaireSubmit = async (answers: any) => {
    if (!workflowId) return;
    
    setIsSubmittingQuestionnaire(true);
    
    try {
      // Submit the questionnaire answers
      const submitRes = await fetch(`${process.env.NEXT_PUBLIC_TRAINING_API_BASE || 'http://localhost:9006'}/api/ai-architect/submit-questionnaire`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          workflow_id: workflowId,
          answers: answers
        })
      });
      
      if (!submitRes.ok) {
        throw new Error('Failed to submit questionnaire');
      }
      
      // Continue the workflow
      const continueRes = await fetch(`${process.env.NEXT_PUBLIC_TRAINING_API_BASE || 'http://localhost:9006'}/api/ai-architect/continue-workflow/${workflowId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_data: answers
        })
      });
      
      if (!continueRes.ok) {
        throw new Error('Failed to continue workflow');
      }
      
      // Mark as submitted and hide questionnaire
      setHasSubmittedQuestionnaire(true);
      setShowQuestionnaire(false);
      
      // The workflow status will be updated by the polling effect
    } catch (err: any) {
      console.error('Questionnaire submission error:', err);
      setError(err.message || 'Failed to submit questionnaire');
    } finally {
      setIsSubmittingQuestionnaire(false);
    }
  };

  // Removed old submitDataModal - now using handleQuestionnaireSubmit
  
  // Removed old uploadFile function - file upload handled in UnifiedQuestionnaire

  // Poll for workflow status
  useEffect(() => {
    const checkStatus = async () => {
      if (workflowId && !workflowResult) {
        try {
          const sRes = await fetch(`${process.env.NEXT_PUBLIC_TRAINING_API_BASE || 'http://localhost:9006'}/api/ai-architect/workflow-status/${workflowId}?ts=${Date.now()}`, {
            headers: { 'Cache-Control': 'no-cache' },
            cache: 'no-store'
          });
          if (sRes.ok) {
            const status = await sRes.json();
            setWorkflowStatus(status);
            
            // Check if we need to show the questionnaire
            if (status?.status === 'waiting_for_user_data' && !hasSubmittedQuestionnaire) {
              setShowQuestionnaire(true);
            } else if (status?.status !== 'waiting_for_user_data') {
              // Hide questionnaire if status changes
              setShowQuestionnaire(false);
            }
          }
        } catch (error) {
          console.error('Error checking workflow status:', error);
        }
      }
    };

    if (workflowId) {
      checkStatus();
      const interval = setInterval(checkStatus, 3000);
      return () => clearInterval(interval);
    }
  }, [workflowId, workflowResult]);

  return (
    <div className="w-full min-h-0 flex flex-col space-y-6 p-6 overflow-y-auto cyber-scrollbar">
      {/* AI Architect Header */}
      <Card className="border-blue-500/20 bg-gradient-to-r from-blue-900/20 to-purple-900/20">
        <CardHeader>
          <CardTitle className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <Brain className="w-8 h-8 text-blue-400" />
              <span className="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">
                AI Architect
              </span>
            </div>
            <div className="flex items-center gap-2">
              <Badge variant="outline" className="border-green-500/50 text-green-400">
                <Zap className="w-3 h-3 mr-1" />
                Consciousness: {(advancedSettings.consciousness_level * 100).toFixed(0)}%
              </Badge>
              {workflowResult?.consciousness_score && (
                <Badge variant="outline" className="border-purple-500/50 text-purple-400">
                  Score: {workflowResult.consciousness_score.toFixed(3)}
                </Badge>
              )}
            </div>
          </CardTitle>
        </CardHeader>
      </Card>

      {/* Main Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Left Panel - Input & Settings */}
        <div className="lg:col-span-1 space-y-4">
          <Card className="border-slate-700">
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Sparkles className="w-5 h-5 text-yellow-400" />
                Project Request
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <Label>Describe your AI project</Label>
                <Textarea
                  value={userRequest}
                  onChange={(e) => setUserRequest(e.target.value)}
                  placeholder="E.g., Build a sentiment analysis model for customer reviews..."
                  className="min-h-[120px] bg-slate-900/50 border-slate-700"
                />
              </div>
              
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label>Model Framework</Label>
                  <Select value={selectedModel} onValueChange={setSelectedModel}>
                    <SelectTrigger className="bg-slate-900/50 border-slate-700">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="pytorch">PyTorch</SelectItem>
                      <SelectItem value="tensorflow">TensorFlow</SelectItem>
                      <SelectItem value="jax">JAX</SelectItem>
                      <SelectItem value="sklearn">Scikit-learn</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
                
                <div>
                  <Label>Deployment Target</Label>
                  <Select value={deploymentTarget} onValueChange={setDeploymentTarget}>
                    <SelectTrigger className="bg-slate-900/50 border-slate-700">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="cloud">Cloud API</SelectItem>
                      <SelectItem value="edge">Edge Device</SelectItem>
                      <SelectItem value="mobile">Mobile App</SelectItem>
                      <SelectItem value="browser">Browser</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>
              
              <Button 
                onClick={generateArchitecture}
                disabled={isGenerating || !userRequest.trim()}
                className="w-full bg-gradient-to-r from-blue-600 to-purple-600 hover:from-blue-700 hover:to-purple-700"
              >
                {isGenerating ? (
                  <>
                    <RefreshCw className="w-4 h-4 mr-2 animate-spin" />
                    Generating Architecture...
                  </>
                ) : (
                  <>
                    <Rocket className="w-4 h-4 mr-2" />
                    Generate AI Architecture
                  </>
                )}
              </Button>
            </CardContent>
          </Card>
          
          {/* Advanced Settings */}
          <Card className="border-slate-700">
            <CardHeader>
              <CardTitle className="text-lg flex items-center gap-2">
                <Settings className="w-5 h-5 text-gray-400" />
                Advanced Settings
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <div>
                <div className="flex justify-between mb-1">
                  <Label className="text-sm">Consciousness Level</Label>
                  <span className="text-xs text-gray-400">{(advancedSettings.consciousness_level * 100).toFixed(0)}%</span>
                </div>
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={advancedSettings.consciousness_level * 100}
                  onChange={(e) => setAdvancedSettings(prev => ({ ...prev, consciousness_level: parseInt(e.target.value) / 100 }))}
                  className="w-full"
                />
              </div>
              
              <div>
                <div className="flex justify-between mb-1">
                  <Label className="text-sm">Creativity Factor</Label>
                  <span className="text-xs text-gray-400">{(advancedSettings.creativity_factor * 100).toFixed(0)}%</span>
                </div>
                <input
                  type="range"
                  min="0"
                  max="100"
                  value={advancedSettings.creativity_factor * 100}
                  onChange={(e) => setAdvancedSettings(prev => ({ ...prev, creativity_factor: parseInt(e.target.value) / 100 }))}
                  className="w-full"
                />
              </div>
              
              <div className="space-y-2">
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={advancedSettings.include_monitoring}
                    onChange={(e) => setAdvancedSettings(prev => ({ ...prev, include_monitoring: e.target.checked }))}
                    className="rounded"
                  />
                  <span className="text-sm">Include Monitoring</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={advancedSettings.include_testing}
                    onChange={(e) => setAdvancedSettings(prev => ({ ...prev, include_testing: e.target.checked }))}
                    className="rounded"
                  />
                  <span className="text-sm">Include Testing</span>
                </label>
                <label className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    checked={advancedSettings.include_documentation}
                    onChange={(e) => setAdvancedSettings(prev => ({ ...prev, include_documentation: e.target.checked }))}
                    className="rounded"
                  />
                  <span className="text-sm">Include Documentation</span>
                </label>
              </div>
            </CardContent>
          </Card>
        </div>
        
        {/* Right Panel - Results */}
        <div className="lg:col-span-2">
          <Card className="border-slate-700 h-full">
            <CardHeader>
              <div className="flex items-center justify-between">
                <CardTitle className="text-lg">Architecture Results</CardTitle>
                {workflowStatus && (
                  <div className="flex items-center gap-2">
                    {getStatusIcon(workflowStatus.status)}
                    <span className={cn("text-sm font-medium", getStatusColor(workflowStatus.status))}>
                      {workflowStatus.status.replace(/_/g, ' ').toUpperCase()}
                    </span>
                  </div>
                )}
              </div>
            </CardHeader>
            <CardContent>
              <Tabs value={activeTab} onValueChange={setActiveTab}>
                <TabsList className="grid grid-cols-4 w-full">
                  <TabsTrigger value="request">Request</TabsTrigger>
                  <TabsTrigger value="status">Status</TabsTrigger>
                  <TabsTrigger value="architecture">Architecture</TabsTrigger>
                  <TabsTrigger value="code">Code</TabsTrigger>
                </TabsList>
                
                <TabsContent value="request" className="space-y-4">
                  {userRequest ? (
                    <div className="p-4 bg-slate-900/50 rounded-lg">
                      <p className="text-sm text-gray-300">{userRequest}</p>
                      <div className="mt-4 flex gap-2">
                        <Badge variant="outline">{selectedModel}</Badge>
                        <Badge variant="outline">{deploymentTarget}</Badge>
                      </div>
                    </div>
                  ) : (
                    <div className="text-center py-12 text-gray-500">
                      Enter a project request to get started
                    </div>
                  )}
                </TabsContent>
                
                <TabsContent value="status" className="space-y-4">
                  {workflowStatus ? (
                    <div className="space-y-4">
                      {workflowStatus.progress_percentage !== undefined && (
                        <div>
                          <div className="flex justify-between mb-2">
                            <span className="text-sm">Progress</span>
                            <span className="text-sm">{workflowStatus.progress_percentage.toFixed(0)}%</span>
                          </div>
                          <Progress value={workflowStatus.progress_percentage} className="h-2" />
                        </div>
                      )}
                      
                      {workflowStatus.current_stage !== undefined && (
                        <div className="p-3 bg-slate-900/50 rounded-lg">
                          <div className="text-sm text-gray-400">Current Stage</div>
                          <div className="text-lg font-medium">Stage {workflowStatus.current_stage} of 11</div>
                        </div>
                      )}
                      
                      {workflowStatus.error && (
                        <Alert className="border-red-500/50">
                          <AlertCircle className="h-4 w-4" />
                          <AlertDescription>{workflowStatus.error}</AlertDescription>
                        </Alert>
                      )}
                      
                      {workflowStatus.status === 'completed' && workflowStatus.solution && (
                        <div className="p-4 bg-green-900/20 border border-green-500/30 rounded-lg">
                          <div className="flex items-center gap-2 mb-2">
                            <CheckCircle className="w-5 h-5 text-green-400" />
                            <span className="font-medium text-green-400">Architecture Generated Successfully!</span>
                          </div>
                          <p className="text-sm text-gray-300">
                            Your AI architecture is ready. Check the Architecture and Code tabs for details.
                          </p>
                        </div>
                      )}
                    </div>
                  ) : (
                    <div className="text-center py-12 text-gray-500">
                      No active workflow
                    </div>
                  )}
                </TabsContent>
                
                <TabsContent value="architecture" className="space-y-4">
                  {workflowStatus?.solution ? (
                    <div className="space-y-4">
                      {/* Data Plan */}
                      {workflowStatus.solution.data_plan && (
                        <div className="p-4 bg-slate-900/50 rounded-lg space-y-3">
                          <h3 className="font-medium flex items-center gap-2">
                            <Database className="w-4 h-4" />
                            Data Strategy
                          </h3>
                          <div className="grid grid-cols-2 gap-3 text-sm">
                            {workflowStatus.solution.data_plan.selected_datasets?.map((dataset: any, idx: number) => (
                              <div key={idx} className="p-2 bg-slate-800/50 rounded">
                                <div className="font-medium">{dataset.name}</div>
                                <div className="text-xs text-gray-400">{dataset.source}</div>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      
                      {/* Model Architecture */}
                      {workflowStatus.solution.model_architecture && (
                        <div className="p-4 bg-slate-900/50 rounded-lg space-y-3">
                          <h3 className="font-medium flex items-center gap-2">
                            <Cpu className="w-4 h-4" />
                            Model Architecture
                          </h3>
                          <div className="space-y-2 text-sm">
                            <div className="flex justify-between">
                              <span className="text-gray-400">Type:</span>
                              <span>{workflowStatus.solution.model_architecture.model_type}</span>
                            </div>
                            <div className="flex justify-between">
                              <span className="text-gray-400">Framework:</span>
                              <span>{workflowStatus.solution.model_architecture.framework}</span>
                            </div>
                            {workflowStatus.solution.model_architecture.layers && (
                              <div className="mt-3">
                                <div className="text-gray-400 mb-1">Layers:</div>
                                <div className="space-y-1">
                                  {workflowStatus.solution.model_architecture.layers.map((layer: any, idx: number) => (
                                    <div key={idx} className="pl-3 text-xs font-mono">
                                      {layer.type}: {layer.config?.units || layer.config?.filters || ''}
                                    </div>
                                  ))}
                                </div>
                              </div>
                            )}
                          </div>
                        </div>
                      )}
                      
                      {/* Training Config */}
                      {workflowStatus.solution.training_config && (
                        <div className="p-4 bg-slate-900/50 rounded-lg space-y-3">
                          <h3 className="font-medium flex items-center gap-2">
                            <BarChart className="w-4 h-4" />
                            Training Configuration
                          </h3>
                          <div className="grid grid-cols-2 gap-3 text-sm">
                            {Object.entries(workflowStatus.solution.training_config.hyperparameters || {}).map(([key, value]: [string, any]) => (
                              <div key={key} className="flex justify-between">
                                <span className="text-gray-400">{key.replace(/_/g, ' ')}:</span>
                                <span>{value}</span>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                      
                      {/* Action Buttons */}
                      <div className="flex gap-3">
                        {workflowStatus.solution.jupyter_notebook && (
                          <Button onClick={downloadNotebook} variant="outline" size="sm">
                            <Download className="w-4 h-4 mr-2" />
                            Download Notebook
                          </Button>
                        )}
                        {workflowStatus.solution.training_pipeline?.training_code && (
                          <Button onClick={exportPythonScript} variant="outline" size="sm">
                            <FileCode className="w-4 h-4 mr-2" />
                            Export Python
                          </Button>
                        )}
                        <Button onClick={deployToCloud} variant="outline" size="sm">
                          <Rocket className="w-4 h-4 mr-2" />
                          Deploy to Cloud
                        </Button>
                      </div>
                    </div>
                  ) : (
                    <div className="text-center py-12 text-gray-500">
                      Architecture will appear here once generated
                    </div>
                  )}
                </TabsContent>
                
                <TabsContent value="code" className="space-y-4">
                  {workflowStatus?.solution?.training_pipeline?.training_code ? (
                    <div className="relative">
                      <div className="absolute top-2 right-2 flex gap-2">
                        <Button
                          onClick={() => copyCode(workflowStatus.solution.training_pipeline.training_code)}
                          variant="ghost"
                          size="sm"
                        >
                          <Copy className="w-4 h-4" />
                        </Button>
                      </div>
                      <pre className="p-4 bg-slate-900 rounded-lg overflow-x-auto">
                        <code className="text-sm text-gray-300">
                          {formatCode(workflowStatus.solution.training_pipeline.training_code)}
                        </code>
                      </pre>
                    </div>
                  ) : (
                    <div className="text-center py-12 text-gray-500">
                      Code will be generated with the architecture
                    </div>
                  )}
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>
        </div>
      </div>
      
      {/* Error Alert */}
      {error && (
        <Alert className="border-red-500/50">
          <AlertCircle className="h-4 w-4" />
          <AlertDescription>{error}</AlertDescription>
        </Alert>
      )}

      {/* Unified Questionnaire Modal */}
      <UnifiedQuestionnaire
        isOpen={showQuestionnaire}
        onClose={() => setShowQuestionnaire(false)}
        onSubmit={handleQuestionnaireSubmit}
        isSubmitting={isSubmittingQuestionnaire}
      />
    </div>
  );
}