<script setup lang="ts">
import { computed } from 'vue';
import { route } from 'ziggy-js';
import { Info } from '@lucide/vue';

const props = defineProps<{
    message: {
        id: number;
        content: string;
        created_at: string;
        subject_id?: number | null;
        subject_type?: string | null;
        subject?: any;
    };
    participantsById: Record<
        number,
        {
            id: number;
            name: string;
            pivot?: { display_name: string | null } | null;
        }
    >;
    dynamicId: string;
}>();

function formatTimestamp(isoString: string): { full: string; time: string } {
    const date = new Date(isoString);
    return {
        full: date.toLocaleString(),
        time: date.toLocaleTimeString([], {
            hour: '2-digit',
            minute: '2-digit',
            hour12: false,
        }),
    };
}

const parsedContent = computed(() => {
    let content = props.message.content;

    // 1. Replace <user:id> placeholders with links to their dynamic profile
    const userRegex = /<user:([0-9a-f-]+)>/g;
    content = content.replace(userRegex, (match, userId) => {
        const user = props.participantsById[(userId)];
        if (user) {
            const url = route('dynamics.users.show', [props.dynamicId, (userId)]);
            return `<a href="${url}" class="c-chat__user-link font-semibold text-blue-500 hover:underline">${
                user.pivot?.display_name ?? user.name
            }</a>`;
        }
        return `User #${userId}`;
    });

    // 2. Link subjects if found in the text
    if (props.message.subject_id && props.message.subject_type) {
        if (
            props.message.subject_type === 'mutation' ||
            props.message.subject_type === 'ledger'
        ) {
            const ledgerId =
                props.message.subject_type === 'mutation'
                    ? props.message.subject?.ledger_id
                    : props.message.subject?.id;

            const ledgerName =
                props.message.subject_type === 'mutation'
                    ? props.message.subject?.ledger?.name
                    : props.message.subject?.name;

            if (ledgerId && ledgerName) {
                const ledgerUrl = route('dynamics.ledgers.show', [
                    props.dynamicId,
                    ledgerId,
                ]);

                const escapedName = ledgerName.replace(
                    /[-\/\\^$*+?.()|[\]{}]/g,
                    '\\$&',
                );

                const nameRegex = new RegExp(`"${escapedName}"`, 'g');
                content = content.replace(
                    nameRegex,
                    `"<a href="${ledgerUrl}" class="c-chat__subject-link font-semibold text-blue-500 hover:underline">${ledgerName}</a>"`,
                );
            }
        }
    }

    return content;
});
</script>

<template>
    <div class="c-chat__system-inner">
        <Info class="c-chat__system-icon" />
        <span
            class="c-chat__system-text"
            v-html="parsedContent"
        ></span>
        <span
            class="c-chat__system-time"
            :title="formatTimestamp(message.created_at).full"
        >
            {{ formatTimestamp(message.created_at).time }}
        </span>
    </div>
</template>
