File size: 37,284 Bytes
fd52f31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useRef, useEffect } from 'react';
import { RiSendPlaneFill } from 'react-icons/ri';
import { useNavigate } from 'react-router-dom';
import './Home.css';
import { TbSparkles } from "react-icons/tb";
import { LuBookAudio } from "react-icons/lu";
import { FaArrowRight, FaPlay, FaVolumeUp, FaChevronDown, FaLightbulb, FaSkull, FaCheckCircle, FaPause, FaLock } from "react-icons/fa";
import { TiFlowMerge } from "react-icons/ti";
import { RiVoiceprintFill } from "react-icons/ri";
import { BsSoundwave } from "react-icons/bs";
import { BiPodcast } from "react-icons/bi";

const Home = () => {
    const [prompt, setPrompt] = useState('');
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const [isBelieverDropdownOpen, setIsBelieverDropdownOpen] = useState(false);
    const [isSkepticDropdownOpen, setIsSkepticDropdownOpen] = useState(false);
    const [selectedWorkflow, setSelectedWorkflow] = useState('Basic Podcast');
    const [selectedBelieverVoice, setSelectedBelieverVoice] = useState({ id: 'alloy', name: 'Alloy' });
    const [selectedSkepticVoice, setSelectedSkepticVoice] = useState({ id: 'echo', name: 'Echo' });
    const [researchSteps, setResearchSteps] = useState([]);
    const [believerResponses, setBelieverResponses] = useState([]);
    const [skepticResponses, setSkepticResponses] = useState([]);
    const [isGenerating, setIsGenerating] = useState(false);
    const [isSuccess, setIsSuccess] = useState(false);
    const [successMessage, setSuccessMessage] = useState('');
    const [audioUrl, setAudioUrl] = useState('');
    const [isPlaying, setIsPlaying] = useState(false);
    const [currentTime, setCurrentTime] = useState(0);
    const [duration, setDuration] = useState(0);
    const [isUnlocking, setIsUnlocking] = useState(false);
    const audioRef = useRef(null);
    const navigate = useNavigate();
    const workflowDropdownRef = useRef(null);
    const believerDropdownRef = useRef(null);
    const skepticDropdownRef = useRef(null);
    const insightsRef = useRef(null);

    const workflows = [
        { id: '1', name: 'Basic Podcast' },
        { id: '2', name: 'Interview Style' },
        { id: '3', name: 'News Digest' }
    ];

    const voices = [
        { id: 'alloy', name: 'Alloy' },
        { id: 'echo', name: 'Echo' },
        { id: 'fable', name: 'Fable' },
        { id: 'onyx', name: 'Onyx' },
        { id: 'nova', name: 'Nova' },
        { id: 'shimmer', name: 'Shimmer' },
        { id: 'ash', name: 'Ash' },
        { id: 'sage', name: 'Sage' },
        { id: 'coral', name: 'Coral' }
    ];

    useEffect(() => {
        const handleClickOutside = (event) => {
            if (workflowDropdownRef.current && !workflowDropdownRef.current.contains(event.target)) {
                setIsDropdownOpen(false);
            }
            if (believerDropdownRef.current && !believerDropdownRef.current.contains(event.target)) {
                setIsBelieverDropdownOpen(false);
            }
            if (skepticDropdownRef.current && !skepticDropdownRef.current.contains(event.target)) {
                setIsSkepticDropdownOpen(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    useEffect(() => {
        const audio = audioRef.current;
        if (audio) {
            const updateTime = () => {
                setCurrentTime(audio.currentTime);
            };

            const updateDuration = () => {
                if (!isNaN(audio.duration) && audio.duration > 0) {
                    // Validate duration before setting it
                    if (audio.duration > 86400) {
                        console.error('Invalid duration detected:', audio.duration);
                        // Don't update state with invalid duration
                        return;
                    }
                    console.log('Duration updated:', audio.duration);
                    setDuration(audio.duration);
                }
            };

            // Add event listeners
            audio.addEventListener('timeupdate', updateTime);
            audio.addEventListener('loadedmetadata', updateDuration);
            audio.addEventListener('durationchange', updateDuration);
            audio.addEventListener('canplay', updateDuration); // Additional event to catch duration
            audio.addEventListener('ended', () => setIsPlaying(false));
            audio.addEventListener('error', (e) => {
                console.error('Audio error in event listener:', e);
                setIsPlaying(false);
            });

            return () => {
                // Remove event listeners
                audio.removeEventListener('timeupdate', updateTime);
                audio.removeEventListener('loadedmetadata', updateDuration);
                audio.removeEventListener('durationchange', updateDuration);
                audio.removeEventListener('canplay', updateDuration);
                audio.removeEventListener('ended', () => setIsPlaying(false));
                audio.removeEventListener('error', (e) => {
                    console.error('Audio error:', e);
                    setIsPlaying(false);
                });
            };
        }
    }, [audioUrl]);

    useEffect(() => {
        if (audioUrl) {
            setIsUnlocking(true);
            // Remove the unlocking class after animation completes
            const timer = setTimeout(() => {
                setIsUnlocking(false);
            }, 500);
            return () => clearTimeout(timer);
        }
    }, [audioUrl]);

    // Add a separate effect to check duration when audioUrl changes
    useEffect(() => {
        if (audioUrl && audioRef.current) {
            console.log('Audio URL changed, checking duration...');

            // Reset current time and check duration
            setCurrentTime(0);

            // Create a function to check duration periodically
            const checkDuration = () => {
                if (audioRef.current && !isNaN(audioRef.current.duration) && audioRef.current.duration > 0) {
                    // Validate the duration
                    if (audioRef.current.duration > 86400) {
                        console.error('Invalid duration detected in check:', audioRef.current.duration);
                        return false;
                    }
                    console.log('Duration found after URL change:', audioRef.current.duration);
                    setDuration(audioRef.current.duration);
                    return true;
                }
                return false;
            };

            // Try immediately
            if (!checkDuration()) {
                // If not successful, try again after a short delay
                const timerId = setTimeout(async () => {
                    if (!checkDuration()) {
                        // If still not successful, try manual calculation
                        console.log('Duration not available, attempting manual calculation');
                        try {
                            const calculatedDuration = await calculateMP3Duration(audioUrl);
                            console.log('Manually calculated duration:', calculatedDuration);
                            setDuration(calculatedDuration);
                        } catch (error) {
                            console.error('Manual duration calculation failed:', error);
                            // Set a default duration as fallback
                            setDuration(300); // Default to 5 minutes
                        }
                    }
                }, 1000);

                return () => clearTimeout(timerId);
            }
        }
    }, [audioUrl]);

    const checkForExistingPodcast = async () => {
        try {
            const token = localStorage.getItem('token');
            if (!token) return;

            // Fetch the most recent podcast using the new endpoint
            const response = await fetch('http://localhost:8000/podcasts/latest', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });

            if (response.ok) {
                const data = await response.json();

                // Check if we got a podcast (not just a message)
                if (data && data.audio_url) {
                    // Set the audio URL directly from the response
                    setAudioUrl(data.audio_url);
                    setSuccessMessage('Latest podcast loaded');
                    setIsSuccess(true);
                    console.log('Latest podcast loaded:', data.topic);
                } else if (data && data.audio_path) {
                    // Fallback to constructing URL from audio_path if audio_url is not present
                    setAudioUrl(`http://localhost:8000${data.audio_path}`);
                    setSuccessMessage('Latest podcast loaded');
                    setIsSuccess(true);
                    console.log('Latest podcast loaded (using path):', data.topic);
                } else {
                    console.log('No podcasts found or no audio URL available');
                }
            } else {
                console.error('Error fetching latest podcast:', await response.text());
            }
        } catch (error) {
            console.error('Error checking for existing podcast:', error);
        }
    };

    useEffect(() => {
        console.log('Component mounted, checking for existing podcasts...');
        checkForExistingPodcast();
    }, []);

    const togglePlay = () => {
        if (audioRef.current) {
            if (isPlaying) {
                audioRef.current.pause();
                setIsPlaying(false);
            } else {
                const playPromise = audioRef.current.play();

                if (playPromise !== undefined) {
                    playPromise
                        .then(() => {
                            setIsPlaying(true);
                        })
                        .catch(error => {
                            console.error('Error playing audio:', error);
                            setSuccessMessage('Error playing audio. Please try again.');
                        });
                }
            }
        }
    };

    const handleSeek = (e) => {
        if (!audioRef.current || !audioUrl) return;

        // Check if duration is valid
        if (isNaN(audioRef.current.duration) || audioRef.current.duration <= 0) {
            console.warn('Cannot seek: Invalid audio duration');
            return;
        }

        const progressBar = e.currentTarget;
        const rect = progressBar.getBoundingClientRect();
        const clickPosition = (e.clientX - rect.left) / rect.width;

        // Ensure clickPosition is between 0 and 1
        const normalizedPosition = Math.max(0, Math.min(1, clickPosition));
        const newTime = normalizedPosition * audioRef.current.duration;

        console.log(`Seeking to ${formatTime(newTime)} (${normalizedPosition * 100}%)`);

        // Update audio time
        audioRef.current.currentTime = newTime;
        setCurrentTime(newTime);
    };

    const formatTime = (time) => {
        // Handle invalid time values
        if (isNaN(time) || time === null || time === undefined || time < 0) {
            return '0:00';
        }

        // Cap extremely large values (likely errors)
        if (time > 86400) { // More than 24 hours
            console.warn('Extremely large duration detected:', time);
            time = 0; // Reset to 0 for display purposes
        }

        const hours = Math.floor(time / 3600);
        const minutes = Math.floor((time % 3600) / 60);
        const seconds = Math.floor(time % 60);

        if (hours > 0) {
            return `${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
        return `${minutes}:${seconds.toString().padStart(2, '0')}`;
    };

    const handleWorkflowSelect = (workflow) => {
        setSelectedWorkflow(workflow.name);
        setIsDropdownOpen(false);
    };

    const handleBelieverVoiceSelect = (voice) => {
        setSelectedBelieverVoice(voice);
        setIsBelieverDropdownOpen(false);
    };

    const handleSkepticVoiceSelect = (voice) => {
        setSelectedSkepticVoice(voice);
        setIsSkepticDropdownOpen(false);
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsGenerating(true);
        setResearchSteps([]);
        setBelieverResponses([]);
        setSkepticResponses([]);
        setIsSuccess(false);
        setSuccessMessage('');
        setAudioUrl('');

        try {
            const token = localStorage.getItem('token');
            if (!token) {
                console.error('No token found');
                return;
            }

            const response = await fetch('http://localhost:8000/generate-podcast/stream', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    topic: prompt,
                    believer_voice_id: selectedBelieverVoice.id,
                    skeptic_voice_id: selectedSkepticVoice.id
                })
            });

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            while (true) {
                const { value, done } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value);
                const lines = chunk.split('\n').filter(line => line.trim());

                for (const line of lines) {
                    try {
                        const data = JSON.parse(line);
                        switch (data.type) {
                            case 'intermediate':
                                setResearchSteps(prev => [...prev, data.content]);
                                break;
                            case 'final':
                                setResearchSteps(prev => [...prev, 'Research completed!']);
                                break;
                            case 'believer':
                                if (data.turn) {
                                    setBelieverResponses(prev => {
                                        const newResponses = [...prev];
                                        newResponses[data.turn - 1] = (newResponses[data.turn - 1] || '') + data.content;
                                        return newResponses;
                                    });
                                }
                                break;
                            case 'skeptic':
                                if (data.turn) {
                                    setSkepticResponses(prev => {
                                        const newResponses = [...prev];
                                        newResponses[data.turn - 1] = (newResponses[data.turn - 1] || '') + data.content;
                                        return newResponses;
                                    });
                                }
                                break;
                            case 'success':
                                setIsSuccess(true);
                                setSuccessMessage(data.content || 'Podcast created successfully!');
                                if (data.podcast_url) {
                                    setAudioUrl(`http://localhost:8000${data.podcast_url}`);
                                }
                                break;
                            case 'error':
                                console.error('Error:', data.content);
                                break;
                        }
                        // Auto-scroll to the bottom of insights
                        if (insightsRef.current) {
                            insightsRef.current.scrollTop = insightsRef.current.scrollHeight;
                        }
                    } catch (e) {
                        console.error('Error parsing JSON:', e);
                    }
                }
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setIsGenerating(false);
        }
    };

    // Add a function to manually calculate duration for MP3 files
    const calculateMP3Duration = async (url) => {
        try {
            console.log('Attempting to manually calculate MP3 duration for:', url);

            // Create a temporary audio element
            const tempAudio = new Audio();

            // Create a promise to handle the duration calculation
            const durationPromise = new Promise((resolve, reject) => {
                // Set up event listeners
                tempAudio.addEventListener('loadedmetadata', () => {
                    if (!isNaN(tempAudio.duration) && tempAudio.duration > 0 && tempAudio.duration < 86400) {
                        console.log('Successfully calculated duration:', tempAudio.duration);
                        resolve(tempAudio.duration);
                    } else {
                        // If duration is invalid, use a default value
                        console.warn('Invalid duration from calculation, using default');
                        resolve(300); // Default to 5 minutes (300 seconds)
                    }
                });

                tempAudio.addEventListener('error', (e) => {
                    console.error('Error calculating duration:', e);
                    reject(e);
                });

                // Set a timeout in case the metadata never loads
                setTimeout(() => {
                    console.warn('Duration calculation timed out, using default');
                    resolve(300); // Default to 5 minutes
                }, 5000);
            });

            // Start loading the audio
            tempAudio.src = url;
            tempAudio.load();

            // Wait for the duration to be calculated
            const calculatedDuration = await durationPromise;
            return calculatedDuration;

        } catch (error) {
            console.error('Error in duration calculation:', error);
            return 300; // Default to 5 minutes on error
        }
    };

    return (
        <div className="home-container">
            <div className='home-hero'>
                <div className="home-hero-content">
                    <h1>Welcome to PodCraft</h1>
                </div>
            </div>
            <div className="top-row">
                <div className="column left-column">
                    <div className="content-card">
                        <h3>Generated insights <TbSparkles /></h3>
                        <div className="insights-container" ref={insightsRef}>
                            {researchSteps.length === 0 && !believerResponses.length && !skepticResponses.length ? (
                                <div className="placeholder-content">
                                    <span className="info-icon"><TbSparkles /></span>
                                    <p>Insights from the AI agents will appear here</p>
                                </div>
                            ) : (
                                <div className="insights-content">
                                    {researchSteps.length > 0 && (
                                        <div className="research-section">
                                            <h4>Research Progress</h4>
                                            <div className="research-steps">
                                                {researchSteps.map((step, index) => (
                                                    <div key={index} className="research-step">
                                                        <span className="step-number">{index + 1}</span>
                                                        <p>{step}</p>
                                                    </div>
                                                ))}
                                            </div>
                                        </div>
                                    )}
                                    {(skepticResponses.length > 0 || believerResponses.length > 0) && (
                                        <div className="debate-section">
                                            {skepticResponses.map((response, index) => (
                                                <React.Fragment key={`turn-${index + 1}`}>
                                                    {response && (
                                                        <div className="agent-response skeptic">
                                                            <div className="agent-header">
                                                                <FaSkull className="agent-icon" />
                                                                <h4>{selectedSkepticVoice.name}'s Turn {index + 1}</h4>
                                                            </div>
                                                            <p>{response}</p>
                                                        </div>
                                                    )}
                                                    {believerResponses[index] && (
                                                        <div className="agent-response believer">
                                                            <div className="agent-header">
                                                                <FaLightbulb className="agent-icon" />
                                                                <h4>{selectedBelieverVoice.name}'s Turn {index + 1}</h4>
                                                            </div>
                                                            <p>{believerResponses[index]}</p>
                                                        </div>
                                                    )}
                                                </React.Fragment>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            )}
                            {isSuccess && (
                                <div className="success-message">
                                    <FaCheckCircle className="success-icon" />
                                    <p>{successMessage}</p>
                                </div>
                            )}
                        </div>
                        {isGenerating && (
                            <div className="generating-indicator">
                                <div className="loading-dots">
                                    <span></span>
                                    <span></span>
                                    <span></span>
                                </div>
                                <p className="generating-text">
                                    {!believerResponses.length ? "Researching topic..." :
                                        !skepticResponses.length ? "Generating believer's perspective..." :
                                            skepticResponses.length > 0 && !isSuccess ? "Creating podcast with TTS..." :
                                                ""}
                                </p>
                            </div>
                        )}
                    </div>
                </div>
                <div className="column right-column">
                    <div className="content-card">
                        <h3>Configure your podcast <LuBookAudio /></h3>
                        <div className="audio-content">
                            <div className="audio-row">
                                <div className="row-header">
                                    <div className="row-title">
                                        <TiFlowMerge className="row-icon" />
                                        <h4>Choose Workflow Template</h4>
                                    </div>
                                </div>
                                <div className="custom-dropdown" ref={workflowDropdownRef}>
                                    <div
                                        className={`dropdown-header ${isDropdownOpen ? 'open' : ''}`}
                                        onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                                    >
                                        <span>{selectedWorkflow || 'Select Workflow'}</span>
                                        <FaChevronDown className={`chevron ${isDropdownOpen ? 'open' : ''}`} />
                                    </div>
                                    {isDropdownOpen && (
                                        <div className="dropdown-options">
                                            {workflows.map((workflow) => (
                                                <div
                                                    key={workflow.id}
                                                    className="dropdown-option"
                                                    onClick={() => handleWorkflowSelect(workflow)}
                                                >
                                                    {workflow.name}
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            </div>
                            <div className="audio-row">
                                <div className="row-header">
                                    <div className="row-title">
                                        <RiVoiceprintFill className="row-icon" />
                                        <h4>Select Voice Style</h4>
                                    </div>
                                </div>
                                <div className="voice-dropdowns">
                                    <div className="voice-dropdown-container">
                                        <div className="voice-type">
                                            <FaLightbulb className="voice-icon believer" />
                                            <span>Believer Voice</span>
                                        </div>
                                        <div className="custom-dropdown" ref={believerDropdownRef}>
                                            <div
                                                className={`dropdown-header ${isBelieverDropdownOpen ? 'open' : ''}`}
                                                onClick={() => setIsBelieverDropdownOpen(!isBelieverDropdownOpen)}
                                            >
                                                <span>{selectedBelieverVoice ? selectedBelieverVoice.name : 'Select Voice'}</span>
                                                <FaChevronDown className={`chevron ${isBelieverDropdownOpen ? 'open' : ''}`} />
                                            </div>
                                            {isBelieverDropdownOpen && (
                                                <div className="dropdown-options">
                                                    {voices.map((voice) => (
                                                        <div
                                                            key={voice.id}
                                                            className={`dropdown-option ${selectedSkepticVoice?.id === voice.id ? 'disabled' : ''}`}
                                                            onClick={() => selectedSkepticVoice?.id !== voice.id && handleBelieverVoiceSelect(voice)}
                                                        >
                                                            <div className="voice-option-content">
                                                                <span>{voice.name}</span>
                                                                <small>{voice.id}</small>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                    <div className="voice-dropdown-container">
                                        <div className="voice-type">
                                            <FaSkull className="voice-icon skeptic" />
                                            <span>Skeptic Voice</span>
                                        </div>
                                        <div className="custom-dropdown" ref={skepticDropdownRef}>
                                            <div
                                                className={`dropdown-header ${isSkepticDropdownOpen ? 'open' : ''}`}
                                                onClick={() => setIsSkepticDropdownOpen(!isSkepticDropdownOpen)}
                                            >
                                                <span>{selectedSkepticVoice ? selectedSkepticVoice.name : 'Select Voice'}</span>
                                                <FaChevronDown className={`chevron ${isSkepticDropdownOpen ? 'open' : ''}`} />
                                            </div>
                                            {isSkepticDropdownOpen && (
                                                <div className="dropdown-options">
                                                    {voices.map((voice) => (
                                                        <div
                                                            key={voice.id}
                                                            className={`dropdown-option ${selectedBelieverVoice?.id === voice.id ? 'disabled' : ''}`}
                                                            onClick={() => selectedBelieverVoice?.id !== voice.id && handleSkepticVoiceSelect(voice)}
                                                        >
                                                            <div className="voice-option-content">
                                                                <span>{voice.name}</span>
                                                                <small>{voice.id}</small>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div className="audio-row">
                                <div className="row-header">
                                    <div className="row-title">
                                        <BiPodcast className="row-icon" />
                                        <h4>Preview Audio</h4>
                                    </div>
                                </div>
                                <div className={`player-controls ${!audioUrl ? 'locked' : isUnlocking ? 'unlocking' : ''}`}>
                                    {!audioUrl && <FaLock className="lock-icon" />}
                                    <button
                                        className="play-btn"
                                        onClick={togglePlay}
                                        disabled={!audioUrl}
                                        aria-label={isPlaying ? "Pause" : "Play"}
                                    >
                                        {isPlaying ? <FaPause /> : <FaPlay />}
                                    </button>
                                    <div
                                        className="player-progress"
                                        onClick={audioUrl ? handleSeek : undefined}
                                        style={{ cursor: audioUrl ? 'pointer' : 'not-allowed' }}
                                    >
                                        <div className="progress-bar">
                                            <div
                                                className="progress"
                                                style={{
                                                    width: `${duration > 0 ? (currentTime / duration) * 100 : 0}%`
                                                }}
                                            />
                                        </div>
                                    </div>
                                    <div className="time-stamps">
                                        <span>{formatTime(currentTime)}/{formatTime(duration)}</span>
                                    </div>
                                </div>
                                <audio
                                    ref={audioRef}
                                    src={audioUrl || undefined}
                                    preload="metadata"
                                    onError={(e) => {
                                        console.error('Audio element error event:', e);
                                        console.error('Audio error details:', e.target.error);
                                        setSuccessMessage('Error loading audio. Please try again.');
                                        setIsSuccess(false);
                                    }}
                                    onLoadedMetadata={(e) => {
                                        console.log('Audio metadata loaded successfully');
                                        console.log('Audio duration from event:', e.target.duration);
                                        if (audioRef.current && !isNaN(audioRef.current.duration)) {
                                            setDuration(audioRef.current.duration);
                                        }
                                    }}
                                    onDurationChange={(e) => {
                                        console.log('Duration changed:', e.target.duration);
                                        if (!isNaN(e.target.duration) && e.target.duration > 0) {
                                            // Validate duration before setting it
                                            if (e.target.duration > 86400) {
                                                console.error('Invalid duration detected in event:', e.target.duration);
                                                return;
                                            }
                                            setDuration(e.target.duration);
                                        }
                                    }}
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div className="bottom-row">
                <div className="prompt-container">
                    <form onSubmit={handleSubmit} className="prompt-form">
                        <input
                            type="text"
                            value={prompt}
                            onChange={(e) => setPrompt(e.target.value)}
                            placeholder="Enter your prompt to generate a podcast..."
                            className="prompt-input"
                            disabled={isGenerating}
                        />
                        <button
                            type="submit"
                            className="prompt-submit"
                            disabled={isGenerating || !prompt.trim()}
                        >
                            <RiSendPlaneFill />
                        </button>
                    </form>
                </div>
            </div>
            <div className="workflows-redirect">
                <button onClick={() => navigate('/workflows')} className="workflows-button">
                    Create in workflows <FaArrowRight />
                </button>
            </div>
        </div>
    );
};

export default Home;