Spaces:
Running

File size: 34,014 Bytes
263213f
 
 
 
3bafddd
263213f
b9f9102
263213f
 
 
 
 
6661747
263213f
 
7e00cd6
263213f
7e00cd6
 
 
 
263213f
 
 
 
 
 
 
b9f9102
 
 
 
 
263213f
 
 
7e00cd6
 
 
 
 
 
 
263213f
 
 
 
 
 
 
3bafddd
263213f
 
b9f9102
263213f
 
7e00cd6
263213f
b9f9102
263213f
7e00cd6
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9f9102
263213f
 
7e00cd6
263213f
b9f9102
263213f
7e00cd6
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e00cd6
263213f
b9f9102
263213f
7e00cd6
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e00cd6
 
 
 
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fafcde0
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e00cd6
 
263213f
 
 
 
 
 
 
 
 
b9f9102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6661747
 
263213f
6661747
 
 
3bafddd
 
 
 
 
 
 
6661747
 
 
 
3bafddd
6661747
 
 
3bafddd
 
 
 
 
 
 
 
 
 
6661747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bafddd
 
 
 
 
 
 
6661747
 
 
 
3bafddd
6661747
 
 
3bafddd
 
 
 
 
 
 
 
 
 
6661747
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263213f
 
6661747
 
 
263213f
 
6661747
263213f
6661747
 
 
 
263213f
6661747
263213f
 
6661747
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e00cd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263213f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'use client'

import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { knowledgeApi, uploadApi } from '@/lib/api'
import { useToast } from '@/contexts/ToastContext'
import { Plus, Trash2, Edit2, FileText, Image as ImageIcon, Video, Link as LinkIcon, Loader2, Save, X, Tag, Calendar, GitBranch, Sparkles, Upload, Type } from 'lucide-react'
import { motion, AnimatePresence } from 'framer-motion'

interface KnowledgeFile {
    id: string
    name: string
    file_type: 'document' | 'image' | 'video' | 'link'
    file_url?: string
    external_link?: string
    thumbnail_url?: string
    description?: string
    send_condition: string
    trigger_day?: number
    trigger_stage_id?: string
    trigger_event?: string
    trigger_keywords?: string
    trigger_stage?: string
    ai_instruction?: string
    sort_order: number
}

const FILE_TYPES = [
    { value: 'text', label: 'Текст', icon: Type, desc: 'Вставьте текст напрямую' },
    { value: 'document', label: 'Документ', icon: FileText, desc: 'PDF, TXT, DOCX' },
    { value: 'image', label: 'Изображение', icon: ImageIcon, desc: 'Фото, схемы' },
    { value: 'video', label: 'Видео', icon: Video, desc: 'YouTube, Vimeo' },
    { value: 'link', label: 'Ссылка', icon: LinkIcon, desc: 'Внешняя ссылка' }
]

const SEND_CONDITIONS = [
    { value: 'on_request', label: 'По запросу клиента', icon: Tag },
    { value: 'by_day', label: 'На определённый день курса', icon: Calendar },
    { value: 'by_stage', label: 'На этапе воронки', icon: GitBranch },
    { value: 'ai_decides', label: 'AI решает сам', icon: Sparkles },
    { value: 'after_purchase', label: 'После покупки', icon: Tag },
    { value: 'after_booking', label: 'После записи', icon: Tag },
    { value: 'on_keyword', label: 'По ключевому слову', icon: Tag }
]

