File size: 27,974 Bytes
4c888b7
 
 
 
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f7b6b
 
 
 
b63786a
34f7b6b
 
 
b63786a
34f7b6b
 
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c888b7
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c888b7
 
 
 
 
 
 
 
 
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c888b7
 
 
 
 
 
 
 
 
 
 
b63786a
 
 
 
 
4c888b7
 
 
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c888b7
 
 
 
 
 
b63786a
 
 
 
 
 
4c888b7
 
 
 
 
 
 
 
34f7b6b
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4c888b7
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f7b6b
 
 
 
 
 
 
b63786a
34f7b6b
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f7b6b
 
b63786a
 
 
 
34f7b6b
b63786a
 
34f7b6b
 
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34f7b6b
 
 
 
 
 
 
 
 
b63786a
 
 
 
34f7b6b
b63786a
 
 
 
34f7b6b
b63786a
 
34f7b6b
b63786a
 
 
 
 
 
 
34f7b6b
b63786a
 
 
34f7b6b
b63786a
 
 
 
34f7b6b
b63786a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
import React, { useEffect, useRef, useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { apiUrl, getJson } from '../utils/api';
import { downloadAsset, resolveDownloadUrl } from '../utils/downloadAsset';
import {
  ASSISTANT_ACTION_EVENT_NAME,
  clearPendingAssistantAction,
  readPendingAssistantAction,
} from '../utils/assistantActions';
import '../styles/ImageGenerator.css';

const GENERATION_MODES = [
  {
    value: 'text-to-image',
    label: 'Text to Image',
    description: 'Create images from prompts.',
  },
  {
    value: 'text-to-video',
    label: 'Text to Video',
    description: 'Turn prompts into short videos.',
  },
  {
    value: 'image-to-video',
    label: 'Image to Video',
    description: 'Animate an uploaded image.',
  },
];

const RATIO_OPTIONS = [
  { value: '1:1', label: '1:1 Square' },
  { value: '16:9', label: '16:9 Landscape' },
  { value: '9:16', label: '9:16 Portrait' },
  { value: '4:3', label: '4:3 Classic' },
  { value: '3:4', label: '3:4 Portrait Classic' },
];

const QUALITY_OPTIONS = [
  { value: 'fast', label: 'Fast' },
  { value: 'balanced', label: 'Balanced' },
  { value: 'high', label: 'High' },
];

const MAX_PROMPT_LENGTH = 2000;
const MAX_PREVIEW_RETRIES = 2;
const PREVIEW_RETRY_DELAY_MS = 1500;
const SETTINGS_STORAGE_KEY = 'image-generator-settings';

const readFileAsDataUrl = (file) =>
  new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = () => resolve(reader.result);
    reader.onerror = () => reject(new Error('Could not load the selected image'));
    reader.readAsDataURL(file);
  });

const findOptionLabel = (options, value) =>
  options.find((option) => option.value === value)?.label || value;

const findModeLabel = (mode) =>
  GENERATION_MODES.find((option) => option.value === mode)?.label || mode;

const isValidOption = (options, value) => options.some((option) => option.value === value);

const getStoredSetting = (settingKey, fallbackValue, options) => {
  if (typeof window === 'undefined') {
    return fallbackValue;
  }

  try {
    const storedSettings = JSON.parse(window.localStorage.getItem(SETTINGS_STORAGE_KEY) || '{}');
    const storedValue = storedSettings[settingKey];
    return isValidOption(options, storedValue) ? storedValue : fallbackValue;
  } catch (error) {
    return fallbackValue;
  }
};

const isDataUrl = (assetUrl = '') => assetUrl.startsWith('data:');
const isRemoteUrl = (assetUrl = '') => /^https?:\/\//i.test(assetUrl);
const isProxyPreviewUrl = (assetUrl = '') => assetUrl.includes('/api/image/preview?');

const getResolvedAssetUrl = (assetUrl = '') => {
  if (!assetUrl || isDataUrl(assetUrl) || isRemoteUrl(assetUrl)) {
    return assetUrl;
  }

  return apiUrl(assetUrl.startsWith('/') ? assetUrl : `/${assetUrl}`);
};

