import React, { useState, useRef, useEffect, useCallback } from 'react';
import {
  Mic,
  StopCircle,
  Play,
  Pause,
  Download,
  AlertTriangle,
  CheckCircle,
  RefreshCw,
} from 'lucide-react';
import useTranslation from "../useTranslation.jsx";
import wordStore from "../../mc/wordStore.json";

// Helper function to convert AudioBuffer to WAV Blob
// buffer: AudioBuffer
function audioBufferToWav(buffer, opt = {}) {
  const numChannels = buffer.numberOfChannels;
  const sampleRate = buffer.sampleRate;
  const format = 1; // PCM
  const bitDepth = 16; // 16-bit PCM

  const interleaved =
    numChannels === 2
      ? interleave(buffer.getChannelData(0), buffer.getChannelData(1))
      : buffer.getChannelData(0);
  const dataView = encodeWAV(
    interleaved,
    format,
    sampleRate,
    numChannels,
    bitDepth,
  );
  return new Blob([dataView], {
    type: "audio/wav",
  });
}

// samples: Float32Array, format: number, sampleRate: number, numChannels: number, bitDepth: number
// Returns: DataView
function encodeWAV(samples, format, sampleRate, numChannels, bitDepth) {
  const bytesPerSample = bitDepth / 8;
  const blockAlign = numChannels * bytesPerSample;
  const buffer = new ArrayBuffer(44 + samples.length * bytesPerSample);
  const view = new DataView(buffer);

  /* RIFF identifier */
  writeString(view, 0, 'RIFF');
  /* RIFF chunk length */
  view.setUint32(4, 36 + samples.length * bytesPerSample, true);
  /* RIFF type */
  writeString(view, 8, 'WAVE');
  /* format chunk identifier */
  writeString(view, 12, 'fmt ');
  /* format chunk length */
  view.setUint32(16, 16, true);
  /* sample format (raw) */
  view.setUint16(20, format, true);
  /* channel count */
  view.setUint16(22, numChannels, true);
  /* sample rate */
  view.setUint32(24, sampleRate, true);
  /* byte rate (sample rate * block align) */
  view.setUint32(28, sampleRate * blockAlign, true);
  /* block align (channel count * bytes per sample) */
  view.setUint16(32, blockAlign, true);
  /* bits per sample */
  view.setUint16(34, bitDepth, true);
  /* data chunk identifier */
  writeString(view, 36, 'data');
  /* data chunk length */
  view.setUint32(40, samples.length * bytesPerSample, true);

  // Write PCM samples
  floatTo16BitPCM(view, 44, samples);
  return view;
}

// output: DataView, offset: number, input: Float32Array
function floatTo16BitPCM(output, offset, input) {
  for (let i = 0; i < input.length; i++, offset += 2) {
    const s = Math.max(-1, Math.min(1, input[i]));
    output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
  }
}

// inputL: Float32Array, inputR: Float32Array
// Returns: Float32Array
function interleave(inputL, inputR) {
  const length = inputL.length + inputR.length;
  const result = new Float32Array(length);
  let index = 0;
  let inputIndex = 0;
  while (index < length) {
    result[index++] = inputL[inputIndex];
    result[index++] = inputR[inputIndex];
    inputIndex++;
  }
  return result;
}

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

