<?php
namespace EasyChat\View;

class IntegrationFragments {

    public static function avitoHealthResult($payload = null, $visible = false) {
        if (!is_array($payload)) {
            return '<div id="avito-health-result" class="mt-3 border bg-light-subtle p-3 small easychat-status-panel easychat-diagnostics-panel mb-4 ' . self::motion('integration-diagnostics') . '" style="display:' . ($visible ? 'block' : 'none') . ';" role="status" aria-live="polite"></div>';
        }

        if (empty($payload['success'])) {
            return '<div id="avito-health-result" class="mt-3 border bg-light-subtle p-3 small easychat-status-panel easychat-diagnostics-panel mb-4 ' . self::motion('integration-diagnostics') . '" role="alert" aria-live="polite">'
                . '<div class="text-danger"><i class="fa fa-exclamation-triangle me-1" aria-hidden="true"></i>'
                . self::e((string)($payload['error'] ?? 'Не удалось выполнить Avito Health.')) . '</div>'
                . '</div>';
        }

        $channel = self::arr($payload['channel'] ?? []);
        $subscriptions = self::arr($payload['subscriptions'] ?? []);
        $avatars = self::arr($payload['avatars'] ?? []);
        $contacts = self::arr($payload['contacts'] ?? []);
        $queue = self::arr($payload['queue'] ?? []);
        $sample = self::arr($contacts['sample'] ?? []);
        $recommendations = self::arr($payload['recommendations'] ?? []);

        $html = '<div id="avito-health-result" class="mt-3 border bg-light-subtle p-3 small easychat-status-panel easychat-diagnostics-panel mb-4 ' . self::motion('integration-diagnostics') . '" role="status" aria-live="polite">';
        $html .= '<div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-2">'
            . '<div class="fw-semibold text-dark"><i class="fa fa-heartbeat me-1" aria-hidden="true"></i> Avito Health</div>'
            . '<div class="text-muted">' . self::e((string)($payload['checked_at'] ?? '')) . '</div>'
            . '</div>';

        $html .= '<div class="mb-2">'
            . self::pill('канал ' . (string)($channel['status'] ?? 'unknown'), !empty($channel['active']) ? 'success' : 'warning', 'Локальный статус канала Avito')
            . self::pill('credentials', !empty($channel['credentials_present']) ? 'success' : 'danger', 'Client ID/Client Secret сохранены')
            . self::pill('account id', !empty($channel['bot_user_id_present']) ? 'success' : (!empty($channel['api_account_present']) ? 'warning' : 'danger'), 'bot_user_id нужен для истории и отправки')
            . self::pill('webhook', !empty($subscriptions['webhook_present']) ? 'success' : (!empty($subscriptions['checked']) ? 'danger' : 'muted'), 'Сверяется по безопасному хешу URL')
            . self::pill('аватарки ' . (!empty($avatars['enabled']) ? 'on' : 'off'), !empty($avatars['enabled']) ? 'success' : 'muted', 'Общий переключатель аватарок клиентов')
            . self::pill('контакты ' . (int)($contacts['total'] ?? 0), ((int)($contacts['total'] ?? 0) > 0) ? 'success' : 'warning', 'Локальные Avito-контакты')
            . self::pill('queue failed ' . (int)($queue['recent_failed'] ?? 0), ((int)($queue['recent_failed'] ?? 0) > 0) ? 'danger' : 'success', 'Последние Avito/avatar задачи очереди')
            . '</div>';

        if (!empty($channel['last_error'])) {
            $html .= '<div class="text-danger mb-2"><i class="fa fa-exclamation-triangle me-1" aria-hidden="true"></i>' . self::e((string)$channel['last_error']) . '</div>';
        }

        if ($sample) {
            $html .= '<div class="table-responsive mt-2"><table class="table table-sm align-middle mb-2">'
                . '<thead><tr><th>Диалог</th><th>Аватар</th><th>История</th><th>Контекст</th><th>Очередь</th></tr></thead><tbody>';
            foreach ($sample as $row) {
                if (!is_array($row)) continue;
                $html .= self::avitoHealthRow($row);
            }
            $html .= '</tbody></table></div>';
        } else {
            $html .= '<div class="text-muted mt-2">Avito-диалогов пока нет. После первого сообщения Health покажет историю, контекст объявления и аватарки.</div>';
        }

        if ($recommendations) {
            $html .= '<div class="mt-2"><div class="fw-semibold text-dark mb-1">Что проверить</div>';
            foreach ($recommendations as $item) {
                $html .= '<div class="text-muted"><i class="fa fa-angle-right me-1" aria-hidden="true"></i>' . self::e((string)$item) . '</div>';
            }
            $html .= '</div>';
        }

        return $html . '</div>';
    }

