<?php

declare(strict_types=1);

use Tournament\User\UserTournamentStatus;

function renderUserTournamentStatus(
    PDO $pdo,
    int $chat_id,
    int $mid,
    int $eid,
    int $uid
): void {
    try {

        /*
         * ==========================================
         * Service
         * ==========================================
         */
        $service =
            new UserTournamentStatus(
                $pdo
            );

        error_log(
            '[USER STATUS RENDER] Service created | '
            . 'eid=' . $eid
            . ' uid=' . $uid
        );

        /*
         * ==========================================
         * Data
         * ==========================================
         */
        $data =
            $service->get(
                $eid,
                $uid
            );

        error_log(
            '[USER STATUS RENDER] Data loaded'
        );

        error_log(
            '[USER STATUS DATA] ' .
            print_r(
                $data,
                true
            )
        );

        /*
         * ==========================================
         * ثبت‌نام نشده
         * ==========================================
         */
        if (empty($data['joined'])) {

            error_log(
                '[USER STATUS] JOINED IS EMPTY'
            );

            $result = editMessageText2(
                $chat_id,
                $mid,
                "❌ <b>شما در این تورنومنت ثبت‌نام نکرده‌اید.</b>",
                [
                    'inline_keyboard' => [
                        [
                            [
                                'text' =>
                                    '🔙 بازگشت',
                                'callback_data' =>
                                    'ev_view:' . $eid . ':' . $uid
                            ]
                        ]
                    ]
                ],
                true
            );

            error_log(
                '[USER STATUS NOT JOINED API] ' .
                print_r(
                    $result,
                    true
                )
            );

            return;
        }

        /*
         * ==========================================
         * Event
         * ==========================================
         */
        $eventName =
            (string) (
                $data['event']['name']
                ?? 'Tournament'
            );

        /*
         * ==========================================
         * Status
         * ==========================================
         */
        $statusKey =
            (string) (
                $data['status']
                ?? 'registered'
            );

        $status =
            match ($statusKey) {

                'winner' =>
                    '🏆 قهرمان',

                'eliminated' =>
                    '🔴 حذف شده',

                'active' =>
                    '🟢 در حال رقابت',

                'waiting' =>
                    '🟡 در انتظار شروع',

                default =>
                    '✅ ثبت‌نام شده',
            };

        /*
         * ==========================================
         * Timeline
         * ==========================================
         */
        $timeline = '';

        $stages =
            is_array(
                $data['stages']
                ?? null
            )
                ? $data['stages']
                : [];

        foreach (
            $stages as $stage
        ) {

            $stageStatus =
                (string) (
                    $stage['status']
                    ?? ''
                );

            $icon =
                match ($stageStatus) {

                    'completed' =>
                        '✅',

                    'active' =>
                        '🟢',

                    'cancelled' =>
                        '🔴',

                    default =>
                        '⚪',
                };

            $stageName =
                htmlspecialchars(
                    (string) (
                        $stage['name']
                        ?? 'Stage'
                    ),
                    ENT_QUOTES |
                    ENT_SUBSTITUTE,
                    'UTF-8'
                );

            $timeline .=
                $icon
                . ' '
                . $stageName
                . "\n";
        }

        if ($timeline === '') {
            $timeline =
                "⚪ هنوز مرحله‌ای برای نمایش وجود ندارد\n";
        }

        /*
         * ==========================================
         * Current Stage
         * ==========================================
         */
        $currentStage =
            is_array(
                $data['current_stage']
                ?? null
            )
                ? $data['current_stage']
                : null;

        $currentStageName =
            $currentStage
                ? (string) (
                    $currentStage['name']
                    ?? '—'
                )
                : '—';

        $currentStageNameHtml =
            htmlspecialchars(
                $currentStageName,
                ENT_QUOTES |
                ENT_SUBSTITUTE,
                'UTF-8'
            );

        /*
         * ==========================================
         * Progress
         * ==========================================
         */
        $played =
            (int) (
                $data['progress']['played']
                ?? 0
            );

        $total =
            (int) (
                $data['progress']['total']
                ?? 0
            );

        if ($total > 0) {

            $played =
                max(
                    0,
                    min(
                        $played,
                        $total
                    )
                );

            $progressText =
                $played
                . '/'
                . $total
                . ' بازی';

        } else {

            $progressText =
                '—';
        }

        /*
         * ==========================================
         * Performance
         * ==========================================
         */
        $performance =
            is_array(
                $data['performance']
                ?? null
            )
                ? $data['performance']
                : [];

        $score =
            (float) (
                $performance['score']
                ?? 0
            );

        $kills =
            (int) (
                $performance['kills']
                ?? 0
            );

        $rank =
            $performance['rank']
            ?? null;

        $totalPlayers =
            (int) (
                $performance['total_players']
                ?? 0
            );

        /*
         * ==========================================
         * Rank
         * ==========================================
         */
        if (
            $rank !== null
            && (int) $rank > 0
        ) {

            $rankText =
                '#'
                . (int) $rank;

            if ($totalPlayers > 0) {
                $rankText .=
                    ' از '
                    . $totalPlayers;
            }

        } else {

            $rankText =
                '—';
        }

        /*
         * ==========================================
         * Score
         * ==========================================
         */
        $scoreText =
            rtrim(
                rtrim(
                    number_format(
                        $score,
                        2,
                        '.',
                        ','
                    ),
                    '0'
                ),
                '.'
            );

        if ($scoreText === '') {
            $scoreText = '0';
        }

        /*
         * ==========================================
         * Next Stage
         * ==========================================
         */
        $nextStage =
            is_array(
                $data['next_stage']
                ?? null
            )
                ? $data['next_stage']
                : null;

        if ($statusKey === 'winner') {

            $nextStageText =
                '🏆 قهرمان تورنومنت';

        } elseif ($statusKey === 'eliminated') {

            $nextStageText =
                'مسابقات شما به پایان رسیده است';

        } elseif ($nextStage) {

            $nextStageText =
                htmlspecialchars(
                    (string) (
                        $nextStage['name']
                        ?? 'مرحله بعد'
                    ),
                    ENT_QUOTES |
                    ENT_SUBSTITUTE,
                    'UTF-8'
                );

        } elseif ($currentStage) {

            $nextStageText =
                'پس از پایان '
                . $currentStageNameHtml;

        } else {

            $nextStageText =
                'در انتظار شروع تورنومنت';
        }

        /*
         * ==========================================
         * متن
         * ==========================================
         */
        $txt =
            "<blockquote>👤 <b>وضعیت شما</b> | $status </blockquote>\n\n"

            . "🔥 <b>مرحله فعلی:</b> $currentStageNameHtml\n\n"

            . "🎯 <b>پیشرفت:</b>\n"
            . $progressText
            . "\n\n"

            . "🏆 <b>رتبه:</b>\n"
            . $rankText
            . "\n\n"

            . "⭐ <b>امتیاز:</b>\n"
            . $scoreText
            . "\n\n"

            . "💀 <b>Kills:</b> "
            . $kills
            . "\n\n"

            . "⏳ <b>مرحله بعد:</b>\n"
            . $nextStageText;

        /*
         * ==========================================
         * Keyboard
         * ==========================================
         */
        $keyboard = [
            [
                [
                    'text' =>
                        '🏆 جدول رتبه‌بندی',
                    'callback_data' =>
                        'user_leaderboard:' . $eid
                ]
            ],
            [
                [
                    'text' =>
                        '🎮 بازی‌های من',
                    'callback_data' =>
                        'user_games:' . $eid
                ]
            ],
            [
                [
                    'text' =>
                        '📜 قوانین',
                    'callback_data' =>
                        'event_rules:' . $eid
                ]
            ],
            [
                [
                    'text' =>
                        '🔙 بازگشت',
                    'callback_data' =>
                    'ev_view:' . $eid . ':' . $uid . ':' . ($data['joined'] ? 'true' : 'false')
                ]
            ]
        ];

        /*
         * ==========================================
         * Edit message
         *
         * از forceDelete استفاده نمی‌کنیم.
         * ==========================================
         */
        error_log(
            '[USER STATUS RENDER] Before edit | '
            . 'chat=' . $chat_id
            . ' mid=' . $mid
        );

        $result =
            editMessageText2(
                $chat_id,
                $mid,
                $txt,
                [
                    'inline_keyboard' =>
                        $keyboard
                ],
                true
            );

        error_log(
            '[USER STATUS RENDER] API result: '
            . print_r(
                $result,
                true
            )
        );

    } catch (Throwable $e) {

        error_log(
            '[USER TOURNAMENT STATUS ERROR] '
            . $e->getMessage()
            . "\n"
            . $e->getTraceAsString()
        );

        try {

            editMessageText2(
                $chat_id,
                $mid,
                "❌ <b>نمایش وضعیت شما انجام نشد.</b>\n\n"
                . "<code>"
                . htmlspecialchars(
                    $e->getMessage(),
                    ENT_QUOTES |
                    ENT_SUBSTITUTE,
                    'UTF-8'
                )
                . "</code>",
                [
                    'inline_keyboard' => [
                        [
                            [
                                'text' =>
                                    '🔙 بازگشت',
                                'callback_data' =>
                                    'event_view:' . $eid
                            ]
                        ]
                    ]
                ],
                true
            );

        } catch (Throwable $inner) {

            error_log(
                '[USER STATUS ERROR UI] '
                . $inner->getMessage()
            );
        }
    }
}