// app/video/video.tsx (ou .jsx selon ton setup)
'use client'

import React, { useEffect, useState, useRef, useCallback } from 'react'
import { useRouter } from 'next/navigation'
import { useSocket } from '@/components/SocketClient'
import Timer from '@/components/videoChat/Timer'
import { Button } from '@/components/ui/button'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faMicrophoneSlash, faMicrophone, faVideo, faVideoSlash, faVolumeHigh, faVolumeXmark } from '@fortawesome/free-solid-svg-icons'
import { ArrowsPointingOutIcon } from '@heroicons/react/24/outline'
import Image from 'next/image'
import shareScreenIcon from '@/assets/share-screen.svg'
import { ToastContainer } from 'react-toastify'
import 'react-toastify/dist/ReactToastify.css'
import Chat from '../chat/chat'

type Props = {
  role: 'offerer' | 'answer'
  roomId: string
  session: any
  appointment: any
  clientInfo: any
  expertInfo: any
  messagesFromDB: any
}

const parseTurnUrls = () => {
  const raw = process.env.NEXT_PUBLIC_TURN_URLS || ''
  return raw.split(',').map(s => s.trim()).filter(Boolean)
}

export default function VideoCallComponent({
  role,
  roomId,
  session,
  appointment,
  clientInfo,
  expertInfo,
  messagesFromDB,
}: Props) {
  const router = useRouter()
  const isOfferer = role === 'offerer'

  // ---- Refs vidéo
  const localVideoRef = useRef<HTMLVideoElement | null>(null)
  const remoteVideoRef = useRef<HTMLVideoElement | null>(null)
  const screenVideoRef = useRef<HTMLVideoElement | null>(null)

  // ---- WebRTC
  const peerConnectionRef = useRef<RTCPeerConnection | null>(null)
  const isRenegotiatingRef = useRef(false)
  const offerInFlightRef = useRef(false)

  // ---- Socket
  const socket = useSocket()
  const socketRef = useRef<any>(null)
  useEffect(() => { if (socket) socketRef.current = socket }, [socket])

  // ---- Streams
  const [localStream, setLocalStream] = useState<MediaStream | null>(null)
  const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null)
  const [screenStream, setScreenStream] = useState<MediaStream | null>(null)

  // ---- UI state
  const [isMeetingStarted, setIsMeetingStarted] = useState(false)
  const [isMicEnabled, setIsMicEnabled] = useState(true)
  const [isCameraEnabled, setIsCameraEnabled] = useState(true)
  const [isScreenSharing, setIsScreenSharing] = useState(false)
  const [remoteMuted, setRemoteMuted] = useState(true)
  const [remainingTime, setRemainingTime] = useState<string>('')
  const [timeLeft, setTimeLeft] = useState<number | undefined>(undefined)
  const [showChat, setShowChat] = useState(true)
  const [showEmojis, setShowEmojis] = useState(false)
  const [hideMediaIcons, setHideMediaIcons] = useState(false)
  const [needsPermission, setNeedsPermission] = useState(false)
  const [showEndConfirm, setShowEndConfirm] = useState(false)
  const [ending, setEnding] = useState(false)

  const APPOINTMENTS_URL = '/dashboard/appointments'

  // ---- Register user room (notifications RDV)
  useEffect(() => {
    if (!socket || !session?.user?.userId) return
    const uid = session.user.userId
    const reg = () => socket.emit('register user', { userId: uid })
    reg()
    socket.on('connect', reg)
    return () => socket.off('connect', reg)
  }, [socket, session?.user?.userId])

  // ---- emit helper
  const emit = useCallback((event: string, payload: any) => {
    const s = socketRef.current ?? socket
    if (!s) return
    s.emit(event, payload)
  }, [socket])

  // ---- Create peer connection
  const createPeerConnection = (): RTCPeerConnection => {
  const turnUrls = parseTurnUrls();

  const stunUrls = [
    'stun:stun.l.google.com:19302',
    'stun:stun1.l.google.com:19302',
    'stun:stun2.l.google.com:19302',
    'stun:stun3.l.google.com:19302',
    'stun:stun4.l.google.com:19302',
  ];

  const iceServers: RTCIceServer[] = [{ urls: stunUrls }];

  if (turnUrls.length) {
    iceServers.push({
      urls: turnUrls,                           // e.g. ["turn:xxx:3478","turns:xxx:5349"]
      username: process.env.NEXT_PUBLIC_TURN_USER,
      credential: process.env.NEXT_PUBLIC_TURN_PASS,
    });
  }

  const pc = new RTCPeerConnection({
    iceServers,
    iceTransportPolicy: 'all',                  // default, but explicit
    // iceCandidatePoolSize: 0,                 // optional; leave default unless you pre-gather
  });

  pc.onicecandidate = (event) => {
    if (event.candidate) {
      // quick visibility on candidate type: host/srflx/relay
      console.log('[ICE] candidate:', event.candidate.candidate);
      emit('ice-candidate', { roomId, candidate: event.candidate, userId: session?.user?.userId });
    }
  };

  pc.onicegatheringstatechange = () => console.log('[ICE] gathering:', pc.iceGatheringState);
  pc.oniceconnectionstatechange = () => {
    console.log('[ICE] conn:', pc.iceConnectionState);
    if ((pc.iceConnectionState === 'disconnected' || pc.iceConnectionState === 'failed') && isMeetingStarted) {
      renegotiate(true);
    }
  };

  pc.onconnectionstatechange = () => {
    console.log('[PC] state:', pc.connectionState);
    if ((pc.connectionState === 'disconnected' || pc.connectionState === 'failed') && isMeetingStarted) {
      renegotiate(true);
    }
  };

  pc.ontrack = async (event) => {
    const stream = event.streams[0];
    if (!stream) return;
    const track = event.track;
    const settings = typeof track.getSettings === 'function' ? track.getSettings() : {};
    const isDisplay = (settings && 'displaySurface' in settings) || (track.label && track.label.toLowerCase().includes('screen'));

    if (track.kind === 'video' && isDisplay) {
      setIsScreenSharing(true);
      setScreenStream(stream);
      if (screenVideoRef.current) {
        screenVideoRef.current.srcObject = stream;
        await screenVideoRef.current.play().catch(() => {});
      }
    } else {
      setRemoteStream(stream);
      if (remoteVideoRef.current) {
        remoteVideoRef.current.muted = true;
        remoteVideoRef.current.srcObject = stream;
        await remoteVideoRef.current.play().catch(() => {});
      }
    }
  };

  return pc;
};


  // ---- Capture locale
  const ensureLocalTracks = useCallback(async () => {
    let pc = peerConnectionRef.current
    if (!pc) { pc = createPeerConnection(); peerConnectionRef.current = pc }

    let stream = localStream
    if (!stream) {
      try {
        stream = await navigator.mediaDevices.getUserMedia({
          video: { width: 1280, height: 720 },
          audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },
        })
        setLocalStream(stream)
        setNeedsPermission(false)
      } catch (e) {
        console.error('[webrtc] getUserMedia failed:', e)
        setNeedsPermission(true)
        return
      }
    }

    if (localVideoRef.current && localVideoRef.current.srcObject !== stream) {
      localVideoRef.current.srcObject = stream
      await localVideoRef.current.play().catch(() => {})
    }

    const senders = pc.getSenders().filter(s => s.track)
    const hasV = senders.some(s => s.track?.kind === 'video')
    const hasA = senders.some(s => s.track?.kind === 'audio')
    const v = stream.getVideoTracks()[0]
    const a = stream.getAudioTracks()[0]
    if (!hasV && v) pc.addTrack(v, stream)
    if (!hasA && a) pc.addTrack(a, stream)

    stream.getVideoTracks().forEach(t => (t.enabled = isCameraEnabled))
    stream.getAudioTracks().forEach(t => (t.enabled = isMicEnabled))
  }, [localStream, isCameraEnabled, isMicEnabled])

  // Preview immédiate
  useEffect(() => { (async () => { await ensureLocalTracks() })() }, [ensureLocalTracks])

  // ---- Renégociation
  const renegotiate = async (iceRestart: boolean) => {
    if (isRenegotiatingRef.current) return
    await ensureLocalTracks()
    const pc = peerConnectionRef.current; if (!pc) return
    try {
      isRenegotiatingRef.current = true
      const offer = await pc.createOffer({ iceRestart })
      await pc.setLocalDescription(offer)
      emit('offer', { roomId, offer, negotiationType: isScreenSharing ? 'screenShare' : 'regular', userId: session?.user?.userId })
    } catch (e) {
      console.error('renegotiate error', e)
      isRenegotiatingRef.current = false
    }
  }

  // ---- Démarrage : seul l’offerer crée l’offer
  const tryStartCall = useCallback(async () => {
    if (!isOfferer || offerInFlightRef.current) return
    try {
      await ensureLocalTracks()
      const pc = peerConnectionRef.current; if (!pc) return
      const offer = await pc.createOffer({ iceRestart: true })
      await pc.setLocalDescription(offer)
      offerInFlightRef.current = true
      emit('offer', { roomId, offer, negotiationType: 'regular', userId: session?.user?.userId })
    } catch (e) {
      offerInFlightRef.current = false
      console.error('tryStartCall error:', e)
    }
  }, [isOfferer, ensureLocalTracks, emit, roomId])

  // ---- Socket: signalling
  useEffect(() => {
    const sock = socketRef.current ?? socket
    if (!sock) return

    const handleOffer = async ({ offer, negotiationType }: any) => {
      try {
        await ensureLocalTracks()
        const pc = peerConnectionRef.current!
        await pc.setRemoteDescription(new RTCSessionDescription(offer))
        const answer = await pc.createAnswer()
        await pc.setLocalDescription(answer)
        emit('answer', { roomId, answer, negotiationType: negotiationType || 'regular', userId: session?.user?.userId })
        setIsMeetingStarted(true)
      } catch (e) {
        console.error('receive offer error', e)
      }
    }
    const handleAnswer = async ({ answer, negotiationType }: any) => {
      try {
        const pc = peerConnectionRef.current; if (!pc) return
        await pc.setRemoteDescription(new RTCSessionDescription(answer))
        offerInFlightRef.current = false
        setIsMeetingStarted(true)
        if (negotiationType === 'stopScreenShare') {
          setIsScreenSharing(false)
          if (screenVideoRef.current) screenVideoRef.current.srcObject = null
        }
      } catch (e) {
        console.error('receive answer error', e)
      } finally {
        isRenegotiatingRef.current = false
      }
    }
    const handleIce = async ({ candidate }: any) => {
      try {
        if (candidate && peerConnectionRef.current) {
          await peerConnectionRef.current.addIceCandidate(new RTCIceCandidate(candidate))
        }
      } catch (e) { console.error('add ICE error', e) }
    }
    const handleMeetingStart = (data: any) => {
      if (data && typeof data.remaining === 'number') {
        const ms = data.remaining
        let sec = Math.floor(ms / 1000)
        const min = Math.floor(sec / 60)
        sec = sec % 60
        setTimeLeft(ms)
        setRemainingTime(`${min}m ${sec < 10 ? '0' : ''}${sec}s`)
        setIsMeetingStarted(true)
      }
    }
    const handleMeetingEnded = () => finishAndLeave()

    // (optionnel) si le serveur demande un resend-offer
    const handleResendOffer = async () => { if (isOfferer) await renegotiate(true) }

    sock.on('offer', handleOffer)
    sock.on('answer', handleAnswer)
    sock.on('ice-candidate', handleIce)
    sock.on('meeting started', handleMeetingStart)
    sock.on('meeting ended', handleMeetingEnded)
    sock.on('resend-offer', handleResendOffer)

    return () => {
      sock.off('offer', handleOffer)
      sock.off('answer', handleAnswer)
      sock.off('ice-candidate', handleIce)
      sock.off('meeting started', handleMeetingStart)
      sock.off('meeting ended', handleMeetingEnded)
      sock.off('resend-offer', handleResendOffer)
    }
  }, [socket, emit, ensureLocalTracks, isOfferer])

  // ---- Join room (une seule fois) puis si offerer, démarrer
  const joinedOnceRef = useRef(false)
  useEffect(() => {
    if (!socket || !session?.user?.userId || joinedOnceRef.current) return
    joinedOnceRef.current = true
    const isExpert = appointment.clientId !== session.user.userId
    emit('join room', {
      roomId,
      userId: session.user.userId,
      isExpert,
      appointmentId: appointment.appointmentKey,
      appointment,
    })
    // in case a negotiation is already in progress, fetch the last offer
  emit('check negotiation', { roomId, userId: session.user.userId })
    if (isOfferer) setTimeout(() => { tryStartCall() }, 300)
  }, [socket, roomId, session?.user?.userId, appointment, emit, isOfferer, tryStartCall])

  // ---- Partage d’écran
  const startScreenShare = async () => {
    if (!peerConnectionRef.current) return
    try {
      const s = await navigator.mediaDevices.getDisplayMedia({ video: true })
      setScreenStream(s); setIsScreenSharing(true)
      if (screenVideoRef.current) { screenVideoRef.current.srcObject = s; await screenVideoRef.current.play().catch(() => {}) }
      const screenTrack = s.getVideoTracks()[0]
      const sender = peerConnectionRef.current.getSenders().find(x => x.track?.kind === 'video')
      if (sender && screenTrack) await sender.replaceTrack(screenTrack)
      const pc = peerConnectionRef.current
      const offer = await pc.createOffer(); await pc.setLocalDescription(offer)
      emit('offer', { roomId, offer, negotiationType: 'screenShare' })
      screenTrack.onended = () => stopScreenShare()
    } catch (e) { console.error('share error', e) }
  }
  const stopScreenShare = async () => {
    if (!isScreenSharing) return
    try {
      const pc = peerConnectionRef.current; if (!pc) return
      setIsScreenSharing(false)
      if (screenVideoRef.current) screenVideoRef.current.srcObject = null
      screenStream?.getTracks().forEach(t => t.stop())
      setScreenStream(null)
      const v = localStream?.getVideoTracks()[0] || null
      const sender = pc.getSenders().find(x => x.track?.kind === 'video')
      if (sender && v) await sender.replaceTrack(v)
      const offer = await pc.createOffer(); await pc.setLocalDescription(offer)
      emit('offer', { roomId, offer, negotiationType: 'stopScreenShare' })
    } catch (e) { console.error('stop share error', e) }
  }

  // ---- Toggles
  const toggleCamera = () => { if (!localStream) return; localStream.getVideoTracks().forEach(t => (t.enabled = !t.enabled)); setIsCameraEnabled(v => !v) }
  const toggleMic = () => { if (!localStream) return; localStream.getAudioTracks().forEach(t => (t.enabled = !t.enabled)); setIsMicEnabled(v => !v) }
  const toggleRemoteAudio = () => {
    const el = remoteVideoRef.current; if (!el) return
    const next = !remoteMuted
    el.muted = next
    setRemoteMuted(next)
    el.play().catch(() => {})
  }
  const toggleFullScreen = (el: HTMLVideoElement | null) => { if (!el) return; if (!document.fullscreenElement) el.requestFullscreen?.(); else document.exitFullscreen?.() }

  // ---- Fin d’appel
  const finishAndLeave = (target: string = APPOINTMENTS_URL) => {
    try { localStream?.getTracks().forEach(t => t.stop()) } catch {}
    try { remoteStream?.getTracks().forEach(t => t.stop()) } catch {}
    try { screenStream?.getTracks().forEach(t => t.stop()) } catch {}
    if (localVideoRef.current) localVideoRef.current.srcObject = null
    if (remoteVideoRef.current) remoteVideoRef.current.srcObject = null
    if (screenVideoRef.current) screenVideoRef.current.srcObject = null
    peerConnectionRef.current?.close(); peerConnectionRef.current = null
    setIsMeetingStarted(false); setIsScreenSharing(false)
    router.replace(target)
  }

  const confirmEndCall = async () => {
    if (ending) return
    setEnding(true)
    try {
      if (socketRef.current) socketRef.current.emit('end-call', { roomId })
    } catch {}
    // on coupe localement tout de suite
    finishAndLeave()
  }

  // ---- Règles chat
  const isPostCall = appointment.status === 'completed'
  const callEndBase = new Date((appointment as any).endedAt ?? appointment.appointmentKey).getTime()
  const writeWindowUntil = isPostCall ? callEndBase + 15 * 24 * 60 * 60 * 1000 : null
  const canSendForChat = isPostCall ? Date.now() <= (writeWindowUntil ?? 0) : isMeetingStarted

  return (
    <>
      {/* Top bar */}
      <div className={`w-full flex items-center ${!showChat && isMeetingStarted ? 'justify-evenly' : 'justify-around'} bg-[#f0f8ff] py-2`}>
        {socketRef.current && (
          <Timer
            socketRef={socketRef}
            setTimeLeft={setTimeLeft}
            timeLeft={timeLeft}
            setHideMediaIcons={setHideMediaIcons}
            setRemainingTime={setRemainingTime}
            remainingTime={remainingTime}
            setisMeetingStarted={setIsMeetingStarted}
          />
        )}

        <div className="flex gap-3">
          <button
            onClick={() => setShowChat(v => !v)}
            className={`py-2 px-4 font-bold rounded-lg text-white transition-colors duration-150 ${
              showChat ? 'bg-red-500 hover:bg-red-700' : 'bg-blue-500 hover:bg-blue-700'
            }`}
          >
            {showChat ? 'Masquer le chat' : 'Afficher le chat'}
          </button>

          <button
            onClick={() => setShowEndConfirm(true)}
            disabled={ending}
            className={`py-2 px-4 font-bold rounded-lg text-white transition-colors duration-150 ${ending ? 'bg-gray-400' : 'bg-red-600 hover:bg-red-700'}`}
            title="Met fin à l'appel (capture / refund selon règles)"
          >
            {ending ? 'Fin en cours…' : 'Fin d’appel'}
          </button>
        </div>
      </div>

      <div className="flex lg:flex-row w-full p-4 max-h-[80vh] gap-4">
        {/* Colonne vidéos */}
        <div className={`flex flex-col gap-4 ${isScreenSharing ? 'lg:items-end w-full lg:w-3/5' : 'w-full lg:w-3/4'}`}>
          {/* Locale */}
          <div
            className={`video-container relative flex justify-center w-full border border-black rounded-[5%] ${isScreenSharing ? 'lg:w-full lg:h-80' : 'h-[70vh]'}`}
            onMouseOver={() => setHideMediaIcons(false)}
            onMouseLeave={() => setHideMediaIcons(true)}
          >
            <div className="absolute top-2 left-2 z-40 text-white text-sm bg-black p-2 opacity-70 rounded">Vous</div>
            <video ref={localVideoRef} autoPlay muted playsInline className="rounded-[5%] shadow-md w-full h-full object-cover bg-white" />
            {!localStream && (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="bg-white/80 rounded-md p-3 text-sm"><p>Préparation de la caméra…</p></div>
              </div>
            )}
            {/* Boutons */}
            <div className="absolute bottom-3 left-1/2 transform -translate-x-1/2 flex gap-4 w-11/12 justify-between">
              <div className={`${hideMediaIcons ? 'hidden' : 'flex'} gap-4 justify-center items-center`}>
                <button onClick={toggleCamera} disabled={!localStream} className="rounded-full bg-white p-2 shadow-sm flex items-center justify-center disabled:opacity-60" aria-label={isCameraEnabled ? 'Désactiver la caméra' : 'Activer la caméra'}>
                  {isCameraEnabled ? <FontAwesomeIcon icon={faVideo} className="w-6 h-6 text-green-500" /> : <FontAwesomeIcon icon={faVideoSlash} className="w-6 h-6 text-red-500" />}
                </button>
                <button onClick={toggleMic} disabled={!localStream} className="rounded-full bg-white p-2 shadow-sm flex items-center justify-center disabled:opacity-60" aria-label={isMicEnabled ? 'Couper le micro' : 'Activer le micro'}>
                  {isMicEnabled ? <FontAwesomeIcon icon={faMicrophone} className="w-6 h-6 text-green-500" /> : <FontAwesomeIcon icon={faMicrophoneSlash} className="w-6 h-6 text-red-500" />}
                </button>
                <button onClick={startScreenShare} className={`rounded-full bg-white p-2 shadow-sm flex items-center justify-center ${isMeetingStarted ? '' : 'hidden'}`} aria-label="Partager l’écran">
                  <Image src={shareScreenIcon} alt="" className="w-6 h-6" />
                </button>
              </div>
              <div
                className={`${hideMediaIcons ? 'hidden' : 'flex'} rounded-full bg-white p-2 shadow-sm items-center justify-center`}
                onClick={() => toggleFullScreen(localVideoRef.current)}
                aria-label="Plein écran caméra locale"
              >
                <ArrowsPointingOutIcon className="w-6 h-6" />
              </div>
            </div>

            {needsPermission && (
              <div className="absolute bottom-4 left-1/2 -translate-x-1/2 bg-white rounded-md shadow px-3 py-2">
                <Button onClick={() => ensureLocalTracks()}>Activer la caméra / micro</Button>
              </div>
            )}
          </div>

          {/* Distante */}
          <div className={`video-container relative rounded-[5%] flex justify-center border border-black ${isScreenSharing ? 'w-full h-80' : 'h-[70vh] w-full'}`}>
            <div className="absolute top-2 left-2 z-40 text-white text-sm bg-black p-2 opacity-70 rounded">
              {session?.user?.userId === appointment?.clientId
                ? `${expertInfo?.firstName ?? ''} ${expertInfo?.lastName ?? ''}`.trim()
                : `${clientInfo?.firstName ?? ''} ${clientInfo?.lastName ?? ''}`.trim()}
            </div>
            <video ref={remoteVideoRef} autoPlay playsInline className="w-full h-full object-cover rounded-[5%] bg-white" />
            {!remoteStream && (
              <div className="absolute inset-0 flex items-center justify-center">
                <div className="bg-white/80 rounded-md p-3 text-sm"><p>En attente de l’autre participant…</p></div>
              </div>
            )}
            <div className="absolute bottom-3 right-3 flex gap-2">
              <button onClick={toggleRemoteAudio} className="rounded-full bg-white p-2 shadow-sm cursor-pointer" aria-label="Activer/Désactiver le son distant">
                {remoteMuted ? <FontAwesomeIcon icon={faVolumeXmark} className="w-6 h-6" /> : <FontAwesomeIcon icon={faVolumeHigh} className="w-6 h-6" />}
              </button>
              <div className="rounded-full bg-white p-2 shadow-sm cursor-pointer" onClick={() => toggleFullScreen(remoteVideoRef.current)} aria-label="Plein écran vidéo distante">
                <ArrowsPointingOutIcon className="w-6 h-6" />
              </div>
            </div>
          </div>

          {/* Partage d’écran distant */}
          {isMeetingStarted && isScreenSharing && (
            <div className="video-container flex-1 mt-4 md:mt-0 border border-blue-400 justify-center w-full h-[70vh] rounded-[5%] relative">
              <video ref={screenVideoRef} autoPlay playsInline className="w-full h-full object-contain rounded-[5%]" />
              <div className="absolute bottom-3 right-3">
                <div className="rounded-full bg-white p-2 shadow-sm cursor-pointer" onClick={() => toggleFullScreen(screenVideoRef.current)} aria-label="Plein écran partage d’écran">
                  <ArrowsPointingOutIcon className="w-6 h-6" />
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Chat */}
        <div className="w-full lg:w-1/4 max-h-[70vh] border border-blue-600 rounded-2xl shadow-xl p-2 pb-1">
          {socketRef.current && (
            <Chat
              userId={session?.user?.userId}
              socketRef={socketRef}
              roomId={roomId}
              messagesFromDB={messagesFromDB}
              showEmojis={showEmojis}
              setShowEmojis={setShowEmojis}
              session={session}
              appointment={appointment}
              expertInfo={expertInfo}
              clientInfo={clientInfo}
              canSend={canSendForChat}
              writeWindowUntil={isPostCall ? writeWindowUntil : null}
            />
          )}
        </div>
      </div>

      {/* Modal fin d’appel */}
      {showEndConfirm && (
        <div className="fixed inset-0 z-50 bg-black/30 flex items-center justify-center">
          <div className="bg-white rounded-lg shadow-xl p-6 w-96">
            <h3 className="text-lg font-semibold mb-2">Terminer l’appel ?</h3>
            <p className="text-sm text-gray-600 mb-4">
              Cette action met fin à l’appel (capture/refund selon les règles). Confirmer ?
            </p>
            <div className="flex justify-end gap-2">
              <button className="px-4 py-2 rounded bg-gray-200 hover:bg-gray-300" onClick={() => setShowEndConfirm(false)}>Annuler</button>
              <button className="px-4 py-2 rounded bg-red-600 text-white hover:bg-red-700 disabled:opacity-60" disabled={ending} onClick={confirmEndCall}>Oui, terminer</button>
            </div>
          </div>
        </div>
      )}

      <ToastContainer />
    </>
  )
}
