Spaces:
Sleeping

File size: 15,963 Bytes
9713441
e602d40
 
 
 
 
 
 
 
 
 
 
 
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
 
 
 
 
9713441
 
 
e602d40
9713441
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
e602d40
9713441
e602d40
 
 
 
9713441
 
 
 
 
 
e602d40
 
 
 
 
9713441
 
 
 
 
 
 
 
 
 
e602d40
9713441
e602d40
 
 
 
9713441
 
e602d40
 
9713441
 
e602d40
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
 
 
e602d40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
e602d40
9713441
 
 
e602d40
 
 
9713441
 
 
 
 
e602d40
9713441
 
e602d40
9713441
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e602d40
9713441
 
 
 
 
 
 
 
e602d40
9713441
 
e602d40
 
9713441
 
 
 
e602d40
 
 
 
9713441
 
e602d40
 
9713441
 
 
 
e602d40
 
9713441
 
 
 
 
e602d40
 
 
 
9713441
 
 
 
 
e602d40
 
9713441
e602d40
 
 
9713441
 
 
e602d40
9713441
 
 
e602d40
9713441
 
 
 
 
 
 
 
 
e602d40
 
 
9713441
 
 
 
 
e602d40
 
 
 
 
9713441
 
 
 
 
 
e602d40
 
 
9713441
 
 
e602d40
 
9713441
 
 
 
 
 
 
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
import React, { useState } from 'react';
import {
  Globe,
  Search,
  Upload,
  Sparkles,
  Tag,
  RefreshCw,
  Trash2,
  Eye,
  FolderOpen,
  CheckCircle2,
} from 'lucide-react';
import { api } from '../api';
import type { AssetItem } from '@olokaflow/shared';
import { Button, Badge } from './ui/primitives';

interface Props {
  assets: AssetItem[];
  onRefresh: () => void;
}

