<script>
    import {page} from "$app/state";
    import {PUBLIC_API_URL} from "$env/static/public";
    import {onMount} from "svelte";

    import Sidebar from "./Sidebar.svelte";
    import Message from "./Message.svelte";

    let game = $state(page.data.data.game);
    let character = $state(page.data.data.character);
    let sessions = $state(page.data.data.sessions.sort((a, b) => a.started_at > b.started_at ? 1 : -1));
    let turns = $state(page.data.data.turns);
    let tokensRemaining = $state(page.data.data.tokens_remaining);
    let streaming = $state(false);

    let inputText = $state("");
    let sidebarOpen = $state(false);
    let messagesEl;

    const scrollToBottom = () => {
        if (messagesEl) messagesEl.scrollTop = messagesEl.scrollHeight;
    };

    $effect(() => {
        turns.length;
        if (turns.length > 0) turns[turns.length - 1].llm_text;
        scrollToBottom();
    });

    const autogrow = (node) => {
        const update = () => {
            node.style.height = "auto";
            node.style.height = Math.min(node.scrollHeight, 200) + "px";
        };
        node.addEventListener("input", update);
        return { destroy: () => node.removeEventListener("input", update) };
    };

    const handleSubmit = (e) => {
        e.preventDefault();
        const text = inputText.trim();
        if (!text || streaming) return;
        inputText = "";
        sendMessage(text);
    };

    const sendMessage = async (text)=>{
        let newTurn = {user_text: text};
        turns.push(newTurn);

        const response = await fetch(`${PUBLIC_API_URL}/game/${game.id}/session/${sessions[0].id}/turn`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Accept-Encoding": "identity"
            },
            credentials: "include",
            body: JSON.stringify({content: text})
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = "";

        while(true){
            const {done, value} = await reader.read();
            if(done) break;

            buffer += decoder.decode(value, {stream: true});
            const lines = buffer.split("\n");
            buffer = lines.pop();

            for(let i = 0; i < lines.length; i++){
                if(!lines[i].startsWith("data:")) continue;
                const data = lines[i].slice(5).trim();
                if(data === "[DONE]") continue;
                try{
                    const json = JSON.parse(data);
                    const chunk = json.choices?.[0]?.delta?.content;
                    if(chunk) turns[turns.length-1].llm_text += chunk;
                }catch{}
            }
        }

        streaming = false;
    }

    onMount(()=>{
        if(turns.length === 0){
            sendMessage("");
        }
    });
</script>

<div class="page">

