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
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
import { useState, useRef, useEffect, useCallback, useMemo } from 'react'
import { Play, Square, Download, Eraser, Loader2, Volume2 } from 'lucide-react'

interface AudioPlayerProps {
  audio: Float32Array
  samplingRate: number
  text: string
  index: number
  voice?: string
}

function createWavBuffer(
  audioData: Float32Array,
  sampleRate: number
): ArrayBuffer {
  const length = audioData.length
  const buffer = new ArrayBuffer(44 + length * 2)
  const view = new DataView(buffer)

  // WAV header
  const writeString = (offset: number, string: string) => {
    for (let i = 0; i < string.length; i++) {
      view.setUint8(offset + i, string.charCodeAt(i))
    }
  }

  writeString(0, 'RIFF')
  view.setUint32(4, 36 + length * 2, true)
  writeString(8, 'WAVE')
  writeString(12, 'fmt ')
  view.setUint32(16, 16, true)
  view.setUint16(20, 1, true)
  view.setUint16(22, 1, true)
  view.setUint32(24, sampleRate, true)
  view.setUint32(28, sampleRate * 2, true)
  view.setUint16(32, 2, true)
  view.setUint16(34, 16, true)
  writeString(36, 'data')
  view.setUint32(40, length * 2, true)

  // Convert float32 to int16
  let offset = 44
  for (let i = 0; i < length; i++) {
    const sample = Math.max(-1, Math.min(1, audioData[i]))
    view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true)
    offset += 2
  }

  return buffer
}

interface CustomAudioVisualizerProps {
  audio: Float32Array
  isPlaying: boolean
  currentTime: number
  duration: number
  height?: number
}

