'use client';

import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query';
import Image from 'next/image';
import React, { useEffect, useRef, useState } from 'react';
import clsx from 'clsx';
import { agent, public_page } from '@/requests';
import Loading from '@/components/Loading';
import { useDemoCall } from '@/hooks/useDemoCall';
import { CallStatus } from '@/lib/public/enums';
import { Chat, LiveKitRoom, RoomAudioRenderer, useRoomContext } from '@livekit/components-react';
import { createLocalAudioTrack, LocalAudioTrack, LocalTrackPublication } from 'livekit-client';
import { Phone, Mic, MicOff, Loader2 } from 'lucide-react';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { v4 as uuidv4 } from 'uuid';

function VoiceRoom({ roomRef }: { roomRef: React.MutableRefObject<any> }) {
    const room = useRoomContext();

    useEffect(() => {
        roomRef.current = room;
        let track: LocalAudioTrack | null = null;

        const initMic = async () => {
            track = await createLocalAudioTrack({
                echoCancellation: true,
                noiseSuppression: true,
            });
            await room.localParticipant.publishTrack(track, { name: 'microphone' });
        };

        initMic();

        return () => {
            if (track) {
                track.stop();
                room.localParticipant.unpublishTrack(track);
            }
            roomRef.current = null;
        };
    }, [room, roomRef]);

    return null;
}

