/**
 * Discord embed builders for PES League match results.
 */

import { EmbedBuilder } from 'discord.js';

const COLORS = {
    win:     0x16a34a,
    draw:    0x64748b,
    info:    0x1d4ed8,
    error:   0xef4444,
    purple:  0x7c3aed,
};

function eloArrow(change) {
    if (change > 0) return `▲ +${change}`;
    if (change < 0) return `▼ ${change}`;
    return `◆ 0`;
}

// ─────────────────────────────────────────────────────────────────────────────
// Ranked match result
// ─────────────────────────────────────────────────────────────────────────────
export function matchResultEmbed(data) {
    const { score_host, score_guest, winner, elo, match_id } = data;
    const isDraw = score_host === score_guest;

    const embed = new EmbedBuilder()
        .setColor(isDraw ? COLORS.draw : COLORS.win)
        .setTitle('⚽  Hasil Pertandingan Ranked')
        .setTimestamp()
        .setFooter({ text: `Match ID #${match_id}` });

    embed.setDescription(
        winner ? `🏆 **${winner}** menang!` : '🤝 Seri!'
    );

    embed.addFields(
        {
            name:   '🟦 Host',
            value:  `Skor: **${score_host}**\nELO: ${eloArrow(elo?.host?.change ?? 0)} → **${elo?.host?.new ?? '?'}**`,
            inline: true,
        },
        { name: '\u200b', value: 'vs', inline: true },
        {
            name:   '🟥 Guest',
            value:  `Skor: **${score_guest}**\nELO: ${eloArrow(elo?.guest?.change ?? 0)} → **${elo?.guest?.new ?? '?'}**`,
            inline: true,
        },
    );

    return embed;
}

// ─────────────────────────────────────────────────────────────────────────────
// Tournament match result
// ─────────────────────────────────────────────────────────────────────────────
export function tournamentResultEmbed(data) {
    const { score1, score2, winner, player1, player2, tournament, round, phase, is_draw, is_golden_goal, match_id } = data;

    let phaseLabel;
    if (phase === 'group')       phaseLabel = `Fase Grup${data.group ? ` — Grup ${data.group}` : ''}`;
    else if (phase === 'tiebreaker') phaseLabel = '⭐ Tiebreaker Golden Goal';
    else                         phaseLabel = `Knockout — Babak ${round}`;

    const embed = new EmbedBuilder()
        .setColor(is_draw ? COLORS.draw : COLORS.win)
        .setTitle(`🏆  ${tournament}`)
        .setDescription(
            [
                `**${phaseLabel}**`,
                is_golden_goal ? '⚡ Golden Goal!' : null,
                winner ? `\n🥇 **${winner}** menang!` : (is_draw ? '\n🤝 Seri!' : null),
            ].filter(Boolean).join('\n')
        )
        .setTimestamp()
        .setFooter({ text: `Tournament Match ID #${match_id}` });

    embed.addFields(
        { name: `👤 ${player1}`, value: `Skor: **${score1}**`, inline: true },
        { name: '\u200b',        value: 'vs',                  inline: true },
        { name: `👤 ${player2}`, value: `Skor: **${score2}**`, inline: true },
    );

    return embed;
}

// ─────────────────────────────────────────────────────────────────────────────
// Pending match list (ranked or tournament)
// ─────────────────────────────────────────────────────────────────────────────
export function pendingMatchesEmbed(matches, title = 'Pertandingan Aktif') {
    const embed = new EmbedBuilder()
        .setColor(COLORS.info)
        .setTitle(`📋  ${title}`)
        .setTimestamp();

    if (!matches.length) {
        embed.setDescription('Tidak ada pertandingan aktif saat ini.');
        return embed;
    }

    const lines = matches.map((m, i) => {
        // Support both ranked (host/guest) and tournament (player1/player2) shapes
        const p1 = m.player1?.username ?? m.host?.username  ?? '?';
        const p2 = m.player2?.username ?? m.guest?.username ?? '?';

        // Extra info for tournament matches
        const extra = [];
        if (m.phase)       extra.push(m.phase === 'group' ? `Grup ${m.group ?? '?'}` : m.phase);
        if (m.is_golden_goal) extra.push('⚡GG');
        if (m.status && m.status !== 'pending') extra.push(m.status);

        const badge = extra.length ? `  \`${extra.join(' · ')}\`` : '';
        return `\`${String(i + 1).padStart(2, ' ')}\`  **#${m.id}** — **${p1}** vs **${p2}**${badge}`;
    });

    embed.setDescription(lines.join('\n').slice(0, 4000));
    embed.setFooter({ text: `${matches.length} pertandingan` });
    return embed;
}

// ─────────────────────────────────────────────────────────────────────────────
// Generic helpers
// ─────────────────────────────────────────────────────────────────────────────
export function errorEmbed(message) {
    return new EmbedBuilder()
        .setColor(COLORS.error)
        .setTitle('❌  Error')
        .setDescription(String(message));
}

export function successEmbed(message) {
    return new EmbedBuilder()
        .setColor(COLORS.win)
        .setTitle('✅  Berhasil')
        .setDescription(String(message));
}
