<template>
    <div v-if="normalized && normalized.data.length" class="scm mt-6">
        <div v-if="showHeader" class="flex align-items-center mb-3">
            <i v-if="icon" :class="icon" class="text-primary-500 mr-2"></i>
            <h4 class="text-lg font-semibold text-surface-700 dark:text-surface-300 m-0">{{ title }}</h4>
        </div>

        <div class="overflow-x-auto border-round" style="border: 1px solid var(--surface-border)">
            <table class="scm__table w-full border-collapse">
                <thead>
                    <tr>
                        <th class="scm__th">Сегмент</th>
                        <th v-for="channel in normalized.channels" :key="channel" class="scm__th text-center">
                            {{ channel }}
                        </th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(row, idx) in normalized.data" :key="idx" class="scm__tr">
                        <td class="scm__td font-semibold">{{ getSegmentName(row) }}</td>
                        <td v-for="channel in normalized.channels" :key="channel" class="scm__td text-center">
                            <span class="scm__badge" :style="getCellStyle(row?.[channel])">
                                {{ formatCell(row?.[channel]) }}
                            </span>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup>
import { computed } from 'vue';

const props = defineProps({
    /**
     * Supported shapes:
     * - Array of rows: [{ segmentName: 'Молодежь', Instagram: 'High', TikTok: 'Low', ... }, ...]
     * - Object: { channels: string[], data: Array<row> } (this is what MarketingAnalysis builds)
     */
    matrix: { type: [Array, Object], default: null },
    title: { type: String, default: 'Матрица каналов по сегментам' },
    icon: { type: String, default: 'pi pi-th-large' },
    showHeader: { type: Boolean, default: true }
});

const normalizeMatrix = (input) => {
    if (!input) return null;

    const data = Array.isArray(input) ? input : Array.isArray(input.data) ? input.data : Array.isArray(input.matrix) ? input.matrix : [];
    if (!Array.isArray(data) || data.length === 0) return { channels: [], data: [] };

    const channels = new Set(Array.isArray(input.channels) ? input.channels : []);
    if (channels.size === 0) {
        data.forEach((row) => {
            if (!row || typeof row !== 'object') return;
            Object.keys(row).forEach((key) => {
                if (key !== 'segmentName' && key !== 'segment' && key !== 'name') channels.add(key);
            });
        });
    }

    return { channels: Array.from(channels), data };
};

const normalized = computed(() => normalizeMatrix(props.matrix));

const getSegmentName = (row) => {
    return row?.segmentName || row?.segment || row?.name || '-';
};

const normalizeLevel = (value) => {
    if (value == null || value === '') return null;
    const s = String(value).trim().toLowerCase();

    if (s === 'high' || s.includes('высок')) return 'high';
    if (s === 'medium' || s.includes('средн')) return 'medium';
    if (s === 'low' || s.includes('низк')) return 'low';
    return null;
};

const getCellStyle = (value) => {
    const level = normalizeLevel(value);

    // Spec colors:
    // - High: bright green
    // - Medium: yellow
    // - Low: light gray
    if (level === 'high') return { backgroundColor: '#22c55e', color: '#ffffff' };
    if (level === 'medium') return { backgroundColor: '#facc15', color: '#111827' };
    if (level === 'low') return { backgroundColor: '#e5e7eb', color: '#111827' };

    return { backgroundColor: 'rgba(156, 163, 175, 0.35)', color: '#111827' };
};

const formatCell = (value) => {
    if (value == null || value === '') return '-';
    return String(value);
};
</script>

<style scoped>
.scm__table {
    border: 1px solid var(--surface-border);
    border-radius: 0.5rem;
    overflow: hidden;
}

.scm__th {
    padding: 0.75rem 1rem;
    text-align: left;
    font-weight: 600;
    color: var(--text-color);
    background-color: var(--surface-100);
    border-bottom: 2px solid var(--surface-border);
    white-space: nowrap;
}

.scm__td {
    padding: 0.75rem 1rem;
    border-bottom: 1px solid var(--surface-border);
    color: var(--text-color);
}

.scm__tr:last-child .scm__td {
    border-bottom: none;
}

.scm__tr:hover {
    background-color: var(--surface-50);
}

.scm__badge {
    display: inline-block;
    padding: 0.375rem 0.75rem;
    border-radius: 0.375rem;
    font-weight: 700;
    font-size: 0.875rem;
    min-width: 70px;
    text-align: center;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08);
}
</style>
