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
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect } from 'react';
import {
  Layers,
  Sparkles,
  Upload,
  Play,
  RefreshCw,
  Film,
  Download,
  Trash2,
  CheckCircle2,
  Clock,
  AlertCircle,
  Cloud,
  FileSpreadsheet,
  Plus,
} from 'lucide-react';
import { api } from '../api';
import type { AspectRatio, BrandKit, FrozenRecipe } from '@olokaflow/shared';
import { Button, Badge } from './ui/primitives';

interface Props {
  catalog: any;
  brands: BrandKit[];
  recipes: FrozenRecipe[];
  onOpenProjectInStudio: (projectId: string) => void;
  onRefreshAll: () => void;
}

export const BatchStudioView: React.FC<Props> = ({
  catalog,
  brands,
  recipes,
  onOpenProjectInStudio,
  onRefreshAll,
}) => {
  const [batches, setBatches] = useState<any[]>([]);
  const [batchName, setBatchName] = useState('');
  const [bulkLinesText, setBulkLinesText] = useState('');
  const [defaultAspectRatio, setDefaultAspectRatio] = useState<AspectRatio>('9:16');
  const [defaultVoiceId, setDefaultVoiceId] = useState('Hải Đăng');
  const [defaultFramePresetId, setDefaultFramePresetId] = useState(
    'editorial-clean-light'
  );
  const [brandKitId, setBrandKitId] = useState('');
  const [recipeId, setRecipeId] = useState('');
  const [creationMode, setCreationMode] = useState<'auto' | 'storyboard_review'>(
    'auto'
  );
  const [autoRenderModal, setAutoRenderModal] = useState(false);
  const [startingBatch, setStartingBatch] = useState(false);

  const voicesList = catalog?.voices || [];
  const presetsList = catalog?.framePresets || [];

  async function loadBatches() {
    try {
      const res = await api.getBatches();
      setBatches(res.batches || []);
    } catch {}
  }

  useEffect(() => {
    void loadBatches();
  }, []);

  // Poll while any batch is running
  useEffect(() => {
    const hasRunning = batches.some((b) => b.status === 'running');
    if (!hasRunning) return;
    const timer = setInterval(() => {
      void loadBatches();
      onRefreshAll();
    }, 4000);
    return () => clearInterval(timer);
  }, [batches]);

  function parseBulkLines(): Array<{ title?: string; prompt: string }> {
    return bulkLinesText
      .split(/\r?\n/)
      .map((line) => line.trim())
      .filter((line) => line.length > 0 && !line.startsWith('#'))
      .map((line) => {
        // Support "Title | Prompt or URL" or CSV "Title,Prompt"
        if (line.includes('|')) {
          const [t, ...rest] = line.split('|');
          return { title: t.trim(), prompt: rest.join('|').trim() };
        }
        return { prompt: line };
      });
  }

  function handleCsvFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = () => {
      const text = String(reader.result || '');
      const rows = text
        .split(/\r?\n/)
        .map((r) => r.trim())
        .filter(Boolean);
      const converted = rows
        .filter((r, i) => !(i === 0 && /title|prompt|url/i.test(r)))
        .map((r) => {
          const cols = r.split(',');
          if (cols.length >= 2) {
            return `${cols[0].replace(/^"|"$/g, '').trim()} | ${cols
              .slice(1)
              .join(',')
              .replace(/^"|"$/g, '')
              .trim()}`;
          }
          return r;
        });
      setBulkLinesText((prev) =>
        prev ? `${prev}\n${converted.join('\n')}` : converted.join('\n')
      );
    };
    reader.readAsText(file);
    e.target.value = '';
  }

  async function handleStartBatch(e: React.FormEvent) {
    e.preventDefault();
    const items = parseBulkLines();
    if (items.length === 0) return;
    setStartingBatch(true);
    try {
      const res = await api.createBatch({
        name: batchName.trim() || undefined,
        items,
        defaultAspectRatio,
        defaultVoiceId,
        defaultFramePresetId,
        brandKitId: brandKitId || undefined,
        recipeId: recipeId || undefined,
        creationMode,
        autoRenderModal,
      });
      setBatches(res.batches || []);
      setBulkLinesText('');
      setBatchName('');
      onRefreshAll();
    } catch (err: any) {
      alert(`Lỗi tạo Batch: ${err.message}`);
    } finally {
      setStartingBatch(false);
    }
  }

  const parsedItemsCount = parseBulkLines().length;

  return (
    <div className="space-y-6">
      {/* Header Banner */}
      <div className="fliki-card p-6 bg-white flex flex-wrap items-center justify-between gap-4">
        <div>
          <Badge variant="crimson" className="mb-1.5">
            <Layers className="w-3 h-3" />
            Batch URL-to-Video Factory • Multi-Project Automation
          </Badge>
          <h2 className="text-xl font-bold tracking-tight text-zinc-900">
            Sản Xuất Video Hàng Loạt Từ Danh Sách URL Sản Phẩm Hoặc CSV
          </h2>
          <p className="text-xs text-zinc-500 mt-0.5">
            Nhập nhiều link trang web sản phẩm hoặc danh sách kịch bản (mỗi dòng 1 video) — Hệ thống tự động cào ảnh, đọc giọng OlokaTTS, dựng HyperFrames 60fps và tùy chọn xuất MP4 hàng loạt qua Modal Cloud.
          </p>
        </div>

        <Button
          type="button"
          variant="secondary"
          onClick={() => {
            setBatchName('Chiến dịch 3 Video Ra mắt Sản phẩm Q4');
            setBulkLinesText(
              [
                'TVC SaaS OlokaFlow | Tạo video quảng cáo ra mắt nền tảng OlokaFlow AI Video Studio dựng đồ họa chuyển động 60fps tự động.',
                'Serum Vitamin C Luxury | Giới thiệu tinh chất dưỡng sáng da Vitamin C nguyên chất cấp ẩm 24h, ưu đãi 30% hôm nay.',
                'Báo cáo Tăng trưởng Thương mại | Thuyết trình số liệu doanh thu thương mại điện tử tăng 320% và tỷ lệ chuyển đổi đạt 8.4%.',
              ].join('\n')
            );
          }}
        >
          <Sparkles className="w-3.5 h-3.5 text-[#E11D48]" />
          <span>Điền Mẫu 3 Video Chiến Dịch</span>
        </Button>
      </div>

      {/* Batch Configuration Form */}
      <form
        onSubmit={handleStartBatch}
        className="fliki-card p-6 bg-white grid grid-cols-1 lg:grid-cols-12 gap-5"
      >
        <div className="lg:col-span-7 space-y-3">
          <div className="flex items-center justify-between">
            <label className="text-xs font-bold text-zinc-800">
              Danh sách Prompt hoặc URL Sản Phẩm (Mỗi dòng 1 Video • Định dạng:{' '}
              <span className="font-mono text-[#E11D48]">
                Tên Video | Nội dung hoặc URL
              </span>
              )
            </label>
            <label className="px-2.5 py-1 rounded-lg bg-zinc-100 hover:bg-zinc-200 text-zinc-700 text-[11px] font-semibold flex items-center gap-1.5 cursor-pointer">
              <FileSpreadsheet className="w-3.5 h-3.5 text-[#E11D48]" />
              <span>Nhập từ CSV / TXT</span>
              <input
                type="file"
                accept=".csv,.txt"
                onChange={handleCsvFileUpload}
                className="hidden"
              />
            </label>
          </div>

          <textarea
            rows={7}
            value={bulkLinesText}
            onChange={(e) => setBulkLinesText(e.target.value)}
            placeholder={`Ví dụ:\nVideo Sản phẩm 1 | https://example.com/san-pham-1 Giới thiệu ưu điểm nổi bật và khuyến mãi\nVideo Sản phẩm 2 | Tạo video quảng cáo tai nghe chống ồn chủ động ANC pin 40 giờ\nVideo Sản phẩm 3 | Báo cáo kết quả kinh doanh quý 4 tăng trưởng vượt bậc`}
            className="w-full bg-zinc-50 border border-zinc-200 rounded-xl p-3.5 text-xs font-mono text-zinc-900 leading-relaxed focus:outline-none focus:border-[#E11D48] focus:bg-white"
            required
          />

          <div className="flex items-center justify-between text-xs text-zinc-500">
            <span>
              Số lượng video nhận diện:{' '}
              <strong className="font-mono tabular-nums text-[#E11D48]">
                {parsedItemsCount} video
              </strong>
            </span>
            <span>Tự động cào ảnh nếu dòng chứa link http/https</span>
          </div>
        </div>

        <div className="lg:col-span-5 bg-zinc-50/80 border border-zinc-200/80 rounded-2xl p-4 space-y-3 flex flex-col justify-between">
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            <div className="sm:col-span-2">
              <label className="block text-xs font-semibold text-zinc-700 mb-1">
                Tên lô sản xuất (Batch Name)
              </label>
              <input
                type="text"
                value={batchName}
                onChange={(e) => setBatchName(e.target.value)}
                placeholder="VD: Lô 10 Video TikTok Sản phẩm Mới..."
                className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs text-zinc-900"
              />
            </div>

            <div>
              <label className="block text-xs font-semibold text-zinc-700 mb-1">
                Tỷ lệ khung hình
              </label>
              <select
                value={defaultAspectRatio}
                onChange={(e) =>
                  setDefaultAspectRatio(e.target.value as AspectRatio)
                }
                className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
              >
                <option value="9:16">9:16 Dọc (TikTok / Reels)</option>
                <option value="16:9">16:9 Ngang (YouTube)</option>
                <option value="1:1">1:1 Vuông (Feed)</option>
              </select>
            </div>

            <div>
              <label className="block text-xs font-semibold text-zinc-700 mb-1">
                Phong cách (Frame Preset)
              </label>
              <select
                value={defaultFramePresetId}
                onChange={(e) => setDefaultFramePresetId(e.target.value)}
                className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
              >
                {presetsList.map((fp: any) => (
                  <option key={fp.id} value={fp.id}>
                    {fp.name}
                  </option>
                ))}
              </select>
            </div>

            <div className="sm:col-span-2">
              <label className="block text-xs font-semibold text-zinc-700 mb-1">
                Giọng đọc mặc định (Bao gồm 25 Giọng OlokaTTS & Giọng Clone)
              </label>
              <select
                value={defaultVoiceId}
                onChange={(e) => setDefaultVoiceId(e.target.value)}
                className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
              >
                {voicesList.map((v: any) => (
                  <option key={v.id} value={v.voiceId || v.id}>
                    {v.name} — {v.description}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-semibold text-zinc-700 mb-1">
                Brand Kit
              </label>
              <select
                value={brandKitId}
                onChange={(e) => setBrandKitId(e.target.value)}
                className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
              >
                <option value="">Mặc định theo Preset</option>
                {brands.map((b) => (
                  <option key={b.id} value={b.id}>
                    {b.name}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-xs font-semibold text-zinc-700 mb-1">
                Frozen Recipe
              </label>
              <select
                value={recipeId}
                onChange={(e) => setRecipeId(e.target.value)}
                className="w-full bg-white border border-zinc-200 rounded-xl px-3 py-2 text-xs font-semibold text-zinc-800"
              >
                <option value="">Tự động chọn Blueprint</option>
                {recipes.map((r) => (
                  <option key={r.id} value={r.id}>
                    {r.name}
                  </option>
                ))}
              </select>
            </div>
          </div>

          <div className="pt-3 border-t border-zinc-200/80 space-y-3">
            <label className="flex items-center gap-2 text-xs font-semibold text-zinc-700 cursor-pointer">
              <input
                type="checkbox"
                checked={autoRenderModal}
                onChange={(e) => setAutoRenderModal(e.target.checked)}
                className="rounded border-zinc-300 text-[#E11D48] focus:ring-[#E11D48]"
              />
              <Cloud className="w-3.5 h-3.5 text-[#E11D48]" />
              <span>
                Tự động gửi Render MP4 lên Modal Cloud (cpu24w22) sau khi dựng xong
              </span>
            </label>

            <Button
              type="submit"
              variant="primary"
              size="lg"
              className="w-full"
              disabled={startingBatch || parsedItemsCount === 0}
            >
              <Play className="w-4 h-4 fill-current" />
              <span>
                {startingBatch
                  ? 'Đang khởi chạy hàng đợi...'
                  : `Khởi Chạy Sản Xuất ${parsedItemsCount} Video Hàng Loạt`}
              </span>
            </Button>
          </div>
        </div>
      </form>

      {/* Active & Completed Batch Queue */}
      <div className="space-y-4">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-bold text-zinc-900">
            Tiến Trình & Lịch Sử Lô Sản Xuất Video ({batches.length})
          </h3>
          <Button variant="secondary" size="sm" onClick={() => loadBatches()}>
            <RefreshCw className="w-3.5 h-3.5" />
            <span>Làm mới trạng thái</span>
          </Button>
        </div>

        {batches.length === 0 ? (
          <div className="fliki-card p-8 bg-white text-center text-xs text-zinc-400">
            Chưa có lô sản xuất hàng loạt nào. Hãy nhập danh sách URL/Prompt ở trên hoặc bấm "Điền Mẫu 3 Video Chiến Dịch" để bắt đầu.
          </div>
        ) : (
          batches.map((batch) => {
            const pct =
              batch.totalItems > 0
                ? Math.round((batch.completedItems / batch.totalItems) * 100)
                : 0;
            return (
              <div key={batch.id} className="fliki-card p-5 bg-white space-y-4">
                <div className="flex flex-wrap items-center justify-between gap-3 border-b border-zinc-100 pb-3">
                  <div>
                    <div className="flex items-center gap-2">
                      <span className="text-sm font-bold text-zinc-900">
                        {batch.name}
                      </span>
                      <Badge
                        variant={
                          batch.status === 'completed'
                            ? 'emerald'
                            : batch.status === 'failed'
                              ? 'crimson'
                              : 'amber'
                        }
                        mono
                      >
                        {batch.status === 'running' ? (
                          <RefreshCw className="w-3 h-3 animate-spin" />
                        ) : (
                          <CheckCircle2 className="w-3 h-3" />
                        )}
                        {batch.completedItems}/{batch.totalItems} HOÀN TẤT ({pct}%)
                      </Badge>
                    </div>
                    <div className="text-[11px] font-mono text-zinc-400 mt-0.5">
                      ID: {batch.id} • Khung hình: {batch.config?.defaultAspectRatio}{' '}
                      • Giọng: {batch.config?.defaultVoiceId}
                    </div>
                  </div>

                  <Button
                    variant="danger"
                    size="sm"
                    onClick={async () => {
                      const res = await api.deleteBatch(batch.id);
                      setBatches(res.batches || []);
                    }}
                  >
                    <Trash2 className="w-3.5 h-3.5" />
                    <span>Xóa lô</span>
                  </Button>
                </div>

                <div className="divide-y divide-zinc-100 border border-zinc-200 rounded-xl overflow-hidden">
                  {(batch.items || []).map((it: any, idx: number) => (
                    <div
                      key={idx}
                      className="p-3.5 bg-white hover:bg-zinc-50/70 flex flex-wrap items-center justify-between gap-3"
                    >
                      <div className="space-y-0.5 max-w-2xl">
                        <div className="flex items-center gap-2">
                          <span className="px-2 py-0.5 rounded-md bg-zinc-100 text-zinc-700 font-mono tabular-nums text-[11px] font-bold">
                            #{String(idx + 1).padStart(2, '0')}
                          </span>
                          <span className="text-xs font-bold text-zinc-900">
                            {it.projectTitle}
                          </span>
                          <Badge
                            variant={
                              it.status === 'ready' || it.status === 'rendered'
                                ? 'emerald'
                                : it.status === 'error'
                                  ? 'crimson'
                                  : 'amber'
                            }
                            mono
                          >
                            {it.status}
                          </Badge>
                          {it.totalDurationSec > 0 && (
                            <span className="text-[11px] font-mono tabular-nums text-zinc-400">
                              {it.sceneCount} cảnh • {Math.round(it.totalDurationSec)}s
                            </span>
                          )}
                        </div>
                        <p className="text-xs text-zinc-500 line-clamp-1">
                          {it.prompt}
                        </p>
                      </div>

                      <div className="flex items-center gap-2">
                        {it.renderOutputUrl && (
                          <a
                            href={it.renderOutputUrl}
                            download
                            className="px-3 py-1.5 rounded-lg bg-emerald-600 hover:bg-emerald-500 text-white text-xs font-semibold flex items-center gap-1"
                          >
                            <Download className="w-3 h-3" />
                            <span>Tải MP4</span>
                          </a>
                        )}
                        {it.projectId && (
                          <Button
                            variant="secondary"
                            size="sm"
                            onClick={() => onOpenProjectInStudio(it.projectId)}
                          >
                            <Film className="w-3.5 h-3.5 text-[#E11D48]" />
                            <span>Mở trong Studio</span>
                          </Button>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            );
          })
        )}
      </div>
    </div>
  );
};