const getResolvedImageUrl = (imageUrl = '') => {
  if (!imageUrl || isDataUrl(imageUrl)) {
    return imageUrl;
  }

  if (isProxyPreviewUrl(imageUrl)) {
    return isRemoteUrl(imageUrl) ? imageUrl : apiUrl(imageUrl);
  }

  if (isRemoteUrl(imageUrl)) {
    return apiUrl(`/api/image/preview?source=${encodeURIComponent(imageUrl)}`);
  }

  return apiUrl(imageUrl.startsWith('/') ? imageUrl : `/${imageUrl}`);
};

const canRetryPreview = (imageUrl = '') => Boolean(imageUrl) && !isDataUrl(imageUrl);

const getPreviewUrl = (imageUrl = '', retryCount = 0) => {
  const resolvedImageUrl = getResolvedImageUrl(imageUrl);

  if (!resolvedImageUrl || isDataUrl(resolvedImageUrl)) {
    return resolvedImageUrl;
  }

  try {
    const url = new URL(resolvedImageUrl, window.location.origin);
    url.searchParams.set('previewAttempt', String(retryCount));
    return url.toString();
  } catch (error) {
    const separator = resolvedImageUrl.includes('?') ? '&' : '?';
    return `${resolvedImageUrl}${separator}previewAttempt=${retryCount}`;
  }
};

const getFileExtension = (assetUrl = '', assetType = 'image') => {
  if (assetType === 'video') {
    if (assetUrl.includes('.webm') || assetUrl.includes('video/webm')) return 'webm';
    if (assetUrl.includes('.mov') || assetUrl.includes('video/quicktime')) return 'mov';
    if (assetUrl.includes('.m4v') || assetUrl.includes('video/x-m4v')) return 'm4v';
    return 'mp4';
  }

  if (assetUrl.includes('image/svg+xml')) return 'svg';
  if (assetUrl.includes('image/png')) return 'png';
  if (assetUrl.includes('image/webp')) return 'webp';
  return 'jpg';
};

  const getPromptPlaceholder = (mode) => {
    if (mode === 'text-to-video') {
      return 'Describe the video you want to create... (e.g., neon cyberpunk street, camera motion)';
    }

    if (mode === 'image-to-video') {
      return 'Optional: describe how the image should animate...';
    }

    return 'Describe the image you want to create... (e.g., futuristic city at sunset)';
  };

const getGenerateButtonLabel = (mode, loading) => {
  if (loading) {
    if (mode === 'text-to-image') return 'Generating Image...';
    return 'Generating Video...';
  }

  if (mode === 'text-to-video') return 'Generate Video';
  if (mode === 'image-to-video') return 'Animate Image';
  return 'Generate Image';
};

