<script>
    import { CornerUpLeftIcon, MoreVerticalIcon } from "svelte-feather-icons";
    import { overlayStore, setMessageInputEvent, userInfoStore } from "../stores";

    export let message;

    const reply = () => {
        let replyString = "";
        const messageLines = message.content.split("\n");

        messageLines.forEach(line => {
            replyString += `> ${line}\n`;
        });

        replyString += `@${message.author_username} `;

        setMessageInputEvent.update(replyString);
    };
</script>

<style>
    .message {
        display: flex;
        align-items: flex-start;
        overflow-x: hidden;
        word-break: break-all;
        padding: var(--space-xxs) var(--space-normplus) var(--space-xxs) var(--space-normplus);
    }

    .message.pinged {
        background-color: var(--blue-alpha-2);
    }

    .message .edit-message {
        visibility: hidden;
    }

    .message:hover {
        background-color: var(--background-color-2);
    }

    .message:hover .edit-message {
        visibility: visible;
    }

    .message-content {
        color: var(--foreground-color-2);
        white-space: pre-wrap;
    }

    .pending {
        color: var(--foreground-color-3);
    }

    .author {
        flex-shrink: 0;
        font-weight: bold;
        margin-right: var(--space-xs);
    }

    .edit-message {
        flex-shrink: 0;
        float: right;
    }
</style>

<div class="message" class:pinged={ userInfoStore.value && message.content.includes(`@${userInfoStore.value.username}`) }>
    <span class="author">{ message.author_username }</span>
    <span class="message-content" class:pending={ message._isPending }>{ message.content }</span>
    <button class="icon-button icon-button-auto edit-message" on:click="{ reply }" aria-label="Reply to Message">
        <CornerUpLeftIcon />
    </button>
    {#if userInfoStore.value && (message.author_id === userInfoStore.value.id || userInfoStore.value.is_superuser)}
        <button class="icon-button edit-message" on:click="{ () => overlayStore.open('editMessage', { message }) }" aria-label="Edit Message">
            <MoreVerticalIcon />
        </button>
    {/if}
</div>