    public static function tlsDiagnosticsResult($payload = null, $visible = false) {
        if (!is_array($payload)) {
            return '<div id="tls-diagnostics-result" class="' . self::motion('integration-diagnostics') . '" style="display:' . ($visible ? 'block' : 'none') . ';" role="status" aria-live="polite">'
                . '<div id="tls-diagnostics-summary" class="alert alert-light border small mb-3" style="border-radius: 10px; display:none;"></div>'
                . '<div class="table-responsive" id="tls-diagnostics-table-wrap" style="display:none;">' . self::tlsTable('') . '</div>'
                . '</div>';
        }

        if (empty($payload['success'])) {
            return '<div id="tls-diagnostics-result" class="' . self::motion('integration-diagnostics') . '" role="alert" aria-live="polite">'
                . '<div id="tls-diagnostics-summary" class="alert alert-danger border small mb-3" style="border-radius: 10px;">'
                . self::e((string)($payload['error'] ?? 'Не удалось выполнить диагностику HTTPS.')) . '</div>'
                . '<div class="table-responsive" id="tls-diagnostics-table-wrap" style="display:none;">' . self::tlsTable('') . '</div>'
                . '</div>';
        }

        $checks = self::arr($payload['checks'] ?? []);
        $failed = 0;
        $fallback = 0;
        foreach ($checks as $item) {
            if (!is_array($item)) continue;
            if (empty($item['transport_ok'])) $failed++;
            if (!empty($item['tls_fallback_used'])) $fallback++;
        }

        $summary_class = $failed ? 'alert-danger' : ($fallback ? 'alert-warning' : 'alert-success');
        $summary = $failed
            ? 'Есть сервисы с ошибкой TLS/HTTPS. Проверьте строки ниже.'
            : ($fallback ? 'Все сервисы доступны, для части host используется российский CA fallback.' : 'Все сервисы доступны через обычное доверие сервера.');

        $rows = '';
        foreach ($checks as $item) {
            if (!is_array($item)) continue;
            $status_class = !empty($item['transport_ok']) ? (!empty($item['tls_fallback_used']) ? 'text-warning' : 'text-success') : 'text-danger';
            $status_text = !empty($item['transport_ok'])
                ? (!empty($item['tls_fallback_used']) ? 'Fallback CA' : 'OK')
                : (string)($item['error_label'] ?? ('Ошибка ' . (int)($item['curl_errno'] ?? 0)));
            $status_hint = empty($item['transport_ok']) ? trim((string)($item['error_hint'] ?? '')) : '';
            $rows .= '<tr>'
                . '<td>' . self::e((string)($item['label'] ?? '')) . '</td>'
                . '<td><code>' . self::e((string)($item['host'] ?? '')) . '</code></td>'
                . '<td><span class="text-secondary small">' . self::e((string)($item['proxy_label'] ?? '')) . '</span></td>'
                . '<td><span class="' . $status_class . '">' . self::e($status_text) . '</span>'
                . ($status_hint !== '' ? '<div class="text-muted small mt-1" style="max-width:320px;line-height:1.35;">' . self::e($status_hint) . '</div>' : '')
                . '</td>'
                . '<td>' . self::e((string)($item['trust_bundle'] ?? '')) . '</td>'
                . '<td>' . (int)($item['http_code'] ?? 0) . '</td>'
                . '</tr>';
        }

        return '<div id="tls-diagnostics-result" class="' . self::motion('integration-diagnostics') . '" role="status" aria-live="polite">'
            . '<div id="tls-diagnostics-summary" class="alert ' . $summary_class . ' border small mb-3" style="border-radius: 10px;">' . self::e($summary) . '</div>'
            . '<div class="table-responsive" id="tls-diagnostics-table-wrap">' . self::tlsTable($rows) . '</div>'
            . '</div>';
    }

