<script setup>
/*
 * MelissaConversasCard — card de thread no kanban Melissa.
 * --------------------------------------------------------
 * Renderiza uma conversa dentro de uma coluna do kanban (Urgente /
 * Aguardando resposta / Aguardando paciente / Resolvido). Mostra:
 *   - Head: icone do canal + nome (paciente ou numero) + badge de
 *     unread count (vermelho)
 *   - Msg: preview da ultima mensagem (truncada, com seta se outbound)
 *   - Tags: chips coloridas (cor + icone vem do registro de tag)
 *   - Foot: relative time + badge de assignee ("Eu" ou nome curto) ou
 *     "nao vinculado" quando nao ha paciente
 *
 * Componente puramente visual — pai decide o que fazer no @click
 * (tipicamente drawerStore.openForThread).
 *
 * Props:
 *   - thread: { thread_key, channel, patient_name, contact_number,
 *               unread_count, last_message_body, last_message_direction,
 *               last_message_at, assigned_to, patient_id, ... }
 *   - tags: Array<{ id, name, color, icon? }> — tags ja resolvidas
 *           pelo pai (via tagsForThread). [] se nao ha tags.
 *   - currentUserId: string|null — pra determinar "Eu" vs nome
 *   - memberNameMap: Record<userId, fullName> — pra labels de outros
 *     assignees (rotulo "Marina S.")
 *
 * Emit:
 *   - click — pai chama drawerStore.openForThread
 */

import { channelIcon } from '@/utils/channelMeta';

const props = defineProps({
    thread: { type: Object, required: true },
    tags: { type: Array, default: () => [] },
    currentUserId: { type: String, default: null },
    memberNameMap: { type: Object, default: () => ({}) }
});
defineEmits(['click']);
function truncate(s, n = 80) {
    if (!s) return '';
    const str = String(s).replace(/\s+/g, ' ').trim();
    return str.length > n ? str.slice(0, n - 1) + '…' : str;
}
function contactLabel(thread) {
    return thread.patient_name || thread.contact_number || 'Desconhecido';
}
function fmtRelative(iso) {
    if (!iso) return '';
    const d = new Date(iso);
    const now = new Date();
    const diff = Math.floor((now - d) / 1000);
    if (diff < 60) return 'agora';
    if (diff < 3600) return `${Math.floor(diff / 60)}m`;
    if (diff < 86400) return `${Math.floor(diff / 3600)}h`;
    if (diff < 604800) return `${Math.floor(diff / 86400)}d`;
    return d.toLocaleDateString('pt-BR');
}
function assigneeLabel(userId) {
    if (!userId) return '';
    const full = props.memberNameMap[userId];
    if (!full) return 'Atribuída';
    const parts = full.trim().split(/\s+/);
    if (parts.length === 1) return parts[0].slice(0, 14);
    return `${parts[0]} ${parts[parts.length - 1][0]}.`;
}
</script>

<template>
    <button
        class="mw-card flex flex-col gap-1.5 px-3 py-2.5 bg-[var(--m-bg-soft)] border border-[var(--m-border)] rounded-[10px] cursor-pointer text-left [font-family:inherit] text-[var(--m-text)] transition-[background-color,border-color,transform] duration-[140ms] hover:bg-[var(--m-bg-soft-hover)] hover:border-[color-mix(in_srgb,var(--m-accent)_40%,var(--m-border))] hover:-translate-y-px"
        :aria-label="`Abrir conversa de ${contactLabel(thread)}`"
        @click="$emit('click')"
    >
        <div class="mw-card__head flex items-center gap-1.5">
            <i :class="['pi', channelIcon(thread.channel), 'mw-card__channel', 'text-[var(--m-text-muted)]', 'text-[0.7rem]']" />
            <span class="mw-card__name flex-1 min-w-0 text-[0.82rem] font-semibold overflow-hidden text-ellipsis whitespace-nowrap">{{ contactLabel(thread) }}</span>
            <span
                v-if="thread.unread_count > 0"
                class="mw-card__unread text-[0.62rem] font-bold text-white bg-[rgb(248,113,113)] px-1.5 py-px rounded-full min-w-[18px] text-center"
                :aria-label="`${thread.unread_count} mensagens não lidas`"
            >{{ thread.unread_count }}</span>
        </div>
        <div class="mw-card__msg text-[0.74rem] text-[var(--m-text-muted)] overflow-hidden text-ellipsis whitespace-nowrap">
            <i v-if="thread.last_message_direction === 'outbound'" class="pi pi-arrow-right text-[0.55rem] mr-1 opacity-60" aria-hidden="true" />
            {{ truncate(thread.last_message_body, 70) }}
        </div>
        <div v-if="tags.length" class="mw-card__tags flex items-center gap-1 flex-wrap">
            <span
                v-for="tag in tags"
                :key="tag.id"
                class="mw-card__tag inline-flex items-center gap-[3px] text-[0.6rem] font-semibold px-[7px] py-px rounded-full border leading-[1.4] [&>i]:text-[0.55rem]"
                :style="{ background: tag.color + '20', color: tag.color, borderColor: tag.color + '40' }"
            >
                <i v-if="tag.icon" :class="tag.icon" aria-hidden="true" />
                {{ tag.name }}
            </span>
        </div>
        <div class="mw-card__foot flex items-center justify-between gap-1.5 text-[0.65rem] text-[var(--m-text-faint)]">
            <span class="mw-card__time font-medium">{{ fmtRelative(thread.last_message_at) }}</span>
            <span
                v-if="thread.assigned_to"
                class="mw-card__assignee inline-flex items-center gap-[3px] px-1.5 py-px rounded-full border border-[var(--m-border)] bg-[var(--m-bg-soft)] text-[var(--m-text)] text-[0.6rem] font-semibold [&>i]:text-[0.55rem]"
                :class="{ 'is-mine': thread.assigned_to === currentUserId }"
                v-tooltip.top="thread.assigned_to === currentUserId ? 'Atribuída a mim' : 'Atribuída a ' + (memberNameMap[thread.assigned_to] || '')"
            >
                <i class="pi pi-user" aria-hidden="true" />
                {{ thread.assigned_to === currentUserId ? 'Eu' : assigneeLabel(thread.assigned_to) }}
            </span>
            <span v-else-if="!thread.patient_name" class="mw-card__unlinked italic">não vinculado</span>
        </div>
    </button>
</template>

<style scoped>
/* State modifier do assignee — usa vars accent (Melissa theme).
   Aceita Tailwind utility tambem mas a override de border-color via
   color-mix fica mais limpa em CSS. */
.mw-card__assignee.is-mine {
    background: var(--m-accent-soft);
    border-color: color-mix(in srgb, var(--m-accent) 35%, var(--m-border));
    color: var(--m-accent);
}
</style>
