<?php
namespace EasyChat\View;

class SettingFragments {

    public static function cmsIndexStatus($type = 'idle', $message = '', $job_id = null) {
        $type = in_array((string)$type, ['idle', 'success', 'warning', 'danger'], true) ? (string)$type : 'idle';
        $message = trim((string)$message);
        if ($message === '') {
            $message = 'Готово к запуску индексации.';
        }

        $icon = [
            'idle' => 'fa-info-circle',
            'success' => 'fa-check-circle',
            'warning' => 'fa-exclamation-triangle',
            'danger' => 'fa-times-circle',
        ][$type];

        $job = $job_id !== null
            ? '<span class="easychat-settings-inline-result__job">#' . self::e((string)$job_id) . '</span>'
            : '';

        return '<div id="cms-index-status"'
            . ' class="easychat-settings-inline-result easychat-settings-inline-result--' . self::e($type) . ' ' . self::e(HtmxFragmentRenderer::motionClass('settings-panel')) . '"'
            . ' role="' . ($type === 'danger' ? 'alert' : 'status') . '" aria-live="polite">'
            . '<i class="fa ' . self::e($icon) . '" aria-hidden="true"></i>'
            . '<span class="easychat-settings-inline-result__text">' . self::e($message) . '</span>'
            . $job
            . '</div>';
    }

    public static function catalogSearchPreview(array $products, $state = 'success', $message = '') {
        $state = in_array((string)$state, ['idle', 'success', 'empty', 'warning', 'danger'], true)
            ? (string)$state
            : 'danger';
        if ($state === 'idle') {
            return '<div id="catalog-preview-results" class="catalog-preview-results" aria-live="polite">'
                . '<div class="catalog-preview-empty"><i class="fa fa-search" aria-hidden="true"></i><span>Результаты появятся здесь</span></div>'
                . '</div>';
        }
        if ($state !== 'success' || empty($products)) {
            $default = $state === 'empty'
                ? 'Совпадений не найдено. Проверьте модель или попробуйте часть названия.'
                : 'Не удалось проверить каталог. Проверьте подключение CMS и повторите.';
            return '<div id="catalog-preview-results" class="catalog-preview-results" aria-live="polite">'
                . '<div class="catalog-preview-message is-' . self::e($state) . '" role="' . ($state === 'danger' ? 'alert' : 'status') . '">'
                . '<i class="fa ' . ($state === 'empty' ? 'fa-search' : 'fa-exclamation-circle') . '" aria-hidden="true"></i>'
                . '<span>' . self::e(trim((string)$message) !== '' ? $message : $default) . '</span></div></div>';
        }

        $html = '<div id="catalog-preview-results" class="catalog-preview-results" aria-live="polite"><div class="catalog-preview-list">';
        foreach ($products as $product) {
            $availability = in_array((string)($product['availability'] ?? ''), ['in_stock', 'preorder', 'out_of_stock', 'unknown'], true)
                ? (string)$product['availability']
                : 'unknown';
            $details = array_filter([
                trim((string)($product['model'] ?? '')) !== '' ? 'Модель: ' . trim((string)$product['model']) : '',
                trim((string)($product['sku'] ?? '')) !== '' ? 'SKU: ' . trim((string)$product['sku']) : '',
                array_key_exists('quantity', $product) ? 'Количество: ' . (string)$product['quantity'] : '',
            ]);
            $html .= '<article class="catalog-preview-product">'
                . '<div><strong>' . self::e($product['name'] ?? '') . '</strong>'
                . (!empty($details) ? '<small>' . self::e(implode(' · ', $details)) . '</small>' : '')
                . '</div><div class="catalog-preview-product__meta">'
                . '<span class="catalog-availability is-' . self::e($availability) . '">' . self::e($product['availability_label'] ?? 'Наличие уточняется') . '</span>'
                . '<b>' . self::e($product['price'] ?? 'Цена по запросу') . '</b>'
                . '<a href="' . self::e($product['link'] ?? '#') . '" target="_blank" rel="noopener noreferrer" aria-label="Открыть товар в новой вкладке"><i class="fa fa-external-link" aria-hidden="true"></i></a>'
                . '</div></article>';
        }
        return $html . '</div></div>';
    }

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

}