export const AssetLibraryView: React.FC<Props> = ({ assets, onRefresh }) => {
  const [scrapeUrl, setScrapeUrl] = useState('');
  const [brandTag, setBrandTag] = useState('');
  const [webSearchQuery, setWebSearchQuery] = useState('');
  const [scraping, setScraping] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [searchingWeb, setSearchingWeb] = useState(false);
  const [statusMessage, setStatusMessage] = useState('');
  const [selectedAsset, setSelectedAsset] = useState<AssetItem | null>(null);
  const [filterSource, setFilterSource] = useState<string>('all');

  async function handleScrapeUrl(e: React.FormEvent) {
    e.preventDefault();
    if (!scrapeUrl.trim()) return;
    setScraping(true);
    setStatusMessage('Đang cào hình ảnh, logo SVG & video từ URL và phân tích bằng Vision AI...');
    try {
      const res = await api.scrapeUrlAssets({
        url: scrapeUrl.trim(),
        brandTag: brandTag.trim() || undefined,
      });
      setStatusMessage(
        `Đã thu thập và phân tích AI ${res.scrapedAssets?.length || 0} tài nguyên từ "${
          res.pageInfo?.pageTitle || scrapeUrl
        }".`
      );
      setScrapeUrl('');
      onRefresh();
    } catch (err: any) {
      setStatusMessage(`Lỗi cào URL: ${err.message}`);
    } finally {
      setScraping(false);
    }
  }

  async function handleWebSearch(e: React.FormEvent) {
    e.preventDefault();
    if (!webSearchQuery.trim()) return;
    setSearchingWeb(true);
    setStatusMessage('Đang tìm hình ảnh thực tế trên Web & phân tích Vision AI...');
    try {
      const res = await api.searchWebAssets({
        query: webSearchQuery.trim(),
        limit: 4,
      });
      setStatusMessage(
        `Đã tìm và phân tích ${res.foundAssets?.length || 0} hình ảnh thực tế cho "${webSearchQuery}".`
      );
      setWebSearchQuery('');
      onRefresh();
    } catch (err: any) {
      setStatusMessage(`Lỗi tìm ảnh: ${err.message}`);
    } finally {
      setSearchingWeb(false);
    }
  }

  async function handleFileUpload(e: React.ChangeEvent<HTMLInputElement>) {
    const files = e.target.files;
    if (!files || files.length === 0) return;
    setUploading(true);
    setStatusMessage(`Đang tải lên và phân tích ${files.length} tệp tin...`);
    try {
      for (let i = 0; i < files.length; i++) {
        await api.uploadAssetFile(files[i]);
      }
      setStatusMessage(`Đã tải lên và phân tích thành công ${files.length} tài nguyên.`);
      onRefresh();
    } catch (err: any) {
      setStatusMessage(`Lỗi upload: ${err.message}`);
    } finally {
      setUploading(false);
      e.target.value = '';
    }
  }

  const filteredAssets = assets.filter((a) =>
    filterSource === 'all' ? true : a.source === filterSource
  );

  return (
    <div className="space-y-6">
      {/* Top Action Cards: URL Scraper, Web Search & Direct Upload */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
        {/* URL Scraper Card */}
        <form
          onSubmit={handleScrapeUrl}
          className="lg:col-span-6 fliki-card p-5 bg-white space-y-3"
        >
          <div className="flex items-center justify-between">
            <Badge variant="crimson">
              <Globe className="w-3 h-3" />
              5-Stage Web Asset Scraper + Vision OCR
            </Badge>
            <span className="text-[11px] text-zinc-400 font-mono">
              Magic Bytes + Brand Guard
            </span>
          </div>
          <h3 className="text-base font-bold text-zinc-900">
            Cào Ảnh Sản Phẩm, Logo SVG & Video Từ URL Bất Kỳ
          </h3>
          <p className="text-xs text-zinc-500">
            Tự động bóc tách og:image, JSON-LD product gallery, thẻ &lt;img&gt;, &lt;svg&gt;, kiểm tra Magic Bytes và phân tích bằng Vision AI.
          </p>
          <div className="flex flex-col sm:flex-row gap-2">
            <input
              type="url"
              value={scrapeUrl}
              onChange={(e) => setScrapeUrl(e.target.value)}
              placeholder="https://example.com/product-page..."
              className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"
              required
            />
            <input
              type="text"
              value={brandTag}
              onChange={(e) => setBrandTag(e.target.value)}
              placeholder="Nhãn thương hiệu (tùy chọn)"
              className="sm:w-40 bg-zinc-50 border border-zinc-200 rounded-xl px-3 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"
            />
            <Button type="submit" variant="primary" disabled={scraping}>
              <Globe className="w-3.5 h-3.5" />
              <span>{scraping ? 'Đang cào...' : 'Cào & Phân Tích'}</span>
            </Button>
          </div>
        </form>

        {/* Web Search & File Upload Card */}
        <div className="lg:col-span-6 fliki-card p-5 bg-white space-y-3 flex flex-col justify-between">
          <div>
            <Badge variant="default">
              <Search className="w-3 h-3" />
              Tìm Ảnh Web Thực Tế & Upload Đa Phương Thức
            </Badge>
            <h3 className="text-base font-bold text-zinc-900 mt-1.5">
              Tìm Ảnh Minh Họa Thực Tế Hoặc Tải Lên Từ Máy Tính
            </h3>
          </div>

          <form onSubmit={handleWebSearch} className="flex gap-2">
            <input
              type="text"
              value={webSearchQuery}
              onChange={(e) => setWebSearchQuery(e.target.value)}
              placeholder="Tìm ảnh thực tế (VD: coffee shop, skincare, AI datacenter)..."
              className="flex-1 bg-zinc-50 border border-zinc-200 rounded-xl px-3.5 py-2 text-xs text-zinc-900 focus:outline-none focus:border-[#E11D48]"
            />
            <Button type="submit" variant="dark" disabled={searchingWeb}>
              <Search className="w-3.5 h-3.5" />
              <span>{searchingWeb ? 'Đang tìm...' : 'Tìm Ảnh Web'}</span>
            </Button>
          </form>

          <div className="flex items-center justify-between pt-2 border-t border-zinc-100">
            <span className="text-xs text-zinc-500">
              Hỗ trợ PNG, JPG, WebP, SVG, MP4, WebM, MP3, WAV
            </span>
            <label className="px-4 py-2 rounded-xl bg-zinc-900 hover:bg-zinc-800 text-white text-xs font-semibold flex items-center gap-1.5 cursor-pointer">
              <Upload className="w-3.5 h-3.5" />
              <span>{uploading ? 'Đang tải lên...' : 'Tải Tệp Lên'}</span>
              <input
                type="file"
                multiple
                accept="image/*,video/*,audio/*,.svg"
                onChange={handleFileUpload}
                className="hidden"
              />
            </label>
          </div>
        </div>
      </div>

      {statusMessage && (
        <div className="fliki-card p-3.5 bg-zinc-50 border-zinc-200 text-xs font-semibold text-zinc-800 flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4 text-[#E11D48] shrink-0" />
          <span>{statusMessage}</span>
        </div>
      )}

      {/* Filter Bar */}
      <div className="flex flex-wrap items-center justify-between gap-3">
        <div className="flex items-center gap-1.5 flex-wrap">
          {[
            { id: 'all', label: `Tất cả (${assets.length})`, Icon: FolderOpen },
            { id: 'url_scrape', label: 'Cào từ URL', Icon: Globe },
            { id: 'ai_generated', label: 'Ảnh AI Tham Khảo', Icon: Sparkles },
            { id: 'web_fallback', label: 'Ảnh Thực Tế Web', Icon: Search },
            { id: 'upload', label: 'Tải lên', Icon: Upload },
          ].map((f) => {
            const Icon = f.Icon;
            return (
              <button
                key={f.id}
                onClick={() => setFilterSource(f.id)}
                className={`px-3 py-1.5 rounded-xl text-xs font-semibold border transition-all cursor-pointer flex items-center gap-1.5 ${
                  filterSource === f.id
                    ? 'bg-[#E11D48] text-white border-[#E11D48]'
                    : 'bg-white text-zinc-600 border-zinc-200 hover:border-zinc-300'
                }`}
              >
                <Icon className="w-3.5 h-3.5" />
                <span>{f.label}</span>
              </button>
            );
          })}
        </div>
      </div>

      {/* Asset Grid + Deep AI Analysis Drawer */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-5">
        <div className="lg:col-span-8 grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3.5">
          {filteredAssets.map((asset) => {
            const isSel = selectedAsset?.id === asset.id;
            return (
              <div
                key={asset.id}
                onClick={() => setSelectedAsset(asset)}
                className={`${
                  isSel ? 'fliki-card-active' : 'fliki-card'
                } overflow-hidden bg-white cursor-pointer flex flex-col`}
              >
                <div className="aspect-square bg-zinc-100 relative overflow-hidden">
                  <img
                    src={asset.publicUrl}
                    alt={asset.name}
                    className="w-full h-full object-cover"
                  />
                  <span className="absolute top-2 left-2 px-2 py-0.5 rounded-md bg-white/90 backdrop-blur-xs text-zinc-800 border border-zinc-200 text-[10px] font-mono font-semibold">
                    {asset.source}
                  </span>
                  {asset.brandTag && (
                    <span className="absolute bottom-2 left-2 px-2 py-0.5 rounded-md bg-[#E11D48] text-white text-[10px] font-semibold flex items-center gap-1">
                      <Tag className="w-2.5 h-2.5" />
                      {asset.brandTag}
                    </span>
                  )}
                </div>
                <div className="p-2.5 flex-1 flex flex-col justify-between">
                  <div>
                    <div className="text-xs font-bold text-zinc-900 truncate">
                      {asset.name}
                    </div>
                    <div className="text-[11px] text-zinc-500 line-clamp-2 mt-0.5">
                      {asset.analysis?.shortCaption || asset.analysis?.subject}
                    </div>
                  </div>
                  <div className="mt-2 pt-2 border-t border-zinc-100 flex items-center justify-between text-[10px] text-zinc-400 font-mono tabular-nums">
                    <span>
                      {asset.width}×{asset.height}
                    </span>
                    <span>{(asset.sizeBytes / 1024).toFixed(0)} KB</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>

        {/* Right 4 Cols: Multimodal AI Analysis Inspector */}
        <div className="lg:col-span-4">
          {selectedAsset ? (
            <div className="fliki-card p-5 bg-white space-y-4 sticky top-4">
              <div className="aspect-video rounded-xl overflow-hidden bg-zinc-100 border border-zinc-200">
                <img
                  src={selectedAsset.publicUrl}
                  alt={selectedAsset.name}
                  className="w-full h-full object-contain"
                />
              </div>

              <div>
                <h4 className="text-sm font-bold text-zinc-900">
                  {selectedAsset.name}
                </h4>
                <p className="text-xs text-zinc-500 mt-0.5 font-mono tabular-nums">
                  Nguồn: <span className="font-semibold">{selectedAsset.source}</span> •{' '}
                  {selectedAsset.width}×{selectedAsset.height}px
                </p>
              </div>

              <div className="p-3.5 rounded-xl bg-zinc-50 border border-zinc-200 space-y-2 text-xs">
                <div className="font-bold text-zinc-800 uppercase tracking-wider text-[11px] flex items-center gap-1.5">
                  <Eye className="w-3.5 h-3.5 text-[#E11D48]" />
                  <span>Hồ sơ Phân tích Đa phương thức (Vision AI)</span>
                </div>
                <div>
                  <span className="font-semibold text-zinc-600">Chủ thể: </span>
                  <span className="text-zinc-900">
                    {selectedAsset.analysis?.subject || 'Đã phân tích'}
                  </span>
                </div>
                <div>
                  <span className="font-semibold text-zinc-600">Mô tả: </span>
                  <span className="text-zinc-800">
                    {selectedAsset.analysis?.shortCaption}
                  </span>
                </div>
                {selectedAsset.analysis?.ocrText && (
                  <div>
                    <span className="font-semibold text-zinc-600">
                      Chữ OCR trên ảnh:{' '}
                    </span>
                    <span className="font-mono text-[#E11D48]">
                      "{selectedAsset.analysis.ocrText}"
                    </span>
                  </div>
                )}
                <div>
                  <span className="font-semibold text-zinc-600">
                    Cảnh phù hợp nhất:{' '}
                  </span>
                  <Badge variant="default" mono>
                    {selectedAsset.analysis?.bestSceneFit || 'Key_Feature'}
                  </Badge>
                </div>
                {selectedAsset.analysis?.dominantColors && (
                  <div className="flex items-center gap-1.5 pt-1">
                    <span className="font-semibold text-zinc-600">Bảng màu:</span>
                    {selectedAsset.analysis.dominantColors.map((hex, i) => (
                      <span
                        key={i}
                        className="w-5 h-5 rounded-full border border-zinc-300 shadow-2xs"
                        style={{ backgroundColor: hex }}
                        title={hex}
                      />
                    ))}
                  </div>
                )}
              </div>

              <div className="flex gap-2">
                <Button
                  variant="dark"
                  className="flex-1"
                  onClick={async () => {
                    await api.reanalyzeAsset(selectedAsset.id);
                    onRefresh();
                  }}
                >
                  <RefreshCw className="w-3.5 h-3.5" />
                  <span>Phân tích lại bằng Vision AI</span>
                </Button>
                <Button
                  variant="danger"
                  onClick={async () => {
                    await api.deleteAsset(selectedAsset.id);
                    setSelectedAsset(null);
                    onRefresh();
                  }}
                >
                  <Trash2 className="w-3.5 h-3.5" />
                  <span>Xóa</span>
                </Button>
              </div>
            </div>
          ) : (
            <div className="fliki-card p-8 bg-white text-center text-zinc-400 text-xs">
              Bấm vào bất kỳ tài nguyên nào bên trái để xem hồ sơ phân tích Vision AI, chữ OCR, bảng màu và gợi ý phân cảnh.
            </div>
          )}
        </div>
      </div>
    </div>
  );
};