function CustomAudioVisualizer({
  audio,
  isPlaying,
  currentTime,
  duration,
  height = 80
}: CustomAudioVisualizerProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  // Memoize expensive calculations with smoothing
  const waveformData = useMemo(() => {
    if (!audio || audio.length === 0) return []

    const samples = Math.min(audio.length, 1600) // Fixed high resolution
    const step = audio.length / samples
    const data = []

    for (let i = 0; i < samples; i++) {
      const sample = Math.abs(audio[Math.floor(i * step)])
      data.push(sample)
    }

    // Apply smoothing filter
    const smoothedData = []
    const smoothingWindow = 3
    for (let i = 0; i < data.length; i++) {
      let sum = 0
      let count = 0
      for (
        let j = Math.max(0, i - smoothingWindow);
        j <= Math.min(data.length - 1, i + smoothingWindow);
        j++
      ) {
        sum += data[j]
        count++
      }
      smoothedData.push(sum / count)
    }

    return smoothedData
  }, [audio])

  // Add resize observer for true responsiveness
  const [containerWidth, setContainerWidth] = useState(800)

  useEffect(() => {
    const container = containerRef.current
    if (!container) return

    const resizeObserver = new ResizeObserver((entries) => {
      for (const entry of entries) {
        setContainerWidth(entry.contentRect.width)
      }
    })

    resizeObserver.observe(container)
    setContainerWidth(container.getBoundingClientRect().width)

    return () => resizeObserver.disconnect()
  }, [])

  useEffect(() => {
    const canvas = canvasRef.current
    const container = containerRef.current
    if (!canvas || !container || waveformData.length === 0) return

    const ctx = canvas.getContext('2d')
    if (!ctx) return

    // Use state-tracked container width for responsive behavior
    const displayWidth = containerWidth
    const displayHeight = height

    // Set high DPI for sharper rendering
    const dpr = window.devicePixelRatio || 1

    canvas.width = displayWidth * dpr
    canvas.height = displayHeight * dpr
    canvas.style.width = `${displayWidth}px`
    canvas.style.height = `${displayHeight}px`

    ctx.scale(dpr, dpr)

    const samples = waveformData.length

    // Clear canvas
    ctx.clearRect(0, 0, displayWidth, displayHeight)

    // Enable smoothing for better quality
    ctx.imageSmoothingEnabled = true
    ctx.imageSmoothingQuality = 'high'

    // Draw waveform bars with full width and logarithmic scaling
    const actualBars = Math.min(samples, displayWidth) // Use full width
    const barWidth = displayWidth / actualBars
    const gap = Math.max(0, barWidth * 0.1)
    const effectiveBarWidth = Math.max(1, barWidth - gap)

    for (let i = 0; i < actualBars; i++) {
      const x = i * barWidth
      const dataIndex = Math.floor((i / actualBars) * samples)
      const sample = waveformData[dataIndex] || 0

      // Logarithmic scaling for better speech visualization
      // This makes quiet sounds (silence) very small and speech much more prominent
      const minThreshold = 0.01 // Silence threshold
      const logSample =
        sample > minThreshold
          ? Math.log10(sample * 9 + 1) // Log scale: log10(sample * 9 + 1) ranges from 0 to 1
          : sample * 0.1 // Very quiet for near-silence

      const amplified = Math.pow(logSample * 3, 1.5) // Further emphasize speech
      const barHeight = Math.max(2, amplified * displayHeight * 0.9)

      const y = (displayHeight - barHeight) / 2

      let barColor = '#6B7280'
      if (duration > 0) {
        const timePosition = (i / actualBars) * duration
        if (isPlaying && timePosition <= currentTime) {
          barColor = '#3B82F6'
        } else if (isPlaying) {
          barColor = '#9CA3AF'
        }
      }

      ctx.fillStyle = barColor
      ctx.fillRect(x, y, effectiveBarWidth, barHeight)

      // Optional: Add rounded corners if supported
      if (typeof ctx.roundRect === 'function') {
        ctx.clearRect(x, y, effectiveBarWidth, barHeight)
        ctx.beginPath()
        const radius = Math.min(effectiveBarWidth / 4, 2)
        ctx.roundRect(x, y, effectiveBarWidth, barHeight, radius)
        ctx.fill()
      }
    }

    // Draw progress line with gradient
    if (isPlaying && duration > 0 && currentTime >= 0) {
      const progressX = Math.min(
        (currentTime / duration) * displayWidth,
        displayWidth
      )

      // Create gradient for progress line
      const gradient = ctx.createLinearGradient(0, 0, 0, displayHeight)
      gradient.addColorStop(0, '#EF4444')
      gradient.addColorStop(0.5, '#DC2626')
      gradient.addColorStop(1, '#EF4444')

      ctx.strokeStyle = gradient
      ctx.lineWidth = 3
      ctx.lineCap = 'round'
      ctx.beginPath()
      ctx.moveTo(progressX, 4)
      ctx.lineTo(progressX, displayHeight - 4)
      ctx.stroke()
    }
  }, [waveformData, isPlaying, currentTime, duration, height, containerWidth])

  return (
    <div ref={containerRef} className="w-full">
      <canvas
        ref={canvasRef}
        className="w-full block"
        style={{
          width: '100%',
          height: `${height}px`,
          maxWidth: '100%',
          display: 'block'
        }}
      />
    </div>
  )
}