const ImageGenerator = () => {
  const [mode, setMode] = useState('text-to-image');
  const [prompt, setPrompt] = useState('');
  const [ratio, setRatio] = useState(() => getStoredSetting('ratio', '1:1', RATIO_OPTIONS));
  const [quality, setQuality] = useState(() => getStoredSetting('quality', 'balanced', QUALITY_OPTIONS));
  const [sourceImage, setSourceImage] = useState('');
  const [sourceImageName, setSourceImageName] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [imgStatus, setImgStatus] = useState('idle');
  const [previewRetryCount, setPreviewRetryCount] = useState(0);
  const [error, setError] = useState('');
  const [videoStatus, setVideoStatus] = useState(null);
  const [videoStatusLoading, setVideoStatusLoading] = useState(false);
  const [publishMessage, setPublishMessage] = useState('');
  const [publishing, setPublishing] = useState(false);
  const { token, user, setUser } = useAuth();
  const previewRetryTimeoutRef = useRef(null);
  const lastAssistantActionIdRef = useRef('');

  useEffect(() => () => {
    if (previewRetryTimeoutRef.current) {
      window.clearTimeout(previewRetryTimeoutRef.current);
    }
  }, []);

  useEffect(() => {
    if (typeof window === 'undefined') {
      return;
    }

    window.localStorage.setItem(
      SETTINGS_STORAGE_KEY,
      JSON.stringify({ ratio, quality })
    );
  }, [ratio, quality]);

  useEffect(() => {
    if (previewRetryTimeoutRef.current) {
      window.clearTimeout(previewRetryTimeoutRef.current);
    }

    setPreviewRetryCount(0);
    setImgStatus(result?.assetType === 'image' ? 'loading' : 'idle');
  }, [result?.id, result?.assetType]);

  useEffect(() => {
    setError('');
    setPublishMessage('');
    setResult(null);
    setPublishing(false);
    setVideoStatus(null);
    setVideoStatusLoading(false);

    if (mode !== 'image-to-video') {
      setSourceImage('');
      setSourceImageName('');
    }
  }, [mode]);

  useEffect(() => {
    let isCancelled = false;

    if (mode === 'text-to-image' || !token) {
      setVideoStatus(null);
      setVideoStatusLoading(false);
      return undefined;
    }

    const loadVideoStatus = async () => {
      setVideoStatusLoading(true);

      try {
        const data = await getJson('/api/image/video-status', {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!isCancelled) {
          setVideoStatus(data.video || null);
        }
      } catch (err) {
        if (!isCancelled) {
          setVideoStatus({
            canGenerate: true,
            level: 'warning',
            message: err.message || 'Could not load video setup details.',
          });
        }
      } finally {
        if (!isCancelled) {
          setVideoStatusLoading(false);
        }
      }
    };

    loadVideoStatus();

    return () => {
      isCancelled = true;
    };
  }, [mode, token]);

  useEffect(() => {
    if (typeof window === 'undefined') {
      return undefined;
    }

    const applyAssistantAction = async (action) => {
      if (!action?.id || action.id === lastAssistantActionIdRef.current) {
        return;
      }

      if (action.type !== 'generate-image' && action.type !== 'generate-video') {
        return;
      }

      lastAssistantActionIdRef.current = action.id;
      const nextMode = action.type === 'generate-video' ? 'text-to-video' : 'text-to-image';
      const nextPrompt = action.prompt || '';

      setMode(nextMode);
      setPrompt(nextPrompt);
      setError('');
      setPublishMessage('');

      if (action.ratio && isValidOption(RATIO_OPTIONS, action.ratio)) {
        setRatio(action.ratio);
      }

      if (action.quality && isValidOption(QUALITY_OPTIONS, action.quality)) {
        setQuality(action.quality);
      }

      if (!action.autoRun || !nextPrompt) {
        clearPendingAssistantAction(action.id);
        return;
      }

      setLoading(true);
      setImgStatus(nextMode === 'text-to-image' ? 'loading' : 'idle');

      try {
        if (nextMode === 'text-to-video') {
          await generateTextToVideo(nextPrompt);
        } else {
          await generateImage(nextPrompt, {
            ratio: isValidOption(RATIO_OPTIONS, action.ratio) ? action.ratio : ratio,
            quality: isValidOption(QUALITY_OPTIONS, action.quality) ? action.quality : quality,
          });
        }
      } catch (err) {
        setError(err.message || 'Generation failed');
        setImgStatus('error');
      } finally {
        setLoading(false);
      }

      clearPendingAssistantAction(action.id);
    };

    void applyAssistantAction(readPendingAssistantAction());

    const handleAssistantAction = (event) => {
      void applyAssistantAction(event.detail);
    };

    window.addEventListener(ASSISTANT_ACTION_EVENT_NAME, handleAssistantAction);

    return () => {
      window.removeEventListener(ASSISTANT_ACTION_EVENT_NAME, handleAssistantAction);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [quality, ratio, token]);

  const generateImage = async (promptText, options = { ratio, quality }) => {
    const data = await getJson('/api/image/generate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        prompt: promptText,
        ratio: options.ratio,
        quality: options.quality,
      }),
    });

    if (!data?.image?.imageUrl) {
      throw new Error('Image service returned an invalid response');
    }

    if (data.currentUser) {
      setUser(data.currentUser);
    }

    setResult({
      id: data.image.id || Date.now(),
      assetType: 'image',
      generationMode: 'text-to-image',
      prompt: data.image.prompt || promptText,
      assetUrl: data.image.imageUrl,
      ratio: data.image.ratio || options.ratio,
      quality: data.image.quality || options.quality,
      generatedAt: data.image.generatedAt || new Date().toISOString(),
    });
  };

  const generateTextToVideo = async (promptText) => {
    const data = await getJson('/api/image/generate-video', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        prompt: promptText,
      }),
    });

    if (!data?.video?.videoUrl) {
      throw new Error('Video service returned an invalid response');
    }

    setResult({
      id: data.video.id || Date.now(),
      assetType: 'video',
      generationMode: 'text-to-video',
      prompt: data.video.prompt || promptText,
      assetUrl: data.video.videoUrl,
      generatedAt: data.video.generatedAt || new Date().toISOString(),
    });
  };

  const animateImage = async (promptText, imageDataUrl, imageName) => {
    const data = await getJson('/api/image/animate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        prompt: promptText,
        sourceImage: imageDataUrl,
      }),
    });

    if (!data?.video?.videoUrl) {
      throw new Error('Video service returned an invalid response');
    }

    setResult({
      id: data.video.id || Date.now(),
      assetType: 'video',
      generationMode: 'image-to-video',
      prompt: data.video.prompt || promptText,
      assetUrl: data.video.videoUrl,
      generatedAt: data.video.generatedAt || new Date().toISOString(),
      sourceImagePreview: imageDataUrl,
      sourceImageName: imageName,
    });
  };

  const runGenerationRequest = async ({

    nextMode = mode,

    promptText = prompt.trim(),

    nextRatio = ratio,

    nextQuality = quality,

    imageDataUrl = sourceImage,

    imageName = sourceImageName,

    clearPromptAfter = true,

  } = {}) => {
    if (!token) {
      setError('Session expired. Please log in again.');
      return false;
    }

    const trimmedPrompt = promptText.trim();

    if (nextMode !== 'image-to-video' && !trimmedPrompt) {
      setError('Please enter a prompt');
      return false;
    }

    if (nextMode === 'image-to-video' && !imageDataUrl) {
      setError('Please upload a source image first');
      return false;
    }

    setLoading(true);
    setError('');
    setPublishMessage('');
    setImgStatus(nextMode === 'text-to-image' ? 'loading' : 'idle');

    try {
      if (nextMode === 'text-to-video') {
        await generateTextToVideo(trimmedPrompt);
      } else if (nextMode === 'image-to-video') {
        await animateImage(trimmedPrompt, imageDataUrl, imageName);
      } else {
        await generateImage(trimmedPrompt, {
          ratio: nextRatio,
          quality: nextQuality,
        });
      }

      if (clearPromptAfter && nextMode !== 'image-to-video') {
        setPrompt('');
      }

      return true;
    } catch (err) {
      setError(err.message || 'Generation failed');
      setImgStatus('error');
      return false;
    } finally {
      setLoading(false);
    }
  };

  const handleGenerate = async (e) => {
    e.preventDefault();
    await runGenerationRequest();
  };

  const handleSourceImageChange = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    try {
      const dataUrl = await readFileAsDataUrl(file);
      setSourceImage(dataUrl);
      setSourceImageName(file.name);
      setError('');
    } catch (err) {
      setError(err.message || 'Could not load the selected image');
    }
  };

  const handleDownloadAsset = () => {
    if (!result) return;

    downloadAsset({
      assetUrl: result.assetUrl,
      assetType: result.assetType,
      fileName: `${result.generationMode}-${Date.now()}.${getFileExtension(result.assetUrl, result.assetType)}`,
    }).catch((err) => {
      setError(err.message || 'Download failed');
    });
  };

  const handleCopyLink = async () => {
    if (!result) return;

    try {
      const resolvedUrl = result.assetType === 'image'
        ? resolveDownloadUrl(result.assetUrl, 'image')
        : resolveDownloadUrl(result.assetUrl, result.assetType);
      await navigator.clipboard.writeText(resolvedUrl);
      alert(`${result.assetType === 'image' ? 'Image' : 'Video'} link copied to clipboard!`);
    } catch (err) {
      setError(`Could not copy the ${result?.assetType || 'asset'} link`);
    }
  };

  const handleRegenerate = async () => {
    if (!result || !token) return;

    setLoading(true);
    setError('');
    setPublishMessage('');

    try {
      if (result.generationMode === 'text-to-video') {
        await generateTextToVideo(result.prompt);
      } else if (result.generationMode === 'image-to-video') {
        await animateImage(
          result.prompt || '',
          result.sourceImagePreview || sourceImage,
          result.sourceImageName || sourceImageName
        );
      } else {
        await generateImage(result.prompt, {
          ratio: result.ratio || ratio,
          quality: result.quality || quality,
        });
      }
    } catch (err) {
      setError(err.message || 'Could not regenerate the asset');
    } finally {
      setLoading(false);
    }
  };

  const handlePublishToExplore = async () => {
    if (!result || result.assetType !== 'image' || !token) return;

    setPublishing(true);
    setPublishMessage('');

    try {
      const data = await getJson('/api/gallery/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify({
          title: (result.prompt || 'Generated image').slice(0, 120),
          description: result.prompt || '',
          prompt: result.prompt || '',
          imageUrl: result.assetUrl,
          source: 'generated',
        }),
      });

      if (data.currentUser) {
        setUser(data.currentUser);
      }

      setPublishMessage(data.message || 'Published to Explore!');
    } catch (err) {
      setPublishMessage(err.message || 'Could not publish image');
    } finally {
      setPublishing(false);
    }
  };

  const isTextToImageMode = mode === 'text-to-image';
  const isImageToVideoMode = mode === 'image-to-video';
  const videoGenerationBlocked =
    !isTextToImageMode && !videoStatusLoading && videoStatus?.canGenerate === false;
  const videoStatusToneClass = videoStatusLoading
    ? 'is-loading'
    : videoStatus?.level === 'error'
      ? 'is-error'
      : videoStatus?.level === 'warning'
        ? 'is-warning'
        : 'is-ready';

  return (
    <div className="image-generator">

      <div className="generator-form">

        <div className="mode-selector" aria-label="Generation mode">
          {GENERATION_MODES.map((modeOption) => (

            <button

              key={modeOption.value}

              type="button"

              className={`mode-card ${mode === modeOption.value ? 'active' : ''}`}

              onClick={() => setMode(modeOption.value)}

              aria-pressed={mode === modeOption.value}

            >

              <strong>{modeOption.label}</strong>

              <span>{modeOption.description}</span>

            </button>

          ))}

        </div>



        <form onSubmit={handleGenerate}>

          {isImageToVideoMode && (

            <div className="source-upload-section">

              <label className="source-upload-box">

                <span>Upload Source Image</span>

                <input type="file" accept="image/*" onChange={handleSourceImageChange} disabled={loading} />

              </label>



                {sourceImage && (

                  <div className="source-preview">

                    <img src={sourceImage} alt={sourceImageName || 'Source preview'} />

                    <div>

                      <strong>{sourceImageName || 'Source image selected'}</strong>

                      <p>This will animate into a short video.</p>

                    </div>

                  </div>

                )}
            </div>

          )}



          <div className="input-group">

            <textarea

              value={prompt}

              onChange={(e) => setPrompt(e.target.value)}

              placeholder={getPromptPlaceholder(mode)}

              maxLength={MAX_PROMPT_LENGTH}

              rows={4}

              disabled={loading}

            />

            <div className="char-count">

              {prompt.length}/{MAX_PROMPT_LENGTH}

            </div>

          </div>



          <p className="input-helper">

            {isTextToImageMode

              ? 'Enter a prompt to generate an image.'

              : 'Video modes require HUGGING_FACE_VIDEO_API_KEY or PIAPI_API_KEY in backend/.env'}

          </p>



          {!isTextToImageMode && (

            <div className={`video-status-banner ${videoStatusToneClass}`}>

              <strong>{videoStatusLoading ? 'Checking setup...' : 'Video Setup'}</strong>

              <span>

                {videoStatusLoading

                  ? 'Reading backend configuration...'

                  : videoStatus?.message || 'Video configuration unavailable.'}

              </span>

            </div>

          )}



          {isTextToImageMode && (

            <div className="generator-controls">

              <div className="control-group">

                <label htmlFor="ratio-select">Aspect Ratio</label>

                <select

                  id="ratio-select"

                  value={ratio}

                  onChange={(e) => setRatio(e.target.value)}

                  disabled={loading}

                >

                  {RATIO_OPTIONS.map((option) => (

                    <option key={option.value} value={option.value}>

                      {option.label}

                    </option>

                  ))}

                </select>

              </div>



              <div className="control-group">

                <label htmlFor="quality-select">Quality</label>

                <select

                  id="quality-select"

                  value={quality}

                  onChange={(e) => setQuality(e.target.value)}

                  disabled={loading}

                >

                  {QUALITY_OPTIONS.map((option) => (

                    <option key={option.value} value={option.value}>

                      {option.label}

                    </option>

                  ))}

                </select>

              </div>

            </div>

          )}



          {error && <div className="error-message">{error}</div>}



          <button

            type="submit"

            className="generate-btn"

            disabled={

              loading ||

              (!prompt.trim() && !isImageToVideoMode) ||

              (isImageToVideoMode && !sourceImage) ||

              videoGenerationBlocked

            }

          >

            {loading ? (

              <>

                <span className="spinner"></span> {getGenerateButtonLabel(mode, true)}

              </>

            ) : (

              getGenerateButtonLabel(mode, false)

            )}

          </button>

        </form>

      </div>

      {loading && (
        <div className="skeleton-loader">

          <div className="skeleton-image"></div>

        </div>
      )}

      {result && !loading && (
        <div className="image-preview">

          {result.assetType === 'image' ? (

            <>

              <img

                key={result.id}

                src={getPreviewUrl(result.assetUrl, previewRetryCount)}

                alt={result.prompt}

                onLoad={() => {

                  if (previewRetryTimeoutRef.current) {

                    window.clearTimeout(previewRetryTimeoutRef.current);

                  }

                  setImgStatus('loaded');

                }}

                onError={() => {

                  if (previewRetryTimeoutRef.current) {

                    window.clearTimeout(previewRetryTimeoutRef.current);

                  }



                  if (canRetryPreview(result.assetUrl) && previewRetryCount < MAX_PREVIEW_RETRIES) {

                    const nextRetryCount = previewRetryCount + 1;

                    setImgStatus('loading');

                    setError(`Preview is taking longer than usual. Retrying (${nextRetryCount}/${MAX_PREVIEW_RETRIES})...`);

                    previewRetryTimeoutRef.current = window.setTimeout(() => {

                      setPreviewRetryCount(nextRetryCount);

                    }, PREVIEW_RETRY_DELAY_MS);

                    return;

                  }



                  setImgStatus('error');

                  setError('Generated image preview could not be loaded. Please try a shorter prompt or regenerate.');

                }}

                style={{ border: imgStatus === 'error' ? '2px solid red' : undefined }}

              />

              {imgStatus === 'loading' && (

                <div className="prompt-label">Loading image preview...</div>

              )}

              {imgStatus === 'error' && (

                <div className="error-message">

                  Failed to load image preview.

                </div>

              )}

            </>
          ) : (
            <video

              key={result.id}

              className="generated-video"

              src={getResolvedAssetUrl(result.assetUrl)}

              controls

              playsInline

            />
          )}

           {result.generationMode === 'image-to-video' && result.sourceImagePreview && (
             <div className="source-preview result-source-preview">

               <img src={result.sourceImagePreview} alt={result.sourceImageName || 'Source image'} />

               <div>

                 <strong>{result.sourceImageName || 'Source image'}</strong>

                 <p>Animated into video above.</p>

               </div>

             </div>
           )}

          <div className="image-info">
            <div className="image-meta">

              <span className="meta-pill">

                {findModeLabel(result.generationMode)}

              </span>

              {result.assetType === 'image' && (

                <>

                  <span className="meta-pill">

                    {findOptionLabel(RATIO_OPTIONS, result.ratio)}

                  </span>

                  <span className="meta-pill">

                    {findOptionLabel(QUALITY_OPTIONS, result.quality)}

                  </span>

                </>
              )}
            </div>

            {result.prompt ? (
              <>

                <p className="prompt-label">Prompt</p>

                <p className="prompt-text">{result.prompt}</p>

              </>
            ) : (
              <p className="generator-note">No prompt provided for this generation.</p>
            )}

            {result.assetType === 'video' && (
              <p className="generator-note">

                Download or share the video. Explore and history remain image-only.

              </p>
            )}

            <div className="image-actions">
              <button type="button" onClick={handleDownloadAsset} className="action-btn">

                Download

              </button>
              <button type="button" onClick={handleCopyLink} className="action-btn">

                Copy Link

              </button>
              <button type="button" onClick={handleRegenerate} className="action-btn">

                Regenerate

              </button>
              {result.assetType === 'image' && (
                <button

                  type="button"

                  onClick={handlePublishToExplore}

                  className="action-btn"

                  disabled={publishing}

                >

                  {publishing ? 'Publishing...' : 'Publish to Explore'}

                </button>
              )}
            </div>
            {publishMessage && <div className="success-message">{publishMessage}</div>}
          </div>
        </div>
      )}
    </div>
  );
};

export default ImageGenerator;