File size: 15,866 Bytes
ceba883
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useRef, useEffect } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { 
  FaRobot, FaBrain, FaCode, FaDatabase, FaCloud, FaShieldAlt, 
  FaChartLine, FaProjectDiagram, FaBug, FaFileCode, FaGitAlt,
  FaDocker, FaServer, FaMobile, FaPalette, FaGlobe, FaLock,
  FaNetworkWired, FaMemory, FaMicrochip, FaCogs, FaRocket,
  FaTerminal, FaBook, FaGraduationCap, FaLightbulb, FaMagic,
  FaTools, FaRegClock, FaSearch, FaFilter, FaDownload, FaUpload,
  FaSave, FaTrash, FaEdit, FaCopy, FaPaste, FaUndo, FaRedo,
  FaPlay, FaStop, FaPause, FaStepForward, FaStepBackward,
  FaExpand, FaCompress, FaFullscreen, FaRegWindowMaximize,
  FaRegWindowMinimize, FaWindowClose, FaRegWindowRestore,
  FaDesktop, FaLaptop, FaTablet, FaMobileAlt, FaTv,
  FaGamepad, FaHeadphones, FaMicrophone, FaVideo, FaCamera,
  FaImage, FaFilm, FaMusic, FaPodcast, FaBroadcastTower,
  FaSatellite, FaWifi, FaEthernet, FaUsb, FaBluetooth,
  FaSimCard, FaSdCard, FaHdd, FaCompactDisc, FaPrint,
  FaScanner, FaKeyboard, FaMouse, FaGamepadAlt, FaJoystick,
  FaVrCardboard, FaGlasses, FaWatch, FaClock, FaStopwatch
} from 'react-icons/fa'
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter'
import { vscDarkPlus } from 'react-syntax-highlighter/dist/cjs/styles/prism'
import toast from 'react-hot-toast'