function AudioPlayer({
  audio,
  samplingRate,
  text,
  index,
  voice
}: AudioPlayerProps) {
  const [isPlaying, setIsPlaying] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [duration, setDuration] = useState(0)

  const audioRef = useRef<HTMLAudioElement>(null)
  const audioContextRef = useRef<AudioContext | null>(null)
  const sourceRef = useRef<AudioBufferSourceNode | null>(null)
  const startTimeRef = useRef<number>(0)
  const animationFrameRef = useRef<number | null>(null)
  const visualizerRef = useRef<HTMLCanvasElement>(null)

  const stopAudio = useCallback(() => {
    if (sourceRef.current) {
      sourceRef.current.stop()
      sourceRef.current = null
    }
    if (animationFrameRef.current) {
      cancelAnimationFrame(animationFrameRef.current)
      animationFrameRef.current = null
    }
    setIsPlaying(false)
    setCurrentTime(0)
  }, [])

  const playAudio = useCallback(async () => {
    if (!audio || audio.length === 0) return

    // Stop current audio if playing
    if (isPlaying) {
      stopAudio()
      return
    }

    try {
      // Create audio context if it doesn't exist
      if (!audioContextRef.current) {
        audioContextRef.current = new (window.AudioContext ||
          (window as any).webkitAudioContext)()
      }

      const audioContext = audioContextRef.current

      // Resume audio context if suspended
      if (audioContext.state === 'suspended') {
        await audioContext.resume()
      }

      // Create audio buffer
      const audioBuffer = audioContext.createBuffer(
        1,
        audio.length,
        samplingRate
      )
      audioBuffer.getChannelData(0).set(audio)

      // Create audio source
      const source = audioContext.createBufferSource()
      source.buffer = audioBuffer
      source.connect(audioContext.destination)
      sourceRef.current = source

      const audioDuration = audio.length / samplingRate
      setDuration(audioDuration)
      setIsPlaying(true)
      startTimeRef.current = audioContext.currentTime

      // Update current time during playback
      const updateTime = () => {
        if (sourceRef.current && audioContextRef.current) {
          const elapsed =
            audioContextRef.current.currentTime - startTimeRef.current
          const newCurrentTime = Math.min(elapsed, audioDuration)
          setCurrentTime(newCurrentTime)

          if (elapsed < audioDuration) {
            animationFrameRef.current = requestAnimationFrame(updateTime)
          } else {
            // Audio finished naturally
            setIsPlaying(false)
            setCurrentTime(0)
            sourceRef.current = null
            animationFrameRef.current = null
          }
        }
      }
      animationFrameRef.current = requestAnimationFrame(updateTime)

      source.onended = () => {
        if (animationFrameRef.current) {
          cancelAnimationFrame(animationFrameRef.current)
          animationFrameRef.current = null
        }
        setIsPlaying(false)
        setCurrentTime(0)
        sourceRef.current = null
      }

      source.start()
    } catch (error) {
      console.error('Error playing audio:', error)
      setIsPlaying(false)
      setCurrentTime(0)
    }
  }, [audio, samplingRate, isPlaying, stopAudio])

  // Cleanup animation frame on component unmount
  useEffect(() => {
    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
      }
    }
  }, [])

  const downloadAudio = useCallback(() => {
    if (!audio || audio.length === 0) return

    try {
      const wavBuffer = createWavBuffer(audio, samplingRate)
      const blob = new Blob([wavBuffer], { type: 'audio/wav' })
      const url = URL.createObjectURL(blob)

      const a = document.createElement('a')
      a.href = url
      a.download = `tts-output-${index + 1}.wav`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      URL.revokeObjectURL(url)
    } catch (error) {
      console.error('Error downloading audio:', error)
    }
  }, [audio, samplingRate, index])

  return (
    <div className="border border-gray-200 rounded-lg p-4 bg-gray-50">
      <div className="mb-3">
        <p className="text-sm text-gray-700 font-medium mb-2">
          Prompt{voice ? ` (${voice})` : ''}:
        </p>
        <p className="text-sm text-gray-600 italic bg-white p-2 rounded border">
          "{text}"
        </p>
      </div>

      <div className="mb-3">
        <div className="w-full border border-gray-200 rounded bg-gray-50 overflow-hidden">
          {audio && audio.length > 0 ? (
            <CustomAudioVisualizer
              audio={audio}
              isPlaying={isPlaying}
              currentTime={currentTime}
              duration={duration}
              height={80}
            />
          ) : (
            <div className="w-full h-20 flex items-center justify-center">
              <span className="text-gray-400 text-sm">Loading waveform...</span>
            </div>
          )}
        </div>
      </div>

      <div className="flex items-center gap-2">
        <button
          onClick={playAudio}
          className="flex items-center gap-1 px-3 py-1 bg-blue-500 hover:bg-blue-600 text-white rounded text-sm transition-colors"
        >
          {isPlaying ? (
            <>
              <Square className="w-4 h-4" />
              Stop
            </>
          ) : (
            <>
              <Play className="w-4 h-4" />
              Play
            </>
          )}
        </button>
        <button
          onClick={downloadAudio}
          className="flex items-center gap-1 px-3 py-1 bg-green-500 hover:bg-green-600 text-white rounded text-sm transition-colors"
        >
          <Download className="w-4 h-4" />
          Download
        </button>
        {duration > 0 && (
          <span className="text-xs text-gray-500 ml-2">
            {currentTime.toFixed(1)}s / {duration.toFixed(1)}s
          </span>
        )}
      </div>
    </div>
  )
}

export default AudioPlayer