{#if sidebarOpen}
    <div class="sidebar-overlay" onclick={() => sidebarOpen = false}></div>
{/if}

<Sidebar
    {game}
    {character}
    {tokensRemaining}
    open={sidebarOpen}
    onClose={() => sidebarOpen = false}
/>

<div class="main">
    <div class="mobile-bar">
        <button class="menu-btn" onclick={() => sidebarOpen = true} aria-label="Open menu">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
                <line x1="3" y1="6" x2="21" y2="6"/>
                <line x1="3" y1="12" x2="21" y2="12"/>
                <line x1="3" y1="18" x2="21" y2="18"/>
            </svg>
        </button>
        <span class="mobile-title">{game.title}</span>
    </div>

    <main class="messages" bind:this={messagesEl}>
        <div class="messages-inner">
            {#each turns as turn, i}
                {#if i !== 0}
                    <Message {turn} role="user" />
                {/if}
                <Message
                    {turn}
                    role="llm"
                    streaming={streaming && i === turns.length - 1}
                />
            {/each}

            {#if streaming}
                <div class="typing-indicator">
                    <span></span><span></span><span></span>
                </div>
            {/if}
        </div>
    </main>

    <div class="composer-wrap">
        <form class="composer" onsubmit={handleSubmit}>
            <textarea
                bind:value={inputText}
                use:autogrow
                placeholder="What do you do?"
                rows="1"
                disabled={streaming}
                onkeydown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSubmit(e); } }}
            ></textarea>
            <button type="submit" disabled={streaming || !inputText.trim()} aria-label="Send message">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round">
                    <path d="M12 19V5M5 12l7-7 7 7"/>
                </svg>
            </button>
        </form>
        <p class="composer-hint">Enter to send &nbsp;·&nbsp; Shift+Enter for new line</p>
    </div>
</div>

</div>

<style>
    .page {
        display: flex;
        height: 100vh;
        overflow: hidden;
        background: #0b0b10;
    }

    .sidebar-overlay {
        display: none;
    }

    .main {
        flex: 1;
        display: flex;
        flex-direction: column;
        height: 100vh;
        background: #0b0b10;
        overflow: hidden;
        min-width: 0;
    }

    /* ── Mobile bar ── */
    .mobile-bar {
        display: none;
        align-items: center;
        gap: 0.75rem;
        padding: 0.75rem 1rem;
        border-bottom: 1px solid #1a1a26;
        background: #0d0d16;
        flex-shrink: 0;
    }

    .menu-btn {
        background: none;
        border: none;
        color: #6b6b7a;
        cursor: pointer;
        padding: 4px;
        border-radius: 6px;
        display: flex;
        align-items: center;
        transition: color 0.15s;
    }

    .menu-btn:hover { color: #e5e5ea; }

    .mobile-title {
        font-size: 0.95rem;
        font-weight: 700;
        color: #e5e5ea;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }

    /* ── Messages ── */
    .messages {
        flex: 1;
        overflow-y: auto;
        scroll-behavior: smooth;
    }

    .messages::-webkit-scrollbar { width: 5px; }
    .messages::-webkit-scrollbar-track { background: transparent; }
    .messages::-webkit-scrollbar-thumb { background: #1e1e2e; border-radius: 3px; }

    .messages-inner {
        max-width: 800px;
        margin: 0 auto;
        padding: 2rem 2rem 1rem;
        display: flex;
        flex-direction: column;
        gap: 1rem;
    }

    /* ── Typing indicator ── */
    .typing-indicator {
        display: flex;
        align-items: center;
        gap: 5px;
        padding: 0.75rem 1rem;
        background: #1a1a28;
        border: 1px solid #2a2a3a;
        border-radius: 16px;
        border-bottom-left-radius: 4px;
        width: fit-content;
    }

    .typing-indicator span {
        width: 7px;
        height: 7px;
        border-radius: 50%;
        background: #44445a;
        animation: bounce 1.2s ease-in-out infinite;
    }

    .typing-indicator span:nth-child(2) { animation-delay: 0.2s; }
    .typing-indicator span:nth-child(3) { animation-delay: 0.4s; }

    @keyframes bounce {
        0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
        30% { transform: translateY(-5px); opacity: 1; }
    }

    /* ── Composer ── */
    .composer-wrap {
        flex-shrink: 0;
        border-top: 1px solid #1a1a26;
        background: #0d0d16;
        padding: 1rem 2rem 0.6rem;
    }

    .composer {
        max-width: 800px;
        margin: 0 auto;
        display: flex;
        align-items: flex-end;
        gap: 0.75rem;
        background: #13131e;
        border: 1px solid #2a2a3a;
        border-radius: 14px;
        padding: 0.6rem 0.6rem 0.6rem 1rem;
        transition: border-color 0.2s, box-shadow 0.2s;
    }

    .composer:focus-within {
        border-color: #5a5aff;
        box-shadow: 0 0 0 3px rgba(90, 90, 255, 0.1);
    }

    .composer textarea {
        flex: 1;
        background: none;
        border: none;
        outline: none;
        resize: none;
        font-size: 0.95rem;
        line-height: 1.6;
        color: #e5e5ea;
        font-family: inherit;
        min-height: 26px;
        max-height: 200px;
        overflow-y: auto;
        padding: 0;
    }

    .composer textarea::placeholder { color: #44445a; font-style: italic; }
    .composer textarea:disabled { opacity: 0.5; cursor: not-allowed; }

    .composer button {
        width: 36px;
        height: 36px;
        border-radius: 9px;
        border: none;
        background: #5a5aff;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        flex-shrink: 0;
        transition: background 0.15s, transform 0.1s, opacity 0.15s;
    }

    .composer button:hover:not(:disabled) { background: #4646e0; }
    .composer button:active:not(:disabled) { transform: scale(0.93); }
    .composer button:disabled { opacity: 0.35; cursor: not-allowed; }

    .composer-hint {
        max-width: 800px;
        margin: 0.4rem auto 0;
        font-size: 0.7rem;
        color: #2e2e44;
        text-align: right;
        padding: 0 0.25rem;
    }

    /* ── Mobile ── */
    @media (max-width: 768px) {
        .sidebar-overlay {
            display: block;
            position: fixed;
            inset: 0;
            background: rgba(0, 0, 0, 0.6);
            z-index: 199;
        }

        .mobile-bar { display: flex; }
        .messages-inner { padding: 1.25rem 1rem 0.75rem; }
        .composer-wrap { padding: 0.75rem 1rem 0.5rem; }
        .composer-hint { display: none; }
    }
</style>
