<script lang="ts">
    import { onMount, onDestroy, tick } from 'svelte';
    import { writable, derived } from 'svelte/store';

    interface User {
        id: string;
        name: string;
        avatar: string;
        lastMessage: string;
        unread: number;
        online: boolean;
    }

    interface Message {
        id: string;
        text: string;
        senderId: string;
        timestamp: string;
    }

    const isMobile = writable(false);
    let selectedUserId: string | null = null;
    $: showUserList = derived([isMobile], ([$isMobile]) => !$isMobile || !selectedUserId);

    const users: User[] = [
        { id: '1', name: 'John Doe', avatar: 'https://i.pravatar.cc/40?img=1', lastMessage: 'Hey, how are you?', unread: 2, online: true },
        { id: '2', name: 'Jane Smith', avatar: 'https://i.pravatar.cc/40?img=2', lastMessage: 'See you tomorrow!', unread: 0, online: false },
    ];

    function checkMobile() {
        isMobile.set(window.innerWidth < 768);
    }

    function selectUser(userId: string) {
        selectedUserId = userId;
    }

    function goBack() {
        selectedUserId = null;
    }

    onMount(() => {
        checkMobile();
        window.addEventListener('resize', checkMobile);
        return () => window.removeEventListener('resize', checkMobile);
    });

    let newMessage = '';
    let messageContainer: HTMLDivElement;

    let messages: Message[] = [];
    $: messages = getMessages(selectedUserId);

    function getMessages(userId: string | null): Message[] {
        if (!userId) return [];
        return userId === '1'
            ? [
                  { id: '1', text: 'Hey, how are you?', senderId: '1', timestamp: '10:30 AM' },
                  { id: '2', text: "I'm good, thanks!", senderId: 'me', timestamp: '10:31 AM' },
              ]
            : [
                  { id: '3', text: 'Ready for tomorrow?', senderId: '2', timestamp: '2:45 PM' },
                  { id: '4', text: 'Yes, see you then!', senderId: 'me', timestamp: '2:46 PM' },
              ];
    }

    async function sendMessage() {
        if (newMessage.trim()) {
            messages = [
                ...messages,
                {
                    id: Date.now().toString(),
                    text: newMessage,
                    senderId: 'me',
                    timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }),
                },
            ];
            newMessage = '';
            await tick();
            messageContainer.scrollTo({ top: messageContainer.scrollHeight, behavior: 'smooth' });
        }
    }
</script>

<style>
    /* Smooth transition for mobile menu */
    .menu-transition {
        transition: transform 0.3s ease-in-out;
    }

    /* Increase button touch areas */
    button {
        min-height: 44px;
    }

    /* Handle text overflow */
    .truncate {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
</style>

<!-- Main Layout -->
<div class="flex flex-col md:flex-row h-full ">
    <!-- Mobile Header -->
    <div class="md:hidden navbar bg-base-100 border-b border-base-300 px-4">
        <div class="flex items-center w-full">
            {#if selectedUserId}
                <button on:click={goBack} class="btn btn-ghost btn-circle" aria-label="Back to conversations">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                    </svg>
                </button>
                <div class="flex items-center flex-wrap gap-2">
                    <div class="w-10 rounded-full relative">
                        <img class=" rounded-lg" src={users.find(u => u.id === selectedUserId)?.avatar} alt={users.find(u => u.id === selectedUserId)?.name} />
                        {#if users.find(u => u.id === selectedUserId)?.online}
                            <div class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-base-100 z-10"></div>
                        {/if}
                    </div>
                    <h1 class="max-h-fit text-lg font-semibold truncate flex-1 text-center max-w-fit">
                        {users.find(u => u.id === selectedUserId)?.name}
                    </h1>
                </div>
            {:else}
                <h1 class="text-lg font-semibold flex-1 text-center">Messages</h1>
            {/if}
        </div>
    </div>

    <!-- User List -->
    <div class={`w-full md:w-80 bg-base-100 border-t border-r rounded-tr-lg border-base-300 fixed md:relative h-full menu-transition ${$showUserList ? 'translate-x-0' : '-translate-x-full'}`}>
        <div class="hidden md:block p-4 bg-neutral-50">
            <h1 class="text-xl font-bold">Direct Messages</h1>
        </div>
        <div class="menu p-2 overflow-y-auto h-[calc(100vh-4rem)]">
            {#each users as user (user.id)}
                <button
                    class="flex items-center gap-3 p-3 hover:bg-base-200 rounded-lg {selectedUserId === user.id ? 'bg-base-200' : ''}"
                    on:click={() => selectUser(user.id)}
                >
                    <div class="avatar online">
                        <div class="w-10 rounded-full relative">
                            <img src={user.avatar} alt={user.name} />
                            {#if user.online}
                                <div class="absolute bottom-0 right-0 w-3 h-3 bg-green-500 rounded-full border-2 border-base-100 z-10"></div>
                            {/if}
                        </div>
                    </div>
                    <div class="flex-1 text-left min-w-0">
                        <div class="font-semibold truncate">{user.name}</div>
                        <div class="text-sm text-gray-500 truncate">{user.lastMessage}</div>
                    </div>
                    {#if user.unread > 0}
                        <div class="badge badge-primary">{user.unread}</div>
                    {/if}
                </button>
            {/each}
        </div>
    </div>

    <!-- Conversation Area -->
    <div class="flex-1 h-[calc(100vh-4rem)]">
        {#if selectedUserId}
            <div class="h-full flex flex-col">
                <div class="flex-1 p-4 space-y-4 overflow-y-auto" bind:this={messageContainer}>
                    {#each messages as message (message.id)}
                        <div class="flex {message.senderId === 'me' ? 'justify-end' : 'justify-start'}">
                            <div class="max-w-[90%] px-3 py-2 rounded-lg {message.senderId === 'me' ? 'bg-primary text-primary-content' : 'bg-base-300'}">
                                <div class="break-words">{message.text}</div>
                                <div class="text-[0.7rem] mt-1 opacity-50">{message.timestamp}</div>
                            </div>
                        </div>
                    {/each}
                </div>
                <div class="p-4 border-t border-base-300 bg-base-100">
                    <div class="flex gap-2">
                        <input
                            type="text"
                            bind:value={newMessage}
                            placeholder="Type a message..."
                            class="flex-1 input input-bordered input-sm"
                            on:keydown={(e) => e.key === 'Enter' && sendMessage()}
                        />
                        <button on:click={sendMessage} class="btn btn-primary btn-circle">
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                            </svg>
                        </button>
                    </div>
                </div>
            </div>
        {:else}
            <div class="hidden md:flex items-center justify-center h-full">
                <div class="text-center text-gray-500">
                    <div class="text-2xl">Select a conversation</div>
                    <div class="text-sm">Start chatting with your friends</div>
                </div>
            </div>
        {/if}
    </div>
</div>