export default function AgentsShowcasePage() {
    const params = useParams();
    const slug = (params?.partner as string) || '';

    const demoCall = useDemoCall(slug);
    const roomRef = useRef<any>(null);
    const [isMuted, setIsMuted] = useState(false);
    const [showSwitchDialog, setShowSwitchDialog] = useState(false);
    const [agentToSwitch, setAgentToSwitch] = useState<any>(null);
    const agentsListRef = useRef<HTMLDivElement>(null);
    const [chatRoomData, setChatRoomData] = useState<{ url: string; token: string, room_name: string } | null>(null);

    const { data, isLoading, error } = useQuery<any>({
        queryKey: ['agents', slug],
        queryFn: () => public_page.getAgents(slug).then(res => res.data),
        enabled: !!slug,
    });

    useEffect(() => {
        if (data?.agents?.length && !demoCall.activeAgent) {
            const first = data.agents[0];
            demoCall.setActiveAgent({
                data: {
                    agent: first.agent,
                    avatar: first.avatar,
                },
            } as any);
        }
    }, [data?.agents]);

    if (isLoading) return <Loading />;

    if (error || !data) {
        return <div className="p-10 text-center">Page Not Found</div>;
    }

    const agents = data.agents.map((a: any) => ({
        ...a.agent,
        avatar_url: a.avatar?.path ?? null,
        _original: a,
    }));

    const activeId = demoCall.activeAgent?.data?.agent?.id;

    const toggleMute = async () => {
        if (!roomRef.current) return;

        setIsMuted(v => !v);

        const pubs = Array.from(
            roomRef.current.localParticipant.audioTrackPublications.values()
        ) as LocalTrackPublication[];

        for (const pub of pubs) {
            if (!pub.track) continue;
            isMuted ? await pub.track.unmute() : await pub.track.mute();
        }
    };

    const formatDuration = (s: number) =>
        `${Math.floor(s / 60)
            .toString()
            .padStart(2, '0')}:${(s % 60).toString().padStart(2, '0')}`;

    const activeAgent = demoCall.activeAgent?.data?.agent;
    const activeAvatar = demoCall.activeAgent?.data?.avatar;
    const isActive = demoCall.callStatus === CallStatus.ACTIVE;
    const isLoadingCall = demoCall.callStatus === CallStatus.LOADING;

    const handleChatConnect = async () => {
        try {
            const roomName = uuidv4();
            const participantName = `${uuidv4()}-user`;

            const { room } = await public_page.connectChatAgent({ room_name: roomName });

            const tokenData = await public_page.generateChatToken({
                room_name: room,
                participant_name: participantName,
            });
            setChatRoomData(tokenData);
        } catch (error) {
            console.error('Error generating token:', error);
        }
    };

    return (
        <div className="min-h-[100dvh] bg-gray-100 p-4 sm:p-6">
            <div className="max-w-7xl mx-auto space-y-6 sm:space-y-8">
                <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 sm:gap-6">
                    <div className="flex-shrink-0 w-full sm:w-auto flex flex-row sm:flex-col items-center sm:items-start justify-between sm:justify-start gap-4 sm:gap-2">
                        <Image
                            src={data.client.logo?.path ?? '/icons/logo.svg'}
                            alt={data.client.name}
                            width={180}
                            height={60}
                            className="object-contain h-10 sm:h-12 w-auto"
                            priority
                        />
                        <a
                            href="https://www.dezyit.com/"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="hover:opacity-80 transition-opacity"
                        >
                            <Image
                                src="/images/Poweredby dt.webp"
                                alt="Powered by dt"
                                width={120}
                                height={30}
                                className="object-contain h-6 sm:h-7 w-auto"
                            />
                        </a>
                    </div>

                    {activeAgent && (
                        <div className="w-full sm:flex-1 sm:max-w-md flex flex-col justify-end">
                            {isActive ? (
                                <div
                                    className="rounded-2xl sm:rounded-2xl overflow-hidden"
                                    style={{
                                        background: 'linear-gradient(135deg, #9333EA 0%, #EC4899 50%, #EF4444 100%)',
                                        padding: '2px',
                                    }}
                                >
                                    <div
                                        className="rounded-2xl sm:rounded-2xl relative h-[32vh] sm:h-[160px]"
                                        style={{
                                            background: 'linear-gradient(135deg, #29323C 0%, #485563 100%)',
                                        }}
                                    >
                                        <div className="absolute inset-0 sm:hidden">
                                            <div className="relative w-full h-full flex items-center justify-center">
                                                <div className="absolute inset-0 opacity-20">
                                                    <svg
                                                        className="w-full h-full"
                                                        viewBox="0 0 400 400"
                                                        preserveAspectRatio="none"
                                                    >
                                                        <path
                                                            d="M0,300 Q150,250 250,280 Q350,310 400,280"
                                                            stroke="rgba(255,255,255,0.15)"
                                                            strokeWidth="2"
                                                            fill="none"
                                                        />
                                                        <path
                                                            d="M0,340 Q100,290 200,320 Q300,350 400,320"
                                                            stroke="rgba(255,255,255,0.1)"
                                                            strokeWidth="2"
                                                            fill="none"
                                                        />
                                                    </svg>
                                                </div>

                                                {activeAvatar?.path ? (
                                                    <div className="absolute bottom-0 left-0 right-0 flex items-end justify-center h-[70%]">
                                                        <div className="relative w-full max-w-[420px] h-full">
                                                            <Image
                                                                src={activeAvatar.path}
                                                                alt={activeAgent.name}
                                                                fill
                                                                className="object-contain object-bottom"
                                                            />
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <div className="absolute bottom-0 left-0 right-0 flex items-end justify-center h-[70%] pb-4 text-6xl text-white/10">
                                                        {activeAgent.name[0]}
                                                    </div>
                                                )}

                                                <div className="absolute top-4 left-4 z-10 max-w-[calc(100%-160px)] pr-2 sm:max-w-none">
                                                    <h3 className="text-2xl font-bold text-white mb-1 break-words line-clamp-2">
                                                        {activeAgent.name}
                                                    </h3>
                                                    <p className="text-sm text-gray-300">
                                                        {activeAgent.role || 'Your AI Friend'}
                                                    </p>
                                                </div>

                                                <div className="absolute top-4 right-4 z-10 flex flex-col items-end gap-3">
                                                    <div className="flex items-center gap-2">
                                                        <Image
                                                            src="/call-activity.gif"
                                                            alt="Active"
                                                            width={32}
                                                            height={24}
                                                            className="w-11 h-auto"
                                                        />
                                                        <span className="text-2xl font-mono tabular-nums text-white font-semibold">
                                                            {formatDuration(demoCall.callDuration)}
                                                        </span>
                                                    </div>

                                                    <div className="flex items-center gap-3">
                                                        <button
                                                            onClick={toggleMute}
                                                            className={clsx(
                                                                'w-10 h-10 rounded-full flex items-center justify-center transition-colors',
                                                                isMuted
                                                                    ? 'bg-gray-400 hover:bg-gray-500'
                                                                    : 'bg-gray-300/30 hover:bg-gray-300/40 backdrop-blur-sm'
                                                            )}
                                                        >
                                                            {isMuted ? (
                                                                <MicOff size={18} className="text-gray-800" />
                                                            ) : (
                                                                <Mic size={18} className="text-white" />
                                                            )}
                                                        </button>
                                                        <button
                                                            onClick={demoCall.stopCall}
                                                            className="w-10 h-10 rounded-full bg-red-600 hover:bg-red-700 flex items-center justify-center transition-colors"
                                                        >
                                                            <Phone size={18} className="text-white rotate-[135deg]" />
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="hidden sm:flex px-4 sm:px-5 pt-4 sm:pt-5 h-full relative">
                                            <div className="flex items-end shrink-0 mr-4">
                                                <div className="w-14 h-14 sm:w-32 sm:h-32 border-2 border-white/20 rounded-full relative flex items-end justify-center overflow-visible">
                                                    {activeAvatar?.path ? (
                                                        <div className="absolute bottom-0 left-1/2 -translate-x-1/2 scale-[2.5] origin-bottom">
                                                            <Image
                                                                src={activeAvatar.path}
                                                                alt={activeAgent.name}
                                                                width={120}
                                                                height={100}
                                                                className="object-contain object-bottom"
                                                                style={{ height: '100px' }}
                                                            />
                                                        </div>
                                                    ) : (
                                                        <div className="w-full h-full bg-gradient-to-br from-blue-600 to-purple-600 flex items-center justify-center text-xl sm:text-2xl font-bold text-white rounded-full">
                                                            {activeAgent.name[0]}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>

                                            <div className="flex-1 flex flex-col justify-between pt-0">
                                                <div className="sm:max-w-[calc(100%-200px)]">
                                                    <h3 className="text-lg sm:text-xl font-bold text-white break-words mb-0.5">
                                                        {activeAgent.name}
                                                    </h3>
                                                    <p className="text-xs sm:text-sm text-gray-400 italic whitespace-nowrap">
                                                        {activeAgent.role ||
                                                            activeAgent.description ||
                                                            'Your AI Friend'}
                                                    </p>
                                                </div>

                                                <div className="flex items-center justify-end gap-2 pb-4">
                                                    <button
                                                        onClick={toggleMute}
                                                        className={clsx(
                                                            'w-9 h-9 sm:w-10 sm:h-10 rounded-full flex items-center justify-center transition-colors',
                                                            isMuted
                                                                ? 'bg-red-500/80 hover:bg-red-500'
                                                                : 'bg-gray-600/80 hover:bg-gray-600'
                                                        )}
                                                    >
                                                        {isMuted ? (
                                                            <MicOff size={18} className="text-white" />
                                                        ) : (
                                                            <Mic size={18} className="text-white" />
                                                        )}
                                                    </button>
                                                    <button
                                                        onClick={demoCall.stopCall}
                                                        className="w-9 h-9 sm:w-10 sm:h-10 rounded-full bg-red-600 hover:bg-red-700 flex items-center justify-center transition-colors"
                                                    >
                                                        <Phone size={18} className="text-white rotate-[135deg]" />
                                                    </button>
                                                </div>
                                            </div>

                                            <div className="absolute top-4 right-4 sm:right-5 flex items-center gap-2">
                                                <Image
                                                    src="/call-activity.gif"
                                                    alt="Active"
                                                    width={32}
                                                    height={24}
                                                    className="w-9 sm:w-12 h-auto"
                                                />
                                                <span className="text-lg sm:text-xl font-mono tabular-nums text-white font-semibold">
                                                    {formatDuration(demoCall.callDuration)}
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ) : (
                                <div
                                    className="rounded-2xl sm:rounded-2xl overflow-hidden"
                                    style={{
                                        background: 'linear-gradient(135deg, #9333EA 0%, #EC4899 50%, #EF4444 100%)',
                                        padding: '2px',
                                    }}
                                >
                                    <div
                                        className="rounded-2xl sm:rounded-2xl relative h-[32vh] sm:h-[160px]"
                                        style={{
                                            background: 'linear-gradient(135deg, #29323C 0%, #485563 100%)',
                                        }}
                                    >
                                        <div className="absolute inset-0 sm:hidden">
                                            <div className="relative w-full h-full flex items-center justify-center">
                                                <div className="absolute inset-0 opacity-20">
                                                    <svg
                                                        className="w-full h-full"
                                                        viewBox="0 0 400 400"
                                                        preserveAspectRatio="none"
                                                    >
                                                        <path
                                                            d="M0,300 Q150,250 250,280 Q350,310 400,280"
                                                            stroke="rgba(255,255,255,0.15)"
                                                            strokeWidth="2"
                                                            fill="none"
                                                        />
                                                        <path
                                                            d="M0,340 Q100,290 200,320 Q300,350 400,320"
                                                            stroke="rgba(255,255,255,0.1)"
                                                            strokeWidth="2"
                                                            fill="none"
                                                        />
                                                    </svg>
                                                </div>

                                                {activeAvatar?.path ? (
                                                    <div className="absolute bottom-0 left-0 right-0 flex items-end justify-center h-[70%]">
                                                        <div className="relative w-full max-w-[350px] h-full">
                                                            <Image
                                                                src={activeAvatar.path}
                                                                alt={activeAgent.name}
                                                                fill
                                                                className="object-contain object-bottom"
                                                            />
                                                        </div>
                                                    </div>
                                                ) : (
                                                    <div className="absolute bottom-0 left-0 right-0 flex items-end justify-center h-[70%] pb-4 text-6xl text-white/10">
                                                        {activeAgent.name[0]}
                                                    </div>
                                                )}

                                                <div className="absolute top-4 left-4 z-10 max-w-[calc(100%-160px)] pr-2 sm:max-w-none">
                                                    <h3 className="text-2xl font-bold text-white mb-1 break-words line-clamp-2">
                                                        {activeAgent.name}
                                                    </h3>
                                                    <p className="text-sm text-gray-300">
                                                        {activeAgent.role || 'Your AI Friend'}
                                                    </p>
                                                </div>

                                                <div className="absolute top-4 right-4 z-10">
                                                    <button
                                                        onClick={() => demoCall.toggleCall(demoCall.activeAgent!)}
                                                        disabled={isLoadingCall}
                                                        className={clsx(
                                                            'rounded-full px-4 py-2 bg-green-600 hover:bg-green-700 flex items-center justify-center gap-2 transition-colors text-white font-medium text-sm shadow-lg',
                                                            isLoadingCall && 'opacity-50 cursor-not-allowed'
                                                        )}
                                                    >
                                                        {isLoadingCall ? (
                                                            <>
                                                                <Loader2 className="w-4 h-4 text-white animate-spin" />
                                                                <span>Connecting…</span>
                                                            </>
                                                        ) : (
                                                            <>
                                                                <Phone size={18} className="text-white" />
                                                                <span>Start a Call</span>
                                                            </>
                                                        )}
                                                    </button>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="hidden sm:flex px-4 sm:px-5 pt-4 sm:pt-5 h-full relative">
                                            <div className="flex items-end shrink-0 mr-4">
                                                <div className="w-14 h-14 sm:w-32 sm:h-32 border-2 border-white/20 rounded-full relative flex items-end justify-center overflow-visible">
                                                    {activeAvatar?.path ? (
                                                        <div className="absolute bottom-0 left-1/2 -translate-x-1/2 scale-[2.5] origin-bottom">
                                                            <Image
                                                                src={activeAvatar.path}
                                                                alt={activeAgent.name}
                                                                width={120}
                                                                height={100}
                                                                className="object-contain object-bottom"
                                                                style={{ height: '100px' }}
                                                            />
                                                        </div>
                                                    ) : (
                                                        <div className="w-full h-full bg-gradient-to-br from-blue-600 to-purple-600 flex items-center justify-center text-xl sm:text-2xl font-bold text-white rounded-full">
                                                            {activeAgent.name[0]}
                                                        </div>
                                                    )}
                                                </div>
                                            </div>

                                            <div className="flex-1 flex flex-col justify-between pt-0">
                                                <div>
                                                    <h3 className="text-lg sm:text-xl font-bold text-white truncate mb-0.5">
                                                        {activeAgent.name}
                                                    </h3>
                                                    <p className="text-xs sm:text-sm text-gray-400 italic truncate">
                                                        {activeAgent.role || 'Your AI Friend'}
                                                    </p>
                                                </div>

                                                <div className="flex pb-4">
                                                    <button
                                                        onClick={() => demoCall.toggleCall(demoCall.activeAgent!)}
                                                        disabled={isLoadingCall}
                                                        className={clsx(
                                                            'rounded-full px-4 sm:px-5 py-2 sm:py-2.5 bg-green-600 hover:bg-green-700 flex items-center justify-center gap-2 transition-colors text-white font-medium text-sm sm:text-base shadow-md hover:shadow-lg',
                                                            isLoadingCall && 'opacity-50 cursor-not-allowed'
                                                        )}
                                                    >
                                                        {isLoadingCall ? (
                                                            <>
                                                                <Loader2 className="w-4 h-4 sm:w-5 sm:h-5 animate-spin" />
                                                                <span className="hidden sm:inline">Connecting…</span>
                                                            </>
                                                        ) : (
                                                            <>
                                                                <Phone size={18} className="sm:w-5 sm:h-5" />
                                                                Start a Call
                                                            </>
                                                        )}
                                                    </button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </div>

                <div className="sm:hidden flex items-center justify-between px-4 mb-4">
                    <h2 className="text-base font-medium text-gray-700">Browse Other Use Cases</h2>
                    <div className="flex items-center gap-2">
                        <button
                            onClick={() => {
                                if (agentsListRef.current) {
                                    agentsListRef.current.scrollBy({
                                        left: -300,
                                        behavior: 'smooth',
                                    });
                                }
                            }}
                            className="w-8 h-8 flex items-center justify-center hover:opacity-80 transition-opacity"
                        >
                            <Image
                                src="/icons/Arrow left-circle.png"
                                alt="Previous"
                                width={32}
                                height={32}
                                className="w-8 h-8"
                            />
                        </button>
                        <button
                            onClick={() => {
                                if (agentsListRef.current) {
                                    agentsListRef.current.scrollBy({
                                        left: 300,
                                        behavior: 'smooth',
                                    });
                                }
                            }}
                            className="w-8 h-8 flex items-center justify-center hover:opacity-80 transition-opacity"
                        >
                            <Image
                                src="/icons/Arrow right-circle.png"
                                alt="Next"
                                width={32}
                                height={32}
                                className="w-8 h-8"
                            />
                        </button>
                    </div>
                </div>

                <div ref={agentsListRef} className="sm:hidden overflow-x-auto pb-4 -mx-4 px-4 scroll-smooth">
                    <div className="flex gap-4" style={{ width: 'max-content' }}>
                        {agents.map((agent: any) => {
                            const isCurrent = agent.id === activeId;
                            const status = isCurrent ? demoCall.callStatus : CallStatus.INACTIVE;
                            const isAgentActive = status === CallStatus.ACTIVE;
                            const isAgentLoadingCall = status === CallStatus.LOADING;

                            return (
                                <div
                                    key={agent.id}
                                    className={clsx(
                                        'bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-md transition-shadow cursor-pointer flex flex-col w-[280px] shrink-0 mt-0.5',
                                        isCurrent && 'ring-2 ring-blue-500'
                                    )}
                                    onClick={() => {
                                        if (!isCurrent) {
                                            if (isActive) {
                                                setAgentToSwitch(agent._original);
                                                setShowSwitchDialog(true);
                                            } else {
                                                demoCall.setActiveAgent({
                                                    data: agent._original,
                                                } as any);
                                            }
                                        }
                                    }}
                                >
                                    <div className="p-4 sm:p-5 pb-3">
                                        <h3 className="text-base sm:text-lg font-bold text-black mb-2">{agent.name}</h3>
                                        <p className="text-xs sm:text-sm text-gray-600 line-clamp-2">
                                            {agent.description || agent.role}
                                        </p>
                                    </div>

                                    <div
                                        className="relative h-[25rem] flex-shrink-0 overflow-hidden mt-auto"
                                        style={{
                                            backgroundImage: 'url(/images/Arabic-bg.png)',
                                            backgroundSize: 'cover',
                                            backgroundPosition: 'center',
                                            backgroundRepeat: 'no-repeat',
                                        }}
                                    >
                                        {agent.avatar_url ? (
                                            <Image
                                                src={agent.avatar_url}
                                                alt={agent.name}
                                                fill
                                                className="object-cover object-bottom"
                                            />
                                        ) : (
                                            <div className="w-full h-full flex items-end justify-center pb-4 text-5xl sm:text-6xl text-gray-300">
                                                {agent.name[0]}
                                            </div>
                                        )}

                                        <div className="absolute bottom-0 left-0 right-0 p-3 sm:p-4 bg-gradient-to-t from-black/20 via-black/5 to-transparent">
                                            <div
                                                className={clsx(
                                                    'w-full rounded-2xl sm:rounded-3xl h-12 sm:h-14 bg-gray-800/30 hover:bg-gray-800/40 backdrop-blur-md flex items-center justify-between px-4 sm:px-5 transition-colors shadow-lg border border-white/10',
                                                    isAgentActive && 'bg-gray-900/30 hover:bg-gray-900/40'
                                                )}
                                            >
                                                <div className="flex items-center gap-3 flex-1 min-w-0">
                                                    <div className="w-2.5 h-2.5 sm:w-3 sm:h-3 rounded-full bg-green-500 shrink-0" />
                                                    <span className="text-white text-sm sm:text-base font-medium truncate">
                                                        {agent.name}
                                                    </span>
                                                </div>

                                                <button
                                                    onClick={e => {
                                                        e.stopPropagation();
                                                        if (isCurrent) {
                                                            isAgentActive
                                                                ? demoCall.stopCall()
                                                                : demoCall.toggleCall(demoCall.activeAgent!);
                                                        } else {
                                                            if (isActive) {
                                                                setAgentToSwitch(agent._original);
                                                                setShowSwitchDialog(true);
                                                            } else {
                                                                demoCall.toggleCall({
                                                                    data: agent._original,
                                                                });
                                                            }
                                                        }
                                                    }}
                                                    disabled={isAgentLoadingCall}
                                                    className={clsx(
                                                        'w-9 h-9 sm:w-10 sm:h-10 rounded-full flex items-center justify-center transition-colors shrink-0',
                                                        isAgentActive
                                                            ? 'bg-red-600 hover:bg-red-700'
                                                            : 'bg-green-600 hover:bg-green-700',
                                                        isAgentLoadingCall && 'opacity-50 cursor-not-allowed'
                                                    )}
                                                >
                                                    {isAgentLoadingCall ? (
                                                        <Loader2 className="w-4 h-4 sm:w-5 sm:h-5 text-white animate-spin" />
                                                    ) : (
                                                        <Phone
                                                            className={clsx(
                                                                'w-4 h-4 sm:w-5 sm:h-5 text-white',
                                                                isAgentActive && 'rotate-[135deg]'
                                                            )}
                                                        />
                                                    )}
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                <div className="hidden sm:grid sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
                    {agents.map((agent: any) => {
                        const isCurrent = agent.id === activeId;
                        const status = isCurrent ? demoCall.callStatus : CallStatus.INACTIVE;
                        const isAgentActive = status === CallStatus.ACTIVE;
                        const isAgentLoadingCall = status === CallStatus.LOADING;

                        return (
                            <div
                                key={agent.id}
                                className={clsx(
                                    'bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-md transition-shadow cursor-pointer flex flex-col',
                                    isCurrent && 'ring-2 ring-blue-500'
                                )}
                                onClick={() => {
                                    if (!isCurrent) {
                                        if (isActive) {
                                            setAgentToSwitch(agent._original);
                                            setShowSwitchDialog(true);
                                        } else {
                                            demoCall.setActiveAgent({
                                                data: agent._original,
                                            } as any);
                                        }
                                    }
                                }}
                            >
                                <div className="p-4 sm:p-5 pb-3">
                                    <h3 className="text-base sm:text-lg font-bold text-black mb-2">{agent.name}</h3>
                                    <p className="text-xs sm:text-sm text-gray-600 line-clamp-2">
                                        {agent.description || agent.role}
                                    </p>
                                </div>

                                <div
                                    className="relative h-[25rem] flex-shrink-0 overflow-hidden mt-auto"
                                    style={{
                                        backgroundImage: 'url(/images/Arabic-bg.png)',
                                        backgroundSize: 'cover',
                                        backgroundPosition: 'center',
                                        backgroundRepeat: 'no-repeat',
                                    }}
                                >
                                    {agent.avatar_url ? (
                                        <Image
                                            src={agent.avatar_url}
                                            alt={agent.name}
                                            fill
                                            className="object-cover object-bottom"
                                        />
                                    ) : (
                                        <div className="w-full h-full flex items-end justify-center pb-4 text-5xl sm:text-6xl text-gray-300">
                                            {agent.name[0]}
                                        </div>
                                    )}

                                    <div className="absolute bottom-0 left-0 right-0 p-3 sm:p-4 bg-gradient-to-t from-black/20 via-black/5 to-transparent">
                                        <div
                                            className={clsx(
                                                'w-full rounded-2xl sm:rounded-3xl h-12 sm:h-14 bg-gray-800/30 hover:bg-gray-800/40 backdrop-blur-md flex items-center justify-between px-4 sm:px-5 transition-colors shadow-lg border border-white/10',
                                                isAgentActive && 'bg-gray-900/30 hover:bg-gray-900/40'
                                            )}
                                        >
                                            <div className="flex items-center gap-3 flex-1 min-w-0">
                                                <div className="w-2.5 h-2.5 sm:w-3 sm:h-3 rounded-full bg-green-500 shrink-0" />
                                                <span className="text-white text-sm sm:text-base font-medium truncate">
                                                    {agent.name}
                                                </span>
                                            </div>

                                            <button
                                                onClick={e => {
                                                    e.stopPropagation();
                                                    if (isCurrent) {
                                                        isAgentActive
                                                            ? demoCall.stopCall()
                                                            : demoCall.toggleCall(demoCall.activeAgent!);
                                                    } else {
                                                        if (isActive) {
                                                            setAgentToSwitch(agent._original);
                                                            setShowSwitchDialog(true);
                                                        } else {
                                                            demoCall.toggleCall({
                                                                data: agent._original,
                                                            });
                                                        }
                                                    }
                                                }}
                                                disabled={isAgentLoadingCall}
                                                className={clsx(
                                                    'w-9 h-9 sm:w-10 sm:h-10 rounded-full flex items-center justify-center transition-colors shrink-0',
                                                    isAgentActive
                                                        ? 'bg-red-600 hover:bg-red-700'
                                                        : 'bg-green-600 hover:bg-green-700',
                                                    isAgentLoadingCall && 'opacity-50 cursor-not-allowed'
                                                )}
                                            >
                                                {isAgentLoadingCall ? (
                                                    <Loader2 className="w-4 h-4 sm:w-5 sm:h-5 text-white animate-spin" />
                                                ) : (
                                                    <Phone
                                                        className={clsx(
                                                            'w-4 h-4 sm:w-5 sm:h-5 text-white',
                                                            isAgentActive && 'rotate-[135deg]'
                                                        )}
                                                    />
                                                )}
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        );
                    })}
                </div>

                {demoCall.callStatus === CallStatus.ACTIVE && demoCall.roomData && (
                    <div className="hidden">
                        <LiveKitRoom
                            key={`${demoCall.callKey}-${demoCall.roomData.token}`}
                            token={demoCall.roomData.token}
                            serverUrl={demoCall.roomData.url}
                            audio
                            connect
                            onDisconnected={demoCall.stopCall}
                        >
                            <VoiceRoom roomRef={roomRef} />
                            <RoomAudioRenderer />
                        </LiveKitRoom>
                    </div>
                )}

                <Dialog
                    open={showSwitchDialog}
                    onOpenChange={open => {
                        setShowSwitchDialog(open);
                        if (!open) {
                            setAgentToSwitch(null);
                        }
                    }}
                >
                    <DialogContent
                        className="sm:max-w-md bg-gradient-to-br from-gray-50 via-white to-gray-50 border-0 shadow-2xl rounded-2xl"
                        showClose={false}
                    >
                        <div className="flex flex-col items-center space-y-5 sm:space-y-6 px-4 py-5 sm:px-6 sm:py-8">
                            <div className="relative">
                                <div className="absolute inset-0 rounded-full bg-gradient-to-r from-orange-400 via-pink-500 to-blue-500 p-[3px]">
                                    <div className="w-full h-full rounded-full bg-transparent"></div>
                                </div>
                                <div className="relative w-20 h-20 sm:w-24 sm:h-24 rounded-full overflow-hidden border-[3px] border-white shadow-lg">
                                    {activeAvatar?.path ? (
                                        <Image
                                            src={activeAvatar.path}
                                            alt={activeAgent?.name || 'Agent'}
                                            width={96}
                                            height={96}
                                            className="w-full h-full object-cover"
                                        />
                                    ) : (
                                        <div className="w-full h-full bg-gradient-to-br from-blue-600 to-purple-600 flex items-center justify-center text-2xl sm:text-3xl text-white font-bold">
                                            {activeAgent?.name?.[0] || 'A'}
                                        </div>
                                    )}
                                </div>
                            </div>

                            <div className="text-center space-y-2 sm:space-y-3">
                                <h3 className="text-lg sm:text-xl font-bold text-gray-900 leading-tight px-2">
                                    Do you want to end the call with{' '}
                                    <span className="text-orange-600">{activeAgent?.name}</span>?
                                </h3>
                                <p className="text-sm sm:text-base text-gray-600 leading-relaxed max-w-sm mx-auto px-2">
                                    You will be disconnected from the current call and connected to{' '}
                                    <span className="font-bold text-gray-900">{agentToSwitch?.agent?.name}</span>.
                                </p>
                            </div>

                            <div className="flex flex-col sm:flex-row gap-3 w-full sm:w-auto sm:min-w-[280px] pt-1">
                                <Button
                                    variant="outline"
                                    onClick={() => {
                                        setShowSwitchDialog(false);
                                        setAgentToSwitch(null);
                                    }}
                                    className="w-full sm:w-auto border-2 border-gray-300 bg-white text-gray-700 hover:bg-gray-50 hover:border-gray-400 font-medium py-5 sm:py-2 h-auto rounded-lg"
                                >
                                    Maybe later
                                </Button>
                                <Button
                                    variant="default"
                                    onClick={() => {
                                        demoCall.stopCall();
                                        demoCall.setActiveAgent({
                                            data: agentToSwitch,
                                        } as any);
                                        setTimeout(() => {
                                            demoCall.toggleCall({
                                                data: agentToSwitch,
                                            });
                                        }, 300);
                                        setShowSwitchDialog(false);
                                        setAgentToSwitch(null);
                                    }}
                                    className="w-full sm:w-auto bg-red-600 hover:bg-red-700 text-white font-medium py-5 sm:py-2 h-auto shadow-md hover:shadow-lg transition-all rounded-lg"
                                >
                                    Switch & Call
                                </Button>
                            </div>
                        </div>
                    </DialogContent>
                </Dialog>
            </div>
            <div className="">
                <div className="mt-6">
                    {!chatRoomData ? (
                        <Button onClick={handleChatConnect}>Connect Chat</Button>
                    ) : (
                        <div className="chat-container w-full h-96 border rounded-lg overflow-hidden">
                            <LiveKitRoom
                                serverUrl={chatRoomData.url}
                                token={chatRoomData.token}
                                connect={true}
                                data-lk-theme="default"
                            >
                                <Chat />
                            </LiveKitRoom>
                        </div>
                    )}
                </div>

            </div>
        </div>
    );
}
 chat is nto working