    private static function avitoHealthRow(array $row) {
        $avatar_state = 'muted';
        $avatar_text = 'не проверялось';
        if (($row['api_avatar_present'] ?? null) === true) {
            $avatar_state = !empty($row['avatar_file_exists']) ? 'success' : 'warning';
            $avatar_text = !empty($row['avatar_file_exists']) ? 'файл готов' : 'есть в API, нет файла';
        } elseif (!empty($row['avatar_file_present'])) {
            $avatar_state = !empty($row['avatar_file_exists']) ? 'success' : 'warning';
            $avatar_text = !empty($row['avatar_file_exists']) ? 'файл готов' : 'файл не отдается';
        } elseif (($row['api_avatar_present'] ?? null) === false) {
            $avatar_text = 'API без avatar URL';
        }

        $history_state = 'muted';
        $history_text = 'не проверялась';
        if (array_key_exists('history_out_missing_count', $row) && $row['history_out_missing_count'] !== null) {
            $history_state = ((int)$row['history_out_missing_count'] > 0) ? 'danger' : 'success';
            $history_text = 'out API ' . (int)($row['api_out_count'] ?? 0) . ', нет локально ' . (int)$row['history_out_missing_count'];
        }

        $context_state = ((int)($row['local_context_count'] ?? 0) > 0) ? 'success' : (!empty($row['api_item_context_present']) ? 'warning' : 'muted');
        $context_text = ((int)($row['local_context_count'] ?? 0) > 0) ? ('локально ' . (int)$row['local_context_count']) : (!empty($row['api_item_context_present']) ? 'есть в API' : 'нет данных');
        $queue = self::arr($row['queue'] ?? []);

        $html = '<tr><td><div class="fw-semibold">' . self::e((string)($row['display_name'] ?? 'Avito contact')) . '</div>'
            . '<div class="text-muted">chat# ' . self::e((string)($row['external_chat_hash'] ?? '-')) . '</div>';
        if (!empty($row['api_error'])) {
            $html .= '<div class="text-danger">api: ' . self::e((string)$row['api_error']) . '</div>';
        }
        $html .= '</td>'
            . '<td>' . self::pill($avatar_text, $avatar_state, (string)($row['avatar_last_error'] ?? '')) . '</td>'
            . '<td>' . self::pill($history_text, $history_state, implode(', ', self::arr($row['history_out_missing_hashes'] ?? []))) . '</td>'
            . '<td>' . self::pill($context_text, $context_state, 'Контекст объявления') . '</td>'
            . '<td><div class="text-muted">history: ' . self::e(self::queueText(self::arr($queue['history'] ?? []))) . '</div>'
            . '<div class="text-muted">avatar: ' . self::e(self::queueText(self::arr($queue['avatar'] ?? []))) . '</div></td></tr>';
        return $html;
    }

    private static function tlsTable($rows) {
        return '<table class="table table-sm align-middle mb-0"><thead><tr class="text-muted small">'
            . '<th>Сервис</th><th>Host</th><th>Маршрут</th><th>Статус</th><th>Bundle</th><th>HTTP</th>'
            . '</tr></thead><tbody id="tls-diagnostics-rows">' . (string)$rows . '</tbody></table>';
    }

    private static function queueText(array $queue) {
        if (empty($queue['total'])) return 'нет задач';
        $parts = [];
        foreach (['pending', 'processing', 'failed'] as $key) {
            if (!empty($queue[$key])) $parts[] = $key . ' ' . (int)$queue[$key];
        }
        if (!$parts) $parts[] = 'done ' . (int)($queue['done'] ?? 0);
        return implode(', ', $parts);
    }

    private static function pill($label, $state, $detail = '') {
        $class_map = [
            'success' => 'bg-success-subtle text-success border border-success-subtle',
            'warning' => 'bg-warning-subtle text-warning border border-warning-subtle',
            'danger' => 'bg-danger-subtle text-danger border border-danger-subtle',
            'muted' => 'bg-light text-secondary border',
        ];
        $icon_map = [
            'success' => 'fa-check-circle',
            'warning' => 'fa-exclamation-triangle',
            'danger' => 'fa-times-circle',
            'muted' => 'fa-circle-o',
        ];
        $state = isset($class_map[$state]) ? $state : 'muted';
        return '<span class="badge ' . $class_map[$state] . ' px-2 py-1 me-1 mb-1" title="' . self::e((string)$detail) . '">'
            . '<i class="fa ' . $icon_map[$state] . ' me-1" aria-hidden="true"></i>' . self::e((string)$label) . '</span>';
    }

    private static function motion($kind) {
        return self::e(HtmxFragmentRenderer::motionClass($kind));
    }

    private static function arr($value) {
        return is_array($value) ? $value : [];
    }

    private static function e($value) {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }

}
