<script>
    import { CornerUpLeftIcon, MoreVerticalIcon } from "svelte-feather-icons";
    import { overlayStore, OverlayType, 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;
        align-items: center;
        overflow-x: hidden;
        word-break: break-all;
        padding: var(--space-xs) var(--space-xs) var(--space-xs) var(--space-normplus);
    }

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

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

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

    .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;
    }

    .date {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        background-color: var(--background-color-2);
        padding-top: 1px;
        padding-bottom: 1px;
        padding-left: 0.375rem;
        padding-right: 0.375rem;
        border-radius: 9999px;
        font-size: small;
        visibility: hidden;
        margin-left: auto;
    }

    .message.clumped .author {
        visibility: hidden;
    }

    .message:hover .date,
    .message.clumped:hover .author {
        visibility: visible;
    }

    @media (max-width: 768px) {
        .message {
            padding: var(--space-xxs) var(--space-xxs) var(--space-xxs) var(--space-normplus);
        }
    }

    .message.clumped {
        padding: 2px 2px 2px var(--space-normplus);
    }
</style>

<div class="message" class:clumped={ message._clumped } class:pinged={ message._mentions }>
    <span class="author">{ message.author_username }</span>
    <span class="message-content" class:pending={ message._isPending }>{ message.content }</span>

    <span class="date">{ message._createdAtTimeString }</span>
    <button class="icon-button edit-message" on:click="{ reply }" aria-label="Reply to Message">
        <CornerUpLeftIcon />
    </button>
    {#if message._editable}
        <button class="icon-button edit-message" on:click="{ () => overlayStore.push(OverlayType.EditMessage, { message }) }" aria-label="Edit Message">
            <MoreVerticalIcon />
        </button>
    {/if}
</div>