// The Headless Audio Recorder Hook
export default function useAudioRecorder(props) {
  const {
    onStateChange,
    onTimerUpdate,
    onRecordingComplete,
    onError,
    onStreamReady,
    config,
  } = props || {};
  const [recordingState, setRecordingState] = useState("idle");
  const [duration, setDuration] = useState(0);
  const [audioChunks, setAudioChunks] = useState([]);
  const [finalWavBlob, setFinalWavBlob] = useState(null);
  const [audioURL, setAudioURL] = useState('');
  const [errorMessage, setErrorMessage] = useState(null);
  const [isMicrophoneAvailable, setIsMicrophoneAvailable] = useState(false);
  const mediaRecorderRef = useRef(null);
  const accumulatedChunksRef = useRef([]);
  const timerIntervalRef = useRef(null);
  const audioContextRef = useRef(null);
  const mediaStreamRef = useRef(null);

  // Function to update state and call prop
  const updateState = useCallback(
    (newState) => {
      setRecordingState((oldState) => {
        if (oldState !== newState) {
          onStateChange?.({
            newState,
            oldState,
          });
        }
        return newState;
      });
    },
    [onStateChange],
  );

  // Error handler
  const handleError = useCallback(
    (message, details) => {
      setErrorMessage(message);
      onError?.({
        message,
        details,
      });
      console.error("AudioRecorder Hook Error:", message, details);
      setRecordingState((currentState) => {
        if (currentState !== "permissionDenied" && currentState !== "idle") {
          onStateChange?.({
            newState: "ready",
            oldState: currentState,
          });
          return "ready";
        }
        return currentState;
      });
    },
    [onError, onStateChange],
  );

  // Request microphone permission
  const requestPermission = useCallback(async () => {
    updateState('requestingPermission');
    setErrorMessage(null);
    if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
      handleError('MediaDevices API not supported.');
      updateState('permissionDenied');
      setIsMicrophoneAvailable(false);
      return false;
    }
    setIsMicrophoneAvailable(true);
    try {
      const stream = await navigator.mediaDevices.getUserMedia({
        audio: true,
      });
      mediaStreamRef.current = stream;
      if (!audioContextRef.current) {
        try {
          audioContextRef.current = new (window.AudioContext ||
            window.webkitAudioContext)();
        } catch (e) {
          handleError(
            'AudioContext could not be created during permission request.',
            e,
          );
          updateState('permissionDenied');
          return false;
        }
      }
      updateState('ready');
      return true;
    } catch (err) {
      if (
        err instanceof Error &&
        (err.name === 'NotAllowedError' || err.name === 'PermissionDeniedError')
      ) {
        handleError(
          'Microphone permission denied. Please enable it in your browser settings.',
        );
      } else {
        handleError('Error accessing microphone.', err);
      }
      updateState('permissionDenied');
      return false;
    }
  }, [handleError, updateState]);

  // Timer management
  const startTimer = () => {
    if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
    timerIntervalRef.current = setInterval(() => {
      setDuration((prev) => {
        const newTime = prev + 1;
        onTimerUpdate?.(newTime);
        return newTime;
      });
    }, 1000);
  };
  const stopTimer = () => {
    if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
    timerIntervalRef.current = null;
  };
  const resetTimer = () => {
    stopTimer();
    setDuration(0);
    onTimerUpdate?.(0);
  };

  // Centralized Reset Logic
  const performReset = useCallback(() => {
    if (
      mediaRecorderRef.current &&
      mediaRecorderRef.current.state !== 'inactive'
    ) {
      mediaRecorderRef.current.stop();
    }
    mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
    mediaStreamRef.current = null;
    if (audioURL) URL.revokeObjectURL(audioURL);
    setAudioURL('');
    setFinalWavBlob(null);
    setAudioChunks([]);
    accumulatedChunksRef.current = [];
    resetTimer();
    setErrorMessage(null);
    updateState("permissionNeeded");
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
      setIsMicrophoneAvailable(true);
      if (navigator.permissions && navigator.permissions.query) {
        navigator.permissions
          .query({
            name: "microphone",
          })
          .then((status) => {
            // Removed 'as PermissionName'
            if (status.state === 'granted') updateState('ready');
            else if (status.state === 'denied') {
              updateState('permissionDenied');
              setErrorMessage(
                (prev) => prev || 'Microphone permission is denied.',
              );
            } else updateState('permissionNeeded');
          })
          .catch(() => updateState('permissionNeeded'));
      } else updateState('permissionNeeded');
    } else {
      setIsMicrophoneAvailable(false);
      updateState('permissionDenied'); // If no media devices, it's effectively denied.
      setErrorMessage('MediaDevices API not supported on this browser.');
    }
  }, [audioURL, updateState]);

  // Initialize and check permissions on mount
  useEffect(() => {
    setIsMicrophoneAvailable(
      !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia),
    );
    performReset();
    if (
      !audioContextRef.current &&
      navigator.mediaDevices &&
      navigator.mediaDevices.getUserMedia
    ) {
      try {
        audioContextRef.current = new (window.AudioContext ||
          window.webkitAudioContext)();
      } catch (e) {
        handleError(
          'AudioContext could not be created on mount. WAV conversion might fail.',
          e,
        );
      }
    }
    let permStatus = null;
    const handlePermissionChange = () => {
      if (permStatus) {
        if (permStatus.state === 'granted') {
          updateState('ready');
          if (!audioContextRef.current) {
            try {
              audioContextRef.current = new (window.AudioContext ||
                window.webkitAudioContext)();
            } catch (e) {
              handleError(
                'AudioContext could not be created after permission grant.',
                e,
              );
            }
          }
        } else if (permStatus.state === 'denied') {
          updateState('permissionDenied');
          handleError('Microphone permission status changed to denied.');
        } else {
          updateState('permissionNeeded');
        }
      }
    };
    if (navigator.permissions && navigator.permissions.query) {
      navigator.permissions
        .query({
          name: "microphone",
        })
        .then((status) => {
          // Removed 'as PermissionName'
          permStatus = status;
          handlePermissionChange();
          status.onchange = handlePermissionChange;
        })
        .catch(() => updateState('permissionNeeded'));
    }
    return () => {
      if (timerIntervalRef.current) clearInterval(timerIntervalRef.current);
      if (audioURL) URL.revokeObjectURL(audioURL);
      mediaStreamRef.current?.getTracks().forEach((track) => track.stop());
      mediaRecorderRef.current?.stream
        ?.getTracks()
        .forEach((track) => track.stop());
      if (permStatus) permStatus.onchange = null;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // performReset, handleError, updateState are stable.

  // Recording actions
  const start = useCallback(async () => {
    if (
      !['ready', 'finished', 'idle', 'permissionNeeded'].includes(
        recordingState,
      )
    ) {
      handleError(`Cannot start recording in state: ${recordingState}`);
      return;
    }
    setErrorMessage(null);
    setFinalWavBlob(null);
    if (audioURL) {
      URL.revokeObjectURL(audioURL);
      setAudioURL('');
    }
    accumulatedChunksRef.current = [];
    setAudioChunks([]);
    resetTimer();
    let stream = mediaStreamRef.current;
    if (
      !stream ||
      stream.getAudioTracks().every((track) => track.readyState === 'ended')
    ) {
      const permissionGranted = await requestPermission();
      if (!permissionGranted) return;
      stream = mediaStreamRef.current;
    }
    if (!stream) {
      handleError('Microphone stream not available.');
      updateState('permissionDenied');
      return;
    }
    if (!audioContextRef.current) {
      try {
        audioContextRef.current = new (window.AudioContext ||
          window.webkitAudioContext)();
      } catch (e) {
        handleError(
          'AudioContext could not be initialized before starting recording.',
          e,
        );
        updateState('permissionDenied');
        return;
      }
    }
    if (stream && audioContextRef.current) {
      onStreamReady?.({
        stream,
        audioContext: audioContextRef.current,
      });
    } else {
      handleError(
        'Stream or AudioContext not available for onStreamReady callback.',
      );
      return;
    }
    try {
      const options = {
        mimeType: config?.mimeType || 'audio/webm',
        audioBitsPerSecond: config?.audioBitsPerSecond,
      };
      mediaRecorderRef.current = new MediaRecorder(stream, options);
      mediaRecorderRef.current.ondataavailable = (event) => {
        if (event.data.size > 0) {
          accumulatedChunksRef.current.push(event.data);
        }
      };
      mediaRecorderRef.current.onstop = async () => {
        updateState('processing');
        const allChunks = [...accumulatedChunksRef.current];
        setAudioChunks(allChunks);
        const recordedBlob = new Blob(allChunks, {
          type: mediaRecorderRef.current?.mimeType || 'audio/webm',
        });
        if (!audioContextRef.current) {
          handleError(
            'AudioContext not available for WAV conversion. Providing raw recording.',
          );
          const rawUrl = URL.createObjectURL(recordedBlob);
          setAudioURL(rawUrl);
          onRecordingComplete?.({
            wavBlob: null,
            audioChunks: allChunks,
            duration,
          });
          updateState('finished');
          return;
        }
        try {
          const arrayBuffer = await recordedBlob.arrayBuffer();
          const audioBuffer =
            await audioContextRef.current.decodeAudioData(arrayBuffer);
          const wavBlob = audioBufferToWav(audioBuffer);
          setFinalWavBlob(wavBlob);
          const newAudioURL = URL.createObjectURL(wavBlob);
          setAudioURL(newAudioURL);
          onRecordingComplete?.({
            wavBlob,
            audioChunks: allChunks,
            duration,
          });
          updateState("finished");
        } catch (conversionError) {
          handleError(
            'Error converting audio to WAV. Providing raw recording.',
            conversionError,
          );
          const originalUrl = URL.createObjectURL(recordedBlob);
          setAudioURL(originalUrl);
          setFinalWavBlob(null);
          onRecordingComplete?.({
            wavBlob: null,
            audioChunks: allChunks,
            duration,
          });
          updateState('finished');
        }
      };
      mediaRecorderRef.current.onerror = (event) => {
        handleError('MediaRecorder error.', event);
        stopTimer();
      };
      mediaRecorderRef.current.start();
      updateState('recording');
      startTimer();
    } catch (err) {
      handleError('Failed to start recording.', err);
    }
  }, [
    recordingState,
    audioURL,
    requestPermission,
    onStreamReady,
    config,
    handleError,
    updateState,
    onRecordingComplete,
    duration,
  ]);
  const pause = useCallback(() => {
    if (
      recordingState === 'recording' &&
      mediaRecorderRef.current?.state === 'recording'
    ) {
      mediaRecorderRef.current.pause();
      updateState('paused');
      stopTimer();
    }
  }, [recordingState, updateState]);
  const resume = useCallback(() => {
    if (
      recordingState === 'paused' &&
      mediaRecorderRef.current?.state === 'paused'
    ) {
      mediaRecorderRef.current.resume();
      updateState('recording');
      startTimer();
    }
  }, [recordingState, updateState]);
  const stop = useCallback(async () => {
    if (
      (recordingState === 'recording' || recordingState === 'paused') &&
      mediaRecorderRef.current?.state !== 'inactive'
    ) {
      updateState('stopping');
      mediaRecorderRef.current?.stop();
      stopTimer();
    }
  }, [recordingState, updateState]);
  return {
    recordingState,
    duration,
    audioChunks,
    finalWavBlob,
    audioURL,
    errorMessage,
    isMicrophoneAvailable,
    actions: {
      start,
      pause,
      resume,
      stop,
      requestPermission,
      reset: performReset,
    },
  };
}

// Main App component - Now uses the useAudioRecorder hook and builds its own UI
export function RecorderTestster() {
  const { findText } = useTranslation(wordStore);
  const {
    recordingState,
    duration,
    // audioChunks, // Available if needed for advanced use
    finalWavBlob,
    audioURL,
    errorMessage,
    isMicrophoneAvailable,
    actions,
  } = useAudioRecorder({
    onStateChange: (payload) =>
      console.log(`State Change: ${payload.oldState} -> ${payload.newState}`),
    onTimerUpdate: (time) => console.log(`Timer Update: ${time}s`),
    onRecordingComplete: (payload) => {
      console.log('App: Recording Complete', payload);
      if (payload.wavBlob)
        console.log('App: WAV Blob size:', payload.wavBlob.size);
    },
    onError: (error) => console.error('App: Recorder Error', error),
    onStreamReady: (payload) => {
      console.log('App: Stream Ready', payload);
      // Example: You could initialize WaveSurfer here with payload.stream and payload.audioContext
    },
    config: {
      mimeType: "audio/webm;codecs=opus",
    },
  });
  const formatDurationForDisplay = (seconds) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
  };

  // Cleanup for audioURL when App unmounts or audioURL changes
  useEffect(() => {
    return () => {
      if (audioURL) {
        URL.revokeObjectURL(audioURL);
      }
    };
  }, [audioURL]);
  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-900 to-slate-800 text-white flex flex-col items-center justify-center p-4 font-sans">
      <header className="mb-8 text-center">
        <h1 className="text-4xl sm:text-5xl font-bold mb-2 bg-clip-text text-transparent bg-gradient-to-r from-sky-400 to-blue-500">
          {findText("Headless Audio Recorder Demo")}
        </h1>
        <p className="text-slate-400 text-lg">
          {findText("UI built in App component using the")}{" "}
          <code className="bg-slate-700 px-1 rounded">
            {findText("useAudioRecorder")}
          </code>{" "}
          {findText("hook.")}
        </p>
      </header>

      {/* UI Section built using the hook's state and actions */}
      <div className="w-full max-w-lg bg-slate-800 shadow-2xl rounded-xl p-6 md:p-8 space-y-6">
        <div className="text-center mb-4">
          <h2 className="text-3xl font-semibold text-sky-400 mb-2">
            {findText("Recorder Controls")}
          </h2>
          <p className="text-sm text-slate-400">
            {findText("Hook State:")}{" "}
            <span
              className={findText("font-semibold {arg1}", {
                arg1:
                  recordingState === "recording"
                    ? "text-rose-400 animate-pulse"
                    : recordingState === "paused"
                    ? "text-yellow-400"
                    : recordingState === "processing" ||
                      recordingState === "stopping"
                    ? "text-sky-400 animate-pulse"
                    : recordingState === "finished"
                    ? "text-green-400"
                    : recordingState === "permissionDenied"
                    ? "text-red-400"
                    : "text-slate-300",
              })}
            >
              {recordingState}
            </span>
          </p>
          <p className="text-lg text-slate-200 mt-1">
            {formatDurationForDisplay(duration)}
          </p>
        </div>

        {!isMicrophoneAvailable && (
          <div
            className="bg-red-700/50 border border-red-600 text-red-200 px-4 py-3 rounded-lg flex items-center"
            role="alert"
          >
            <AlertTriangle size={20} className="mr-3 flex-shrink-0" />
            <span>
              {findText(
                "Microphone/MediaDevices API not available on this browser."
              )}
            </span>
          </div>
        )}

        {errorMessage && recordingState !== 'permissionNeeded' && (
          <div
            className="bg-red-500/20 border border-red-500 text-red-300 px-4 py-3 rounded-lg flex items-center"
            role="alert"
          >
            <AlertTriangle size={20} className="mr-3 flex-shrink-0" />
            <span>{errorMessage}</span>
          </div>
        )}

        {isMicrophoneAvailable && recordingState === 'permissionNeeded' && (
          <div className="text-center p-4 bg-yellow-800 bg-opacity-50 border border-yellow-700 rounded-lg space-y-3">
            <div className="flex items-center justify-center text-yellow-300">
              <AlertTriangle size={24} className="mr-2" />
              <h3 className="text-lg font-semibold">
                {findText("Microphone Access Required")}
              </h3>
            </div>
            <p className="text-yellow-200 text-sm">
              {findText(
                "To record audio, this application needs access to your microphone. Please grant permission when prompted by your browser."
              )}
            </p>
            <button
              onClick={actions.requestPermission}
              className="w-full flex items-center justify-center px-4 py-3 bg-yellow-500 hover:bg-yellow-600 text-slate-900 font-semibold rounded-lg shadow-md transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-yellow-400"
            >
              <CheckCircle size={20} className="mr-2" />
              {findText("Grant Microphone Permission")}
            </button>
          </div>
        )}

        {recordingState === 'permissionDenied' && (
          <div className="text-center p-4 bg-red-800 bg-opacity-70 border border-red-700 rounded-lg">
            <AlertTriangle size={32} className="mx-auto mb-2 text-red-300" />
            <p className="text-red-200 mb-1 font-semibold">
              {findText("Microphone Access Denied")}
            </p>
            <p className="text-sm text-red-300 mb-3">
              {errorMessage &&
              errorMessage !== 'Microphone permission is denied.'
                ? errorMessage
                : "Please enable microphone permissions in your browser's site settings."}
            </p>
            <button
              onClick={actions.reset}
              className="mt-2 px-4 py-2 bg-slate-600 hover:bg-slate-500 text-white font-semibold rounded-lg shadow-md transition-colors text-sm"
            >
              <RefreshCw size={16} className="mr-2 inline" />
              {findText("Try Reset & Re-check Permission")}
            </button>
          </div>
        )}

        {['ready', 'recording', 'paused', 'finished'].includes(
          recordingState,
        ) && (
          <div className="space-y-4">
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
              {recordingState !== 'recording' &&
                recordingState !== 'paused' && (
                  <button
                    onClick={actions.start}
                    disabled={
                      recordingState === 'processing' ||
                      recordingState === 'stopping' ||
                      recordingState === 'permissionDenied'
                    }
                    className="w-full flex items-center justify-center px-6 py-3 bg-sky-500 hover:bg-sky-600 disabled:bg-slate-600 text-white font-semibold rounded-lg shadow-md transition-all"
                  >
                    <Mic size={20} className="mr-2" />
                    {findText("Start Recording")}
                  </button>
                )}

              {recordingState === 'recording' && (
                <button
                  onClick={actions.pause}
                  className="w-full flex items-center justify-center px-6 py-3 bg-yellow-500 hover:bg-yellow-600 text-slate-900 font-semibold rounded-lg shadow-md transition-all"
                >
                  <Pause size={20} className="mr-2" />
                  {findText("Pause")}
                </button>
              )}

              {recordingState === 'paused' && (
                <button
                  onClick={actions.resume}
                  className="w-full flex items-center justify-center px-6 py-3 bg-green-500 hover:bg-green-600 text-white font-semibold rounded-lg shadow-md transition-all"
                >
                  <Play size={20} className="mr-2" />
                  {findText("Resume")}
                </button>
              )}

              {(recordingState === 'recording' ||
                recordingState === 'paused') && (
                <button
                  onClick={actions.stop}
                  className="w-full flex items-center justify-center px-6 py-3 bg-rose-500 hover:bg-rose-600 text-white font-semibold rounded-lg shadow-md transition-all"
                >
                  <StopCircle size={20} className="mr-2" />
                  {findText("Stop")}
                </button>
              )}
            </div>
            {(recordingState === 'ready' || recordingState === 'finished') &&
              recordingState !== 'recording' &&
              recordingState !== 'paused' && (
                <button
                  onClick={actions.reset}
                  className="w-full flex items-center justify-center px-4 py-2 bg-slate-600 hover:bg-slate-500 text-white font-semibold rounded-lg shadow-md transition-colors text-sm"
                >
                  <RefreshCw size={16} className="mr-2" />
                  {findText("Reset Recorder")}
                </button>
              )}

            {audioURL && recordingState === 'finished' && (
              <div className="mt-6 p-4 bg-slate-700 rounded-lg shadow">
                <h3 className="text-lg font-medium text-sky-300 mb-3">
                  {findText("Recording Complete")}
                  {finalWavBlob ? findText("(WAV)") : findText("(Raw Format)")}
                </h3>
                {!finalWavBlob && (
                  <p className="text-sm text-slate-400 mb-2">
                    {findText("WAV conversion failed. Raw audio is available.")}
                  </p>
                )}
                <audio
                  controls
                  src={audioURL}
                  className="w-full rounded-md shadow-inner bg-slate-600"
                >
                  {findText("Your browser does not support the audio element.")}
                </audio>
                <a
                  href={audioURL}
                  download={findText("recording-{arg1}.{arg2}", {
                    arg1: new Date()
                      .toISOString()
                      .slice(0, 19)
                      .replace(/:/g, "-"),
                    arg2: finalWavBlob ? "wav" : "webm",
                  })}
                  className={findText(
                    "mt-4 w-full flex items-center justify-center px-6 py-3 text-white font-semibold rounded-lg shadow-md transition-colors {arg1}",
                    {
                      arg1: finalWavBlob
                        ? "bg-teal-500 hover:bg-teal-600"
                        : "bg-orange-500 hover:bg-orange-600",
                    }
                  )}
                >
                  <Download size={20} className="mr-2" />
                  {findText("Download")}{" "}
                  {finalWavBlob ? findText("WAV") : findText("Raw Audio")}
                </a>
              </div>
            )}
          </div>
        )}
      </div>

      <footer className="mt-12 text-center text-slate-500 text-sm">
        <p>
          &copy; {new Date().getFullYear()}
          {findText("Your Company. All rights reserved.")}
        </p>
      </footer>
    </div>
  );
}