export function KnowledgeFilesManager() {
    const toast = useToast()
    const queryClient = useQueryClient()
    const [editingFile, setEditingFile] = useState<KnowledgeFile | null>(null)
    const [showForm, setShowForm] = useState(false)
    const [uploading, setUploading] = useState(false)
    const [formData, setFormData] = useState({
        name: '',
        file_type: 'text',
        file_url: '',
        external_link: '',
        thumbnail_url: '',
        description: '',
        text_content: '',
        send_condition: 'on_request',
        trigger_day: undefined as number | undefined,
        trigger_stage_id: '',
        trigger_event: '',
        trigger_keywords: '',
        trigger_stage: '',
        ai_instruction: '',
        sort_order: 0
    })

    const { data: files = [], isLoading } = useQuery({
        queryKey: ['knowledge-files'],
        queryFn: knowledgeApi.getKnowledgeFiles
    })

    const createMutation = useMutation({
        mutationFn: knowledgeApi.createKnowledgeFile,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['knowledge-files'] })
            toast.success('Файл добавлен')
            resetForm()
        },
        onError: () => toast.error('Ошибка при добавлении')
    })

    const updateMutation = useMutation({
        mutationFn: ({ id, data }: { id: string; data: any }) => knowledgeApi.updateKnowledgeFile(id, data),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['knowledge-files'] })
            toast.success('Файл обновлён')
            resetForm()
        },
        onError: () => toast.error('Ошибка при обновлении')
    })

    const deleteMutation = useMutation({
        mutationFn: knowledgeApi.deleteKnowledgeFile,
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['knowledge-files'] })
            toast.success('Файл удалён')
        },
        onError: () => toast.error('Ошибка при удалении')
    })

    const resetForm = () => {
        setFormData({
            name: '',
            file_type: 'text',
            file_url: '',
            external_link: '',
            thumbnail_url: '',
            description: '',
            text_content: '',
            send_condition: 'on_request',
            trigger_day: undefined,
            trigger_stage_id: '',
            trigger_event: '',
            trigger_keywords: '',
            trigger_stage: '',
            ai_instruction: '',
            sort_order: 0
        })
        setEditingFile(null)
        setShowForm(false)
    }

    const handleEdit = (file: KnowledgeFile) => {
        setFormData({
            name: file.name,
            file_type: file.file_type,
            file_url: file.file_url || '',
            external_link: file.external_link || '',
            thumbnail_url: file.thumbnail_url || '',
            description: file.description || '',
            text_content: (file as any).text_content || '',
            send_condition: file.send_condition,
            trigger_day: file.trigger_day,
            trigger_stage_id: file.trigger_stage_id || '',
            trigger_event: file.trigger_event || '',
            trigger_keywords: file.trigger_keywords || '',
            trigger_stage: file.trigger_stage || '',
            ai_instruction: file.ai_instruction || '',
            sort_order: file.sort_order
        })
        setEditingFile(file)
        setShowForm(true)
    }

    const handleSubmit = () => {
        if (!formData.name.trim()) {
            toast.error('Введите название')
            return
        }

        if (editingFile) {
            updateMutation.mutate({ id: editingFile.id, data: formData })
        } else {
            createMutation.mutate(formData)
        }
    }

    const getTypeIcon = (type: string) => {
        const found = FILE_TYPES.find(t => t.value === type)
        return found?.icon || FileText
    }

    if (isLoading) {
        return (
            <div className="flex items-center justify-center py-8">
                <Loader2 className="w-6 h-6 animate-spin text-indigo-500" />
            </div>
        )
    }

    return (
        <div className="space-y-4">
            <div className="flex items-center justify-between">
                <h3 className="text-lg font-semibold text-white">Информационные файлы</h3>
                <button
                    onClick={() => setShowForm(true)}
                    className="flex items-center gap-2 px-3 py-1.5 bg-emerald-600 text-white text-sm rounded-lg hover:bg-emerald-700"
                >
                    <Plus className="w-4 h-4" />
                    Добавить
                </button>
            </div>

            <p className="text-sm text-slate-400">
                Добавьте PDF, изображения, видео или ссылки, которые ИИ будет отправлять клиентам в нужный момент.
            </p>

            {/* List */}
            <div className="space-y-2">
                {files.length === 0 ? (
                    <div className="text-center py-8 text-slate-400">
                        Нет файлов. Добавьте материалы для клиентов!
                    </div>
                ) : (
                    files.map((file: KnowledgeFile) => {
                        const TypeIcon = getTypeIcon(file.file_type)
                        return (
                            <div key={file.id} className="flex items-center justify-between p-3 bg-white/5 rounded-lg border border-white/10">
                                <div className="flex items-center gap-3">
                                    <div className="w-8 h-8 rounded-lg bg-emerald-500/20 flex items-center justify-center">
                                        <TypeIcon className="w-4 h-4 text-emerald-400" />
                                    </div>
                                    <div>
                                        <div className="text-white font-medium">{file.name}</div>
                                        <div className="text-xs text-slate-400 flex items-center gap-2">
                                            <span>{SEND_CONDITIONS.find(c => c.value === file.send_condition)?.label}</span>
                                            {file.trigger_day && (
                                                <span className="flex items-center gap-1 text-blue-400">
                                                    <Calendar className="w-3 h-3" />
                                                    День {file.trigger_day}
                                                </span>
                                            )}
                                            {file.trigger_keywords && (
                                                <span className="flex items-center gap-1 text-emerald-400">
                                                    <Tag className="w-3 h-3" />
                                                    {file.trigger_keywords}
                                                </span>
                                            )}
                                        </div>
                                    </div>
                                </div>
                                <div className="flex items-center gap-2">
                                    <button onClick={() => handleEdit(file)} className="p-2 hover:bg-white/10 rounded-lg">
                                        <Edit2 className="w-4 h-4 text-slate-400" />
                                    </button>
                                    <button onClick={() => deleteMutation.mutate(file.id)} className="p-2 hover:bg-red-500/20 rounded-lg">
                                        <Trash2 className="w-4 h-4 text-red-400" />
                                    </button>
                                </div>
                            </div>
                        )
                    })
                )}
            </div>

            {/* Form Modal */}
            <AnimatePresence>
                {showForm && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm flex items-center justify-center p-4"
                        onClick={() => resetForm()}
                    >
                        <motion.div
                            initial={{ scale: 0.95 }}
                            animate={{ scale: 1 }}
                            exit={{ scale: 0.95 }}
                            className="bg-[#1E1F2E] rounded-t-2xl sm:rounded-2xl w-full max-w-md border border-white/10 max-h-[85dvh] overflow-y-auto mb-[var(--footer-height-mobile)] sm:mb-0"
                            onClick={e => e.stopPropagation()}
                        >
                            <div className="flex items-center justify-between p-4 border-b border-white/10">
                                <h3 className="text-lg font-bold text-white">
                                    {editingFile ? 'Редактировать файл' : 'Новый файл'}
                                </h3>
                                <button onClick={() => resetForm()} className="p-2 hover:bg-white/10 rounded-lg">
                                    <X className="w-5 h-5 text-slate-400" />
                                </button>
                            </div>

                            <div className="p-4 space-y-4">
                                <div>
                                    <label className="text-sm font-medium text-slate-400 mb-1 block">Название</label>
                                    <input
                                        type="text"
                                        value={formData.name}
                                        onChange={e => setFormData({ ...formData, name: e.target.value })}
                                        placeholder="Например: Инструкция по курсу"
                                        className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                    />
                                </div>

                                <div>
                                    <label className="text-sm font-medium text-slate-400 mb-1 block">Тип файла</label>
                                    <div className="grid grid-cols-2 gap-2">
                                        {FILE_TYPES.map(type => (
                                            <button
                                                key={type.value}
                                                onClick={() => setFormData({ ...formData, file_type: type.value })}
                                                className={`flex items-center gap-2 p-2 rounded-lg border ${formData.file_type === type.value
                                                    ? 'bg-emerald-500/20 border-emerald-500 text-emerald-400'
                                                    : 'bg-white/5 border-white/10 text-slate-300'
                                                    }`}
                                            >
                                                <type.icon className="w-4 h-4" />
                                                <span className="text-sm">{type.label}</span>
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                {/* Text - Direct paste */}
                                {formData.file_type === 'text' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-2 block">Вставьте текст</label>
                                        <textarea
                                            value={formData.text_content}
                                            onChange={e => setFormData({ ...formData, text_content: e.target.value })}
                                            placeholder="Скопируйте и вставьте текст сюда...

Поддерживаются:
• FAQ и ответы на вопросы
• Описания услуг/продуктов
• Инструкции для клиентов
• Любая текстовая информация"
                                            rows={8}
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white resize-none text-sm"
                                        />
                                        <p className="text-[11px] text-slate-500 mt-1">
                                            AI будет использовать этот текст для ответов клиентам
                                        </p>
                                    </div>
                                )}

                                {/* Document - Upload or URL */}
                                {formData.file_type === 'document' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-2 block">Документ (PDF)</label>

                                        {/* Upload button */}
                                        <label className={`flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer transition-all mb-3 ${uploading ? 'border-emerald-500 bg-emerald-500/10' : 'border-white/20 hover:border-emerald-500/50 hover:bg-emerald-500/5'}`}>
                                            {uploading ? (
                                                <Loader2 className="w-5 h-5 text-emerald-400 animate-spin" />
                                            ) : (
                                                <Upload className="w-5 h-5 text-slate-400" />
                                            )}
                                            <span className="text-slate-400">{uploading ? 'Загрузка...' : 'Загрузить PDF'}</span>
                                            <input
                                                type="file"
                                                accept=".pdf,.doc,.docx"
                                                className="hidden"
                                                disabled={uploading}
                                                onChange={async (e) => {
                                                    const file = e.target.files?.[0]
                                                    if (file) {
                                                        try {
                                                            setUploading(true)
                                                            const result = await uploadApi.uploadDocument(file)
                                                            setFormData({ ...formData, file_url: result.url })
                                                            toast.success('Документ загружен!')
                                                        } catch (err) {
                                                            toast.error('Ошибка загрузки')
                                                        } finally {
                                                            setUploading(false)
                                                        }
                                                    }
                                                }}
                                            />
                                        </label>

                                        {/* URL fallback */}
                                        <div className="relative">
                                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-slate-500">или URL:</span>
                                            <input
                                                type="url"
                                                value={formData.file_url}
                                                onChange={e => setFormData({ ...formData, file_url: e.target.value })}
                                                placeholder="https://..."
                                                className="w-full pl-16 pr-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
                                            />
                                        </div>
                                    </div>
                                )}

                                {/* Image - Upload or URL */}
                                {formData.file_type === 'image' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-2 block">Изображение</label>

                                        {/* Upload button */}
                                        <label className={`flex items-center justify-center gap-2 p-4 border-2 border-dashed rounded-xl cursor-pointer transition-all mb-3 ${uploading ? 'border-emerald-500 bg-emerald-500/10' : 'border-white/20 hover:border-emerald-500/50 hover:bg-emerald-500/5'}`}>
                                            {uploading ? (
                                                <Loader2 className="w-5 h-5 text-emerald-400 animate-spin" />
                                            ) : (
                                                <Upload className="w-5 h-5 text-slate-400" />
                                            )}
                                            <span className="text-slate-400">{uploading ? 'Загрузка...' : 'Загрузить изображение'}</span>
                                            <input
                                                type="file"
                                                accept="image/*"
                                                className="hidden"
                                                disabled={uploading}
                                                onChange={async (e) => {
                                                    const file = e.target.files?.[0]
                                                    if (file) {
                                                        try {
                                                            setUploading(true)
                                                            const result = await uploadApi.uploadImage(file)
                                                            setFormData({ ...formData, file_url: result.url })
                                                            toast.success('Изображение загружено!')
                                                        } catch (err) {
                                                            toast.error('Ошибка загрузки')
                                                        } finally {
                                                            setUploading(false)
                                                        }
                                                    }
                                                }}
                                            />
                                        </label>

                                        {/* URL fallback */}
                                        <div className="relative">
                                            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-xs text-slate-500">или URL:</span>
                                            <input
                                                type="url"
                                                value={formData.file_url}
                                                onChange={e => setFormData({ ...formData, file_url: e.target.value })}
                                                placeholder="https://..."
                                                className="w-full pl-16 pr-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm"
                                            />
                                        </div>

                                        {/* Preview */}
                                        {formData.file_url && (
                                            <div className="mt-3 p-2 bg-white/5 rounded-lg">
                                                <img
                                                    src={formData.file_url}
                                                    alt="Preview"
                                                    className="max-h-32 mx-auto rounded"
                                                    onError={(e) => (e.target as HTMLImageElement).style.display = 'none'}
                                                />
                                            </div>
                                        )}
                                    </div>
                                )}

                                {/* Video - URL only */}
                                {formData.file_type === 'video' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-1 block">Ссылка на видео</label>
                                        <input
                                            type="url"
                                            value={formData.file_url}
                                            onChange={e => setFormData({ ...formData, file_url: e.target.value })}
                                            placeholder="https://youtube.com/... или прямая ссылка"
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                        />
                                        <p className="text-xs text-slate-500 mt-1">YouTube, Vimeo или прямая ссылка на видеофайл</p>
                                    </div>
                                )}

                                {/* Link - External URL */}
                                {formData.file_type === 'link' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-1 block">Внешняя ссылка</label>
                                        <input
                                            type="url"
                                            value={formData.external_link}
                                            onChange={e => setFormData({ ...formData, external_link: e.target.value })}
                                            placeholder="https://..."
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                        />
                                    </div>
                                )}

                                <div>
                                    <label className="text-sm font-medium text-slate-400 mb-1 block">Описание (опционально)</label>
                                    <textarea
                                        value={formData.description}
                                        onChange={e => setFormData({ ...formData, description: e.target.value })}
                                        placeholder="Краткое описание файла..."
                                        rows={2}
                                        className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white resize-none"
                                    />
                                </div>

                                <div>
                                    <label className="text-sm font-medium text-slate-400 mb-1 block">Когда отправлять</label>
                                    <select
                                        value={formData.send_condition}
                                        onChange={e => setFormData({ ...formData, send_condition: e.target.value })}
                                        className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                    >
                                        {SEND_CONDITIONS.map(c => (
                                            <option key={c.value} value={c.value}>{c.label}</option>
                                        ))}
                                    </select>
                                </div>

                                {formData.send_condition === 'by_day' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-1 block">День курса</label>
                                        <input
                                            type="number"
                                            min="1"
                                            value={formData.trigger_day || ''}
                                            onChange={e => setFormData({ ...formData, trigger_day: parseInt(e.target.value) || undefined })}
                                            placeholder="1"
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                        />
                                        <p className="text-xs text-slate-500 mt-1">Материал отправится на N-ый день от старта курса</p>
                                    </div>
                                )}

                                {formData.send_condition === 'by_stage' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-1 block">Этап воронки</label>
                                        <input
                                            type="text"
                                            value={formData.trigger_stage}
                                            onChange={e => setFormData({ ...formData, trigger_stage: e.target.value })}
                                            placeholder="Квалификация, Закрытие..."
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                        />
                                        <p className="text-xs text-slate-500 mt-1">AI отправит когда лид достигнет этого этапа</p>
                                    </div>
                                )}

                                {formData.send_condition === 'ai_decides' && (
                                    <div className="p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg">
                                        <div className="flex items-center gap-2 text-purple-400 text-sm">
                                            <Sparkles className="w-4 h-4" />
                                            <span>AI сам решит когда отправить на основе инструкции ниже</span>
                                        </div>
                                    </div>
                                )}

                                {formData.send_condition === 'on_keyword' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-1 block">Ключевые слова (через запятую)</label>
                                        <input
                                            type="text"
                                            value={formData.trigger_keywords}
                                            onChange={e => setFormData({ ...formData, trigger_keywords: e.target.value })}
                                            placeholder="инструкция, гайд, как начать"
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                        />
                                    </div>
                                )}

                                {formData.send_condition === 'on_stage' && (
                                    <div>
                                        <label className="text-sm font-medium text-slate-400 mb-1 block">Этап воронки</label>
                                        <input
                                            type="text"
                                            value={formData.trigger_stage}
                                            onChange={e => setFormData({ ...formData, trigger_stage: e.target.value })}
                                            placeholder="closing, payment, onboarding"
                                            className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white"
                                        />
                                    </div>
                                )}

                                <div>
                                    <label className="text-sm font-medium text-slate-400 mb-1 block">Инструкция для ИИ (опционально)</label>
                                    <textarea
                                        value={formData.ai_instruction}
                                        onChange={e => setFormData({ ...formData, ai_instruction: e.target.value })}
                                        placeholder="Когда и как отправлять этот файл..."
                                        rows={2}
                                        className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white resize-none"
                                    />
                                </div>

                                <button
                                    onClick={handleSubmit}
                                    disabled={createMutation.isPending || updateMutation.isPending}
                                    className="w-full py-3 bg-emerald-600 text-white font-bold rounded-xl hover:bg-emerald-700 disabled:opacity-50 flex items-center justify-center gap-2"
                                >
                                    {(createMutation.isPending || updateMutation.isPending) ? (
                                        <Loader2 className="w-4 h-4 animate-spin" />
                                    ) : (
                                        <Save className="w-4 h-4" />
                                    )}
                                    {editingFile ? 'Сохранить' : 'Добавить'}
                                </button>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    )
}