<script setup lang="ts">
/**
 * Таблица реестра лидов «Сделки» (редизайн 2026-05-17).
 * Колонки: чекбокс · Телефон · Источник · Город · Статус ·
 * Комментарий · Поставлен. Комментарий — read-only.
 */
import type { MockDeal } from '../../composables/mockDeals';
import type { LeadStatus } from '../../composables/leadStatuses';
import { stripChannelPrefix } from '../../composables/projectName';
import StatusPill from '../ui/StatusPill.vue';

const props = withDefaults(
    defineProps<{
        deals: MockDeal[];
        selectedIds: number[];
        statusBySlug: Map<string, LeadStatus>;
        activeDealId?: number | null;
    }>(),
    { activeDealId: null },
);

const emit = defineEmits<{
    'update:selectedIds': [value: number[]];
    'row-click': [deal: MockDeal];
}>();

const SIGNAL_LABELS: Record<string, string> = { call: 'Звонки', site: 'Сайт', sms: 'СМС' };

function signalLabel(t: MockDeal['signalType']): string {
    return t ? (SIGNAL_LABELS[t] ?? '') : '';
}

function formatDateTime(iso: string | null | undefined): string {
    if (!iso) return '—';
    const d = new Date(iso);
    return new Intl.DateTimeFormat('ru-RU', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    }).format(d);
}

function rowProps(deal: MockDeal): Record<string, unknown> {
    return { class: deal.id === props.activeDealId ? 'deals-row-active' : '' };
}
</script>

<template>
    <v-card variant="outlined" class="deals-table-card">
        <v-data-table
            :model-value="selectedIds"
            :items="deals"
            :headers="[
                { title: 'Телефон', key: 'phone', sortable: true },
                { title: 'Источник', key: 'project', sortable: false },
                { title: 'Город', key: 'city', sortable: false },
                { title: 'Статус', key: 'statusSlug', sortable: false },
                { title: 'Комментарий', key: 'comment', sortable: false },
                { title: 'Поставлен', key: 'receivedAt', align: 'end', sortable: true },
            ]"
            show-select
            item-value="id"
            items-per-page="-1"
            hide-default-footer
            hover
            :row-props="(p: { item: MockDeal }) => rowProps(p.item)"
            @update:model-value="(v: number[]) => emit('update:selectedIds', v)"
            @click:row="(_e: Event, { item }: { item: MockDeal }) => emit('row-click', item)"
        >
            <template #[`item.phone`]="{ item }: { item: MockDeal }">
                <span class="num ld-mono">{{ item.phone }}</span>
            </template>

            <template #[`item.project`]="{ item }: { item: MockDeal }">
                <div class="cell-source">
                    <span class="source-project">{{ stripChannelPrefix(item.project) }}</span>
                    <span v-if="signalLabel(item.signalType)" class="source-signal">{{
                        signalLabel(item.signalType)
                    }}</span>
                </div>
            </template>

            <template #[`item.city`]="{ item }: { item: MockDeal }">
                <span :class="{ 'text-medium-emphasis': !item.city }">{{ item.city || '—' }}</span>
            </template>

            <template #[`item.statusSlug`]="{ item }: { item: MockDeal }">
                <StatusPill
                    :slug="item.statusSlug"
                    :label="statusBySlug.get(item.statusSlug)?.nameRu ?? item.statusSlug"
                />
            </template>

            <template #[`item.comment`]="{ item }: { item: MockDeal }">
                <span class="cell-comment" :class="{ 'text-medium-emphasis': !item.comment }">{{
                    item.comment || '—'
                }}</span>
            </template>

            <template #[`item.receivedAt`]="{ item }: { item: MockDeal }">
                <span class="num ld-mono-s">{{ formatDateTime(item.receivedAt) }}</span>
            </template>

            <template #[`header.data-table-select`]="{ allSelected, selectAll, someSelected }">
                <v-checkbox-btn
                    :model-value="allSelected"
                    :indeterminate="someSelected && !allSelected"
                    aria-label="Выбрать все сделки"
                    @update:model-value="selectAll"
                />
            </template>

            <template #[`item.data-table-select`]="{ isSelected, toggleSelect, internalItem, item }">
                <v-checkbox-btn
                    :model-value="isSelected(internalItem)"
                    :aria-label="`Выбрать сделку «${(item as MockDeal).phone}»`"
                    @update:model-value="() => toggleSelect(internalItem)"
                />
            </template>
        </v-data-table>

        <div v-if="deals.length === 0" class="empty-state pa-8 text-center text-medium-emphasis">
            Нет сделок по выбранным фильтрам
        </div>
    </v-card>
</template>

<style scoped>
.deals-table-card {
    background: #fff;
}
.num {
    font-family: 'JetBrains Mono', ui-monospace, monospace;
    font-feature-settings: 'tnum';
}
.cell-source {
    display: flex;
    flex-direction: column;
    line-height: 1.3;
}
.source-project {
    font-weight: 500;
    color: #081319;
}
.source-signal {
    font-size: 11px;
    color: #6b6356;
}
.cell-comment {
    display: inline-block;
    max-width: 240px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: bottom;
}
:deep(.deals-row-active) {
    background: rgba(15, 110, 86, 0.07);
}
</style>