export default function AIAgent({ language, theme }) {
  const [activeModel, setActiveModel] = useState('code-assistant')
  const [messages, setMessages] = useState([])
  const [input, setInput] = useState('')
  const [isProcessing, setIsProcessing] = useState(false)
  const [selectedCapability, setSelectedCapability] = useState('code-generation')
  const [context, setContext] = useState({})
  const [models] = useState([
    { id: 'code-assistant', name: 'Code Assistant', icon: FaCode, description: 'Full-stack programming assistant' },
    { id: 'database-expert', name: 'Database Expert', icon: FaDatabase, description: 'Database design and optimization' },
    { id: 'cloud-architect', name: 'Cloud Architect', icon: FaCloud, description: 'Cloud infrastructure and deployment' },
    { id: 'security-specialist', name: 'Security Specialist', icon: FaShieldAlt, description: 'Security analysis and protection' },
    { id: 'performance-analyst', name: 'Performance Analyst', icon: FaChartLine, description: 'Performance optimization' },
    { id: 'project-manager', name: 'Project Manager', icon: FaProjectDiagram, description: 'Project planning and management' },
    { id: 'debugger', name: 'Bug Hunter', icon: FaBug, description: 'Debug and fix issues' },
    { id: 'documentation', name: 'Documentation', icon: FaBook, description: 'Generate documentation' },
    { id: 'testing', name: 'Testing Expert', icon: FaVrCardboard, description: 'Automated testing' },
    { id: 'deployment', name: 'Deployment', icon: FaRocket, description: 'CI/CD and deployment' }
  ])

  const capabilities = [
    { id: 'code-generation', name: 'Code Generation', icon: FaCode },
    { id: 'code-review', name: 'Code Review', icon: FaSearch },
    { id: 'refactoring', name: 'Refactoring', icon: FaEdit },
    { id: 'optimization', name: 'Optimization', icon: FaRocket },
    { id: 'debugging', name: 'Debugging', icon: FaBug },
    { id: 'testing', name: 'Testing', icon: FaFlask },
    { id: 'documentation', name: 'Documentation', icon: FaBook },
    { id: 'architecture', name: 'Architecture', icon: FaProjectDiagram },
    { id: 'security', name: 'Security', icon: FaShieldAlt },
    { id: 'performance', name: 'Performance', icon: FaChartLine },
    { id: 'database', name: 'Database', icon: FaDatabase },
    { id: 'api', name: 'API Design', icon: FaNetworkWired },
    { id: 'ui-ux', name: 'UI/UX', icon: FaPalette },
    { id: 'mobile', name: 'Mobile Dev', icon: FaMobile },
    { id: 'web', name: 'Web Dev', icon: FaGlobe },
    { id: 'devops', name: 'DevOps', icon: FaServer },
    { id: 'ml', name: 'Machine Learning', icon: FaBrain },
    { id: 'blockchain', name: 'Blockchain', icon: FaLink },
    { id: 'iot', name: 'IoT', icon: FaWifi },
    { id: 'gaming', name: 'Game Dev', icon: FaGamepad }
  ]

  const handleSendMessage = async () => {
    if (!input.trim()) return

    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: input,
      capability: selectedCapability,
      model: activeModel,
      timestamp: new Date()
    }

    setMessages(prev => [...prev, userMessage])
    setInput('')
    setIsProcessing(true)

    try {
      // Simulate AI processing
      await new Promise(resolve => setTimeout(resolve, 2000))

      const aiResponse = await generateAIResponse(input, selectedCapability, activeModel)
      
      const assistantMessage = {
        id: Date.now() + 1,
        type: 'assistant',
        content: aiResponse,
        capability: selectedCapability,
        model: activeModel,
        timestamp: new Date()
      }

      setMessages(prev => [...prev, assistantMessage])
    } catch (error) {
      toast.error(language === 'fa' ? 'خطا در پردازش درخواست' : 'Error processing request')
    } finally {
      setIsProcessing(false)
    }
  }

  const generateAIResponse = async (prompt, capability, model) => {
    const responses = {
      'code-generation': `// Generated code for: ${prompt}\nfunction generateSolution() {\n  // AI-generated implementation\n  return "Solution generated by ${model}";\n}`,
      'code-review': `Code Review Results:\n✓ Code follows best practices\n✓ No security vulnerabilities detected\n⚠ Consider optimizing performance\n✓ Documentation is complete`,
      'refactoring': `Refactored Code:\n// Improved version with better structure\nclass RefactoredSolution {\n  constructor() {\n    this.optimized = true;\n  }\n}`,
      'debugging': `Debug Analysis:\n🐛 Issue identified in line 42\n🔧 Suggested fix: Initialize variable before use\n✅ Solution implemented successfully`,
      'testing': `Test Coverage Report:\n✓ Unit tests: 95%\n✓ Integration tests: 88%\n✓ E2E tests: 92%\n📊 Overall coverage: 92%`,
      'documentation': `Generated Documentation:\n# API Documentation\n\n## Overview\nThis module provides...\n\n## Installation\n\`\`\`bash\nnpm install package\n\`\`\`\n\n## Usage\n\`\`\`javascript\nimport { module } from 'package';\n\`\`\``,
      'architecture': `Architecture Recommendation:\n🏗️ Pattern: Microservices\n📊 Scalability: High\n🔒 Security: Enterprise grade\n⚡ Performance: Optimized`,
      'security': `Security Analysis:\n🔒 SSL/TLS: Configured\n🛡️ Firewall: Active\n🔐 Authentication: OAuth 2.0\n✅ No vulnerabilities found`,
      'performance': `Performance Metrics:\n⚡ Response time: 45ms\n💾 Memory usage: 128MB\n📈 Throughput: 1000 req/s\n🎯 Score: 95/100`,
      'database': `Database Schema:\n📊 Tables: Optimized\n🔍 Indexes: Properly configured\n⚡ Queries: Optimized\n💾 Storage: Efficient`,
      'api': `API Design:\n🌐 RESTful: Yes\n📝 Documentation: Complete\n🔒 Security: JWT auth\n⚡ Performance: High`,
      'ui-ux': `UI/UX Recommendations:\n🎨 Design: Modern\n📱 Responsive: Yes\n♿ Accessible: WCAG 2.1\n⚡ Performance: Optimized`,
      'mobile': `Mobile Solution:\n📱 Platform: Cross-platform\n⚡ Performance: Native-like\n🔋 Battery: Optimized\n📦 Size: Minimal`,
      'web': `Web Solution:\n🌐 Framework: Next.js\n⚡ Performance: Optimized\n🔒 Security: HTTPS\n📱 Responsive: Yes`,
      'devops': `DevOps Pipeline:\n🚀 CI/CD: Automated\n🐳 Docker: Containerized\n☁️ Cloud: AWS\n📊 Monitoring: Enabled`,
      'ml': `ML Solution:\n🧠 Model: Neural Network\n📊 Accuracy: 98%\n⚡ Training: Optimized\n🔮 Prediction: Real-time`,
      'blockchain': `Blockchain Solution:\n⛓️ Network: Ethereum\n🔐 Smart Contract: Audited\n⚡ Gas: Optimized\n🔒 Security: High`,
      'iot': `IoT Solution:\n📡 Devices: Connected\n🔌 Protocol: MQTT\n⚡ Real-time: Yes\n🔒 Security: Encrypted`,
      'gaming': `Game Development:\n🎮 Engine: Unity\n⚡ Performance: 60 FPS\n🎨 Graphics: 4K\n🎯 Gameplay: Smooth`
    }

    return responses[capability] || `AI Response from ${model} for: ${prompt}`
  }

  const exportConversation = () => {
    const data = JSON.stringify(messages, null, 2)
    const blob = new Blob([data], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = 'ai-conversation.json'
    a.click()
    toast.success(language === 'fa' ? 'گفتگو export شد' : 'Conversation exported')
  }

  const clearConversation = () => {
    setMessages([])
    toast.success(language === 'fa' ? 'گفتگو پاک شد' : 'Conversation cleared')
  }

  return (
    <div className="flex flex-col h-full space-y-4">
      {/* Header */}
      <div className="flex items-center justify-between p-4 bg-gray-800 rounded-lg">
        <div className="flex items-center space-x-reverse space-x-3">
          <FaRobot className="w-6 h-6 text-primary-400" />
          <h2 className="text-lg font-semibold">AI Agent Studio</h2>
        </div>
        <div className="flex items-center space-x-reverse space-x-2">
          <button
            onClick={exportConversation}
            className="px-3 py-1 bg-gray-700 text-white rounded-lg hover:bg-gray-600 transition-all text-sm"
          >
            <FaDownload className="w-4 h-4 inline ml-2" />
            {language === 'fa' ? 'export' : 'Export'}
          </button>
          <button
            onClick={clearConversation}
            className="px-3 py-1 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-all text-sm"
          >
            <FaTrash className="w-4 h-4 inline ml-2" />
            {language === 'fa' ? 'پاک کردن' : 'Clear'}
          </button>
        </div>
      </div>

      <div className="flex-1 flex space-x-reverse space-x-4 min-h-0">
        {/* Sidebar */}
        <div className="w-80 bg-gray-800 rounded-lg p-4 space-y-4 overflow-y-auto">
          {/* Models */}
          <div>
            <h3 className="text-sm font-medium mb-3">AI Models</h3>
            <div className="space-y-2">
              {models.map(model => {
                const Icon = model.icon
                return (
                  <button
                    key={model.id}
                    onClick={() => setActiveModel(model.id)}
                    className={`w-full p-3 rounded-lg transition-all text-left ${
                      activeModel === model.id
                        ? 'bg-primary-600 text-white'
                        : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                    }`}
                  >
                    <div className="flex items-center space-x-reverse space-x-2">
                      <Icon className="w-4 h-4" />
                      <div>
                        <div className="text-sm font-medium">{model.name}</div>
                        <div className="text-xs opacity-75">{model.description}</div>
                      </div>
                    </div>
                  </button>
                )
              })}
            </div>
          </div>

          {/* Capabilities */}
          <div>
            <h3 className="text-sm font-medium mb-3">Capabilities</h3>
            <div className="grid grid-cols-2 gap-2">
              {capabilities.map(cap => {
                const Icon = cap.icon
                return (
                  <button
                    key={cap.id}
                    onClick={() => setSelectedCapability(cap.id)}
                    className={`p-2 rounded-lg transition-all flex flex-col items-center justify-center ${
                      selectedCapability === cap.id
                        ? 'bg-primary-600 text-white'
                        : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                    }`}
                  >
                    <Icon className="w-4 h-4 mb-1" />
                    <span className="text-xs">{cap.name}</span>
                  </button>
                )
              })}
            </div>
          </div>
        </div>

        {/* Chat Area */}
        <div className="flex-1 bg-gray-800 rounded-lg flex flex-col">
          <div className="flex-1 p-4 overflow-y-auto space-y-4">
            <AnimatePresence>
              {messages.map(message => (
                <motion.div
                  key={message.id}
                  initial={{ opacity: 0, y: 20 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -20 }}
                  className={`flex ${message.type === 'user' ? 'justify-start' : 'justify-end'}`}
                >
                  <div className={`max-w-lg p-4 rounded-lg ${
                    message.type === 'user'
                      ? 'bg-gray-700 text-white'
                      : 'bg-primary-600 text-white'
                  }`}>
                    <div className="flex items-center space-x-reverse space-x-2 mb-2">
                      {message.type === 'user' ? (
                        <FaUser className="w-4 h-4" />
                      ) : (
                        <FaRobot className="w-4 h-4" />
                      )}
                      <span className="text-xs opacity-75">
                        {message.model} • {message.capability}
                      </span>
                    </div>
                    {message.content.includes('```') ? (
                      <SyntaxHighlighter
                        language="javascript"
                        style={vscDarkPlus}
                        className="rounded"
                      >
                        {message.content}
                      </SyntaxHighlighter>
                    ) : (
                      <div className="whitespace-pre-wrap text-sm">
                        {message.content}
                      </div>
                    )}
                  </div>
                </motion.div>
              ))}
            </AnimatePresence>

            {isProcessing && (
              <motion.div
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="flex justify-end"
              >
                <div className="bg-primary-600 p-4 rounded-lg">
                  <div className="flex space-x-reverse space-x-1">
                    <div className="w-2 h-2 bg-white rounded-full animate-bounce" />
                    <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '150ms' }} />
                    <div className="w-2 h-2 bg-white rounded-full animate-bounce" style={{ animationDelay: '300ms' }} />
                  </div>
                </div>
              </motion.div>
            )}
          </div>

          {/* Input */}
          <div className="p-4 border-t border-gray-700">
            <div className="flex space-x-reverse space-x-2">
              <input
                type="text"
                value={input}
                onChange={(e) => setInput(e.target.value)}
                onKeyPress={(e) => e.key === 'Enter' && handleSendMessage()}
                placeholder="Ask AI anything..."
                className="flex-1 px-4 py-2 bg-gray-700 text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
                disabled={isProcessing}
              />
              <button
                onClick={handleSendMessage}
                disabled={!input.trim() || isProcessing}
                className="px-4 py-2 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 transition-all"
              >
                <FaPaperPlane className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}