File size: 12,401 Bytes
030c057
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useState } from 'react'
import JSZip from 'jszip'
import ImageLightbox from './ImageLightbox'

const API_BASE = '/api'
const AUTH_TOKEN_KEY = 'amalfa_auth_token'

function authHeaders() {
  const token = typeof localStorage !== 'undefined' ? localStorage.getItem(AUTH_TOKEN_KEY) : null
  if (!token) return {}
  return { Authorization: `Bearer ${token}` }
}

function proxyImageUrl(url) {
  return url ? `${API_BASE}/proxy-image?url=${encodeURIComponent(url)}` : ''
}

function downloadImage(url, filename) {
  const a = document.createElement('a')
  a.href = proxyImageUrl(url) || url
  a.download = filename
  document.body.appendChild(a)
  a.click()
  a.remove()
}

async function fetchImageBlob(url) {
  if (!url) throw new Error('Missing image URL')
  try {
    const proxied = await fetch(proxyImageUrl(url))
    if (proxied.ok) return await proxied.blob()
  } catch (_) {}
  const direct = await fetch(url)
  if (!direct.ok) throw new Error('Failed to fetch image')
  return await direct.blob()
}

export default function Variations({ onLogout }) {
  const [imageModels, setImageModels] = useState([])
  const [selectedImageModel, setSelectedImageModel] = useState('nano-banana-2')
  const [aspectRatio, setAspectRatio] = useState('1:1')
  const [variationCount, setVariationCount] = useState(10)
  const [userPrompt, setUserPrompt] = useState('')
  const [winningImageUrl, setWinningImageUrl] = useState('')
  const [winningPreviewUrl, setWinningPreviewUrl] = useState('')
  const [uploading, setUploading] = useState(false)
  const [generating, setGenerating] = useState(false)
  const [progress, setProgress] = useState({ done: 0, total: 0 })
  const [results, setResults] = useState([])
  const [selected, setSelected] = useState([])
  const [downloading, setDownloading] = useState(false)
  const [error, setError] = useState(null)
  const [lightboxImage, setLightboxImage] = useState(null)

  useEffect(() => {
    fetch(`${API_BASE}/image-models`, { headers: authHeaders() })
      .then((r) => {
        if (r.status === 401) {
          localStorage.removeItem(AUTH_TOKEN_KEY)
          onLogout?.()
          return null
        }
        return r.ok ? r.json() : null
      })
      .then((data) => {
        if (!data) return
        setImageModels(data.models || [])
        if (data.default) setSelectedImageModel(data.default)
      })
      .catch(() => {})
  }, [onLogout])

  useEffect(() => {
    return () => {
      if (winningPreviewUrl) URL.revokeObjectURL(winningPreviewUrl)
    }
  }, [winningPreviewUrl])

  async function handleUpload(file) {
    if (!file) return
    if (winningPreviewUrl) URL.revokeObjectURL(winningPreviewUrl)
    setWinningPreviewUrl(URL.createObjectURL(file))
    setUploading(true)
    setError(null)
    try {
      const form = new FormData()
      form.append('file', file)
      const res = await fetch(`${API_BASE}/upload-reference`, {
        method: 'POST',
        headers: authHeaders(),
        body: form,
      })
      if (res.status === 401) {
        localStorage.removeItem(AUTH_TOKEN_KEY)
        onLogout?.()
        return
      }
      const data = await res.json().catch(() => ({}))
      if (!res.ok) throw new Error(data.detail || 'Upload failed')
      setWinningImageUrl(data.url || '')
    } catch (e) {
      setError(e.message || 'Upload failed')
    } finally {
      setUploading(false)
    }
  }

  async function handleGenerate() {
    if (!winningImageUrl) {
      setError('Upload a winning creative first.')
      return
    }
    setGenerating(true)
    setError(null)
    setResults([])
    setSelected([])
    setProgress({ done: 0, total: variationCount })
    try {
      const res = await fetch(`${API_BASE}/generate-variations/stream`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...authHeaders() },
        body: JSON.stringify({
          image_url: winningImageUrl,
          n: variationCount,
          model_key: selectedImageModel,
          aspect_ratio: aspectRatio,
          user_prompt: userPrompt || undefined,
        }),
      })
      if (res.status === 401) {
        localStorage.removeItem(AUTH_TOKEN_KEY)
        onLogout?.()
        return
      }
      if (!res.ok) {
        const data = await res.json().catch(() => ({}))
        throw new Error(data.detail || 'Variation generation failed')
      }
      const reader = res.body.getReader()
      const decoder = new TextDecoder()
      let buffer = ''
      while (true) {
        const { done, value } = await reader.read()
        if (done) break
        buffer += decoder.decode(value, { stream: true })
        const chunks = buffer.split('\n\n')
        buffer = chunks.pop() || ''
        for (const chunk of chunks) {
          const dataLine = chunk.split('\n').find((l) => l.startsWith('data: '))
          if (!dataLine) continue
          try {
            const payload = JSON.parse(dataLine.slice(6))
            if (payload.event === 'result' && payload.data) {
              const rowId = `${payload.data.variation_id ?? 'v'}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
              setResults((prev) => [...prev, { ...payload.data, rowId }])
              setProgress((prev) => ({ ...prev, done: prev.done + 1 }))
            } else if (payload.event === 'error') {
              setError(payload.message || 'Variation generation failed')
            }
          } catch (_) {}
        }
      }
    } catch (e) {
      setError(e.message || 'Variation generation failed')
    } finally {
      setGenerating(false)
    }
  }

  function toggleSelect(rowId) {
    setSelected((prev) => (prev.includes(rowId) ? prev.filter((id) => id !== rowId) : [...prev, rowId]))
  }

  async function handleDownloadSelected() {
    const toDownload = results.filter((r) => r.image_url && selected.includes(r.rowId))
    if (!toDownload.length) return
    setDownloading(true)
    try {
      const zip = new JSZip()
      await Promise.all(
        toDownload.map(async (item, idx) => {
          const blob = await fetchImageBlob(item.image_url)
          const id = String(item.variation_id ?? idx + 1).padStart(2, '0')
          const slug = (item.concept_name || 'variation')
            .replace(/[^a-z0-9]+/gi, '-')
            .toLowerCase()
            .replace(/^-|-$/g, '') || 'variation'
          zip.file(`Amalfa-variation-${id}-${slug}.png`, blob)
        })
      )
      const blob = await zip.generateAsync({ type: 'blob' })
      const a = document.createElement('a')
      a.href = URL.createObjectURL(blob)
      a.download = 'Amalfa-variations-selected.zip'
      a.click()
      URL.revokeObjectURL(a.href)
    } catch (e) {
      setError(e.message || 'Failed to prepare ZIP')
    } finally {
      setDownloading(false)
    }
  }

  return (
    <section className="card variations-card">
      {lightboxImage && (
        <ImageLightbox
          src={lightboxImage.src}
          alt={lightboxImage.alt}
          onClose={() => setLightboxImage(null)}
        />
      )}
      <h2>Winning Creative Variations</h2>
      <p className="gallery-desc">Upload your best-performing creative and generate multiple fresh variations.</p>
      {error && <p className="error">{error}</p>}

      <div className="variations-controls">
        <label>
          <span>Winning creative image</span>
          <input
            type="file"
            accept="image/png,image/jpeg,image/webp"
            onChange={(e) => handleUpload(e.target.files?.[0])}
            disabled={uploading || generating}
          />
        </label>
        <label>
          <span>User prompt (optional)</span>
          <input
            type="text"
            value={userPrompt}
            onChange={(e) => setUserPrompt(e.target.value)}
            placeholder="e.g. Make it moodier, cinematic lighting, more close-up angles"
            disabled={generating}
          />
        </label>
        <label>
          <span>How many variations</span>
          <input
            type="range"
            min="1"
            max="30"
            value={variationCount}
            onChange={(e) => setVariationCount(Number(e.target.value))}
            disabled={generating}
          />
          <strong>{variationCount}</strong>
        </label>
        <label>
          <span>Image model</span>
          <select
            value={selectedImageModel}
            onChange={(e) => setSelectedImageModel(e.target.value)}
            disabled={generating}
          >
            {imageModels.map((m) => (
              <option key={m.key} value={m.key}>
                {m.label || m.key}
              </option>
            ))}
          </select>
        </label>
        <label>
          <span>Aspect ratio</span>
          <select value={aspectRatio} onChange={(e) => setAspectRatio(e.target.value)} disabled={generating}>
            <option value="1:1">1:1</option>
            <option value="16:9">16:9</option>
            <option value="9:16">9:16</option>
          </select>
        </label>
      </div>

      {winningImageUrl && (
        <div className="variations-winning-preview">
          <img src={winningPreviewUrl || winningImageUrl} alt="Winning creative" />
        </div>
      )}

      <div className="variations-actions">
        <button type="button" className="btn-run" disabled={generating || uploading || !winningImageUrl} onClick={handleGenerate}>
          {generating ? 'Generating…' : `Generate ${variationCount} Variations`}
        </button>
        {generating && <span className="gallery-item-date">Progress: {progress.done}/{progress.total}</span>}
      </div>

      {results.length > 0 && (
        <>
          <div className="gallery-toolbar">
            <label className="gallery-select-all">
              <input
                type="checkbox"
                checked={selected.length === results.length && results.length > 0}
                onChange={(e) => (e.target.checked ? setSelected(results.map((r) => r.rowId)) : setSelected([]))}
              />
              Select all
            </label>
            <button
              type="button"
              className="btn-download-zip"
              disabled={downloading || selected.length === 0}
              onClick={handleDownloadSelected}
            >
              {downloading ? 'Preparing…' : `Download selected (${selected.length})`}
            </button>
          </div>
          <div className="gallery-grid">
          {results.map((item, idx) => (
            <div className="gallery-item" key={item.rowId || `${item.variation_id || idx}-${idx}`}>
              <div className="gallery-item-img-wrap">
                {item.image_url ? (
                  <img
                    src={proxyImageUrl(item.image_url)}
                    alt={item.concept_name || `Variation ${idx + 1}`}
                    className="gallery-item-img img-expandable"
                    onClick={() =>
                      setLightboxImage({
                        src: proxyImageUrl(item.image_url),
                        alt: item.concept_name || `Variation ${idx + 1}`,
                      })
                    }
                  />
                ) : (
                  <div className="gallery-item-placeholder">Failed</div>
                )}
                <label className="gallery-item-checkbox">
                  <input
                    type="checkbox"
                    checked={selected.includes(item.rowId)}
                    onChange={() => toggleSelect(item.rowId)}
                  />
                  <span>Select</span>
                </label>
              </div>
              <div className="gallery-item-footer">
                <p className="gallery-item-concept">#{item.variation_id || idx + 1} {item.concept_name || 'Variation'}</p>
                {item.error ? (
                  <p className="error">{item.error}</p>
                ) : (
                  <button
                    type="button"
                    className="btn-gallery-download-one"
                    onClick={() => downloadImage(item.image_url, `variation-${item.variation_id || idx + 1}.png`)}
                  >
                    Download
                  </button>
                )}
              </div>
            </div>
          ))}
        </div>
        </>
      )}
    </section>
  )
}