<?php
$marketplace_escape = static function ($value) {
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
};
$marketplace_stream_labels = [
    'buyer_chat' => ['title' => 'Чаты покупателей', 'icon' => 'fa-comments-o'],
    'question' => ['title' => 'Вопросы о товарах', 'icon' => 'fa-question-circle-o'],
    'review' => ['title' => 'Отзывы', 'icon' => 'fa-star-o'],
    'return_claim' => ['title' => 'Возвраты', 'icon' => 'fa-undo'],
];
$marketplace_date = static function ($value) {
    $timestamp = strtotime((string)$value);
    return $timestamp ? date('d.m.Y H:i', $timestamp) : '';
};
$marketplace_count_label = static function ($count) {
    $count = abs((int)$count) % 100;
    $last = $count % 10;
    if ($count > 10 && $count < 20) return 'кабинетов подключено';
    if ($last === 1) return 'кабинет подключен';
    if ($last >= 2 && $last <= 4) return 'кабинета подключено';
    return 'кабинетов подключено';
};

$marketplace_provider = (string)($marketplace_provider ?? '');
$marketplace_definition = is_array($marketplace_provider_definition ?? null) ? $marketplace_provider_definition : [];
$marketplace_accounts = is_array($marketplace_provider_accounts ?? null) ? $marketplace_provider_accounts : [];
$marketplace_title = (string)($marketplace_definition['title'] ?? $marketplace_provider);
$marketplace_is_wb = $marketplace_provider === 'wildberries';
$marketplace_is_yandex = $marketplace_provider === 'yandex_market';
$marketplace_brand_class = (string)($marketplace_definition['brand_class'] ?? ($marketplace_is_wb ? 'wb' : 'ozon'));
$marketplace_brand_text = (string)($marketplace_definition['brand_text'] ?? ($marketplace_is_wb ? 'WB' : 'O'));
$marketplace_brand_asset = (string)($marketplace_definition['brand_asset'] ?? '');
$marketplace_active_count = count(array_filter($marketplace_accounts, static function ($account) {
    return (string)($account['status'] ?? '') === 'active';
}));
?>
<section class="easychat-marketplaces" data-marketplace-screen data-marketplace-provider-root="<?php echo $marketplace_escape($marketplace_provider); ?>" data-csrf-token="<?php echo $marketplace_escape($marketplace_csrf_token ?? ''); ?>">
    <header class="easychat-marketplaces__panel-head">
        <div class="easychat-marketplaces__panel-title">
            <span class="easychat-marketplaces__brand easychat-marketplaces__brand--<?php echo $marketplace_escape($marketplace_brand_class); ?>">
                <?php if ($marketplace_brand_asset !== '') { ?>
                    <img src="<?php echo $marketplace_escape($marketplace_brand_asset); ?>" width="136" height="20" alt="Яндекс Маркет">
                <?php } else { ?>
                    <span aria-hidden="true"><?php echo $marketplace_escape($marketplace_brand_text); ?></span>
                <?php } ?>
            </span>
            <div>
                <h5><?php echo $marketplace_escape($marketplace_title); ?></h5>
                <p><?php echo $marketplace_escape($marketplace_definition['description'] ?? ''); ?></p>
            </div>
        </div>
        <div class="easychat-marketplaces__panel-actions">
            <span class="easychat-marketplaces__summary" aria-label="Активные кабинеты">
                <strong><?php echo $marketplace_active_count; ?></strong>
                <span><?php echo $marketplace_escape($marketplace_count_label($marketplace_active_count)); ?></span>
            </span>
            <?php if (!empty($marketplace_definition['docs_url'])) { ?>
                <a class="btn btn-outline-secondary btn-sm" href="<?php echo $marketplace_escape($marketplace_definition['docs_url']); ?>" target="_blank" rel="noopener noreferrer">
                    <i class="fa fa-book" aria-hidden="true"></i><span>Инструкция</span>
                </a>
            <?php } ?>
        </div>
    </header>

    <div class="easychat-marketplaces__notice" role="note">
        <i class="fa fa-shield" aria-hidden="true"></i>
        <span>Ключи шифруются на этом сервере. История переписки не передается в центральный EasyChat.</span>
    </div>

    <?php if (empty($marketplace_storage_ready)) { ?>
        <div class="alert alert-warning mb-0" role="alert">
            <strong>Настройка маркетплейсов пока недоступна.</strong>
            Завершите обновление EasyChat, затем откройте вкладку снова.
        </div>
    <?php } else { ?>
        <section class="easychat-marketplaces__connect" aria-labelledby="marketplace-connect-title-<?php echo $marketplace_escape($marketplace_provider); ?>">
            <div class="easychat-marketplaces__connect-head">
                <div>
                    <h6 id="marketplace-connect-title-<?php echo $marketplace_escape($marketplace_provider); ?>">Подключить кабинет <?php echo $marketplace_escape($marketplace_title); ?></h6>
                    <p>EasyChat проверит ключ и сам включит доступные обращения.</p>
                </div>
                <span class="easychat-marketplaces__instant-note"><i class="fa fa-check-circle" aria-hidden="true"></i> Сохраняется сразу</span>
            </div>

            <div class="easychat-marketplaces__form" data-marketplace-form="<?php echo $marketplace_escape($marketplace_provider); ?>" role="group" aria-labelledby="marketplace-connect-title-<?php echo $marketplace_escape($marketplace_provider); ?>">
                <?php if ($marketplace_is_wb) { ?>
                    <div class="easychat-marketplaces__field easychat-marketplaces__field--wide">
                        <label for="marketplace-wb-token">API-токен Wildberries</label>
                        <input id="marketplace-wb-token" data-marketplace-field="api_token" type="password" autocomplete="new-password" spellcheck="false"
                               autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                               data-marketplace-required="1" aria-required="true"
                               placeholder="Вставьте токен из кабинета WB">
                        <small>Выберите «Персональный» токен с правами «Чат с покупателями», «Вопросы и отзывы» и, при необходимости, «Возвраты».</small>
                        <div class="easychat-marketplaces__token-preview" data-wb-token-preview role="status" aria-live="polite" hidden></div>
                    </div>
                <?php } elseif ($marketplace_is_yandex) { ?>
                    <div class="easychat-marketplaces__field easychat-marketplaces__field--wide">
                        <label for="marketplace-yandex-key">API-Key Яндекс Маркета</label>
                        <input id="marketplace-yandex-key" data-marketplace-field="api_key" type="password" autocomplete="new-password" spellcheck="false"
                               autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                               data-marketplace-required="1" aria-required="true"
                               placeholder="Вставьте API-Key с доступом communication">
                        <small>Создайте ключ в кабинете Маркета: Настройки → API и модули → Токены авторизации.</small>
                    </div>
                <?php } else { ?>
                    <div class="easychat-marketplaces__field">
                        <label for="marketplace-ozon-client">Client ID</label>
                        <input id="marketplace-ozon-client" data-marketplace-field="client_id" type="text" inputmode="numeric" autocomplete="off" spellcheck="false"
                               autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                               data-marketplace-required="1" aria-required="true"
                               placeholder="Например, 123456">
                    </div>
                    <div class="easychat-marketplaces__field">
                        <label for="marketplace-ozon-key">API key</label>
                        <input id="marketplace-ozon-key" data-marketplace-field="api_key" type="password" autocomplete="new-password" spellcheck="false"
                               autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                               data-marketplace-required="1" aria-required="true"
                               placeholder="Вставьте ключ Seller API">
                    </div>
                    <div class="easychat-marketplaces__token-preview" data-ozon-key-preview role="status" aria-live="polite" hidden></div>
                <?php } ?>
                <button class="btn btn-primary" type="button" data-marketplace-connect>
                    <i class="fa fa-plug" aria-hidden="true"></i><span>Проверить и подключить</span>
                </button>
                <?php if (!$marketplace_is_wb && !$marketplace_is_yandex) { ?>
                    <small class="easychat-marketplaces__form-note">Для переписки у кабинета должна быть доступна работа с чатами через Seller API.</small>
                <?php } ?>
            </div>
            <div class="easychat-marketplaces__result" data-marketplace-result role="status" aria-live="polite" hidden></div>
        </section>

        <section class="easychat-marketplaces__accounts-section" aria-labelledby="marketplace-accounts-title-<?php echo $marketplace_escape($marketplace_provider); ?>">
            <div class="easychat-marketplaces__accounts-head">
                <div>
                    <h6 id="marketplace-accounts-title-<?php echo $marketplace_escape($marketplace_provider); ?>">Подключенные кабинеты <?php echo $marketplace_escape($marketplace_title); ?></h6>
                    <p>Первое получение истории проходит тихо: без push и автоответов.</p>
                </div>
            </div>

            <div class="easychat-marketplaces__accounts" data-marketplace-accounts>
                <?php if (empty($marketplace_accounts)) { ?>
                    <div class="easychat-marketplaces__empty">
                        <i class="fa fa-inbox" aria-hidden="true"></i>
                        <strong>Пока нет подключенных кабинетов <?php echo $marketplace_escape($marketplace_title); ?></strong>
                        <span><?php echo $marketplace_escape($marketplace_definition['empty_text'] ?? 'Добавьте первый кабинет выше.'); ?></span>
                    </div>
                <?php } ?>

                <?php foreach ($marketplace_accounts as $account) {
                $active = (string)($account['status'] ?? '') === 'active';
                ?>
                <article class="easychat-marketplaces__account<?php echo $active ? '' : ' is-disabled'; ?>" data-marketplace-account="<?php echo (int)$account['channel_id']; ?>">
                    <div class="easychat-marketplaces__account-head">
                        <div class="easychat-marketplaces__identity">
                            <span class="easychat-marketplaces__brand easychat-marketplaces__brand--<?php echo $marketplace_escape($marketplace_brand_class); ?>">
                                <?php if ($marketplace_brand_asset !== '') { ?>
                                    <img src="<?php echo $marketplace_escape($marketplace_brand_asset); ?>" width="136" height="20" alt="Яндекс Маркет">
                                <?php } else { ?>
                                    <span aria-hidden="true"><?php echo $marketplace_escape($marketplace_brand_text); ?></span>
                                <?php } ?>
                            </span>
                            <div>
                                <div class="easychat-marketplaces__account-title">
                                    <h6><?php echo $marketplace_escape($account['title'] ?: $marketplace_title); ?></h6>
                                    <span class="easychat-marketplaces__state <?php echo $active ? 'is-ok' : 'is-off'; ?>"><?php echo $active ? 'Подключен' : 'Отключен'; ?></span>
                                </div>
                                <p><?php echo $marketplace_escape($marketplace_title); ?> · ID <?php echo $marketplace_escape($account['external_account_id'] ?? ''); ?></p>
                            </div>
                        </div>
                        <div class="easychat-marketplaces__account-actions">
                            <?php if ($active) { ?>
                                <button type="button" class="btn btn-outline-primary btn-sm" data-marketplace-sync title="Сверить обращения сейчас">
                                    <i class="fa fa-refresh" aria-hidden="true"></i><span>Синхронизировать</span>
                                </button>
                                <button type="button" class="btn btn-outline-danger btn-sm" data-marketplace-disconnect title="Отключить кабинет" aria-label="Отключить кабинет">
                                    <i class="fa fa-power-off" aria-hidden="true"></i>
                                </button>
                            <?php } ?>
                        </div>
                    </div>

                    <?php if ($active) { ?>
                        <div class="easychat-marketplaces__streams">
                            <?php foreach (($account['streams'] ?? []) as $stream) {
                                $code = (string)($stream['stream'] ?? '');
                                $meta = $marketplace_stream_labels[$code] ?? ['title' => $code, 'icon' => 'fa-circle-o'];
                                $available = $stream['available'] ?? null;
                                $enabled = (string)($stream['status'] ?? '') === 'enabled';
                                $permission_missing = $available === false;
                            ?>
                                <label class="easychat-marketplaces__stream<?php echo $permission_missing ? ' is-unavailable' : ''; ?>">
                                    <span class="easychat-marketplaces__stream-icon"><i class="fa <?php echo $marketplace_escape($meta['icon']); ?>" aria-hidden="true"></i></span>
                                    <span class="easychat-marketplaces__stream-copy">
                                        <strong><?php echo $marketplace_escape($meta['title']); ?></strong>
                                        <small><?php if ($permission_missing) { ?>Нет прав у ключа<?php
                                            } elseif (!empty($stream['last_error'])) { ?>Повторим автоматически<?php
                                            } elseif (!empty($stream['last_success_at'])) { ?>Обновлено <?php echo $marketplace_escape($marketplace_date($stream['last_success_at'])); ?><?php
                                            } else { ?>Готово к первой сверке<?php } ?></small>
                                    </span>
                                    <input type="checkbox" class="form-check-input" data-marketplace-stream="<?php echo $marketplace_escape($code); ?>"
                                           <?php echo $enabled ? 'checked' : ''; ?> <?php echo $permission_missing ? 'disabled' : ''; ?>>
                                </label>
                            <?php } ?>
                        </div>

                        <div class="easychat-marketplaces__health">
                            <span><i class="fa fa-clock-o" aria-hidden="true"></i>
                                <?php echo !empty($account['last_sync_at']) ? 'Последняя сверка: ' . $marketplace_escape($marketplace_date($account['last_sync_at'])) : 'Первая сверка поставлена в очередь'; ?>
                            </span>
                            <?php if ($marketplace_provider === 'ozon') { ?>
                                <span class="<?php echo !empty($account['webhook_synced_at']) ? 'is-ok' : 'is-warn'; ?>">
                                    <i class="fa <?php echo !empty($account['webhook_synced_at']) ? 'fa-bolt' : 'fa-refresh'; ?>" aria-hidden="true"></i>
                                    <?php echo !empty($account['webhook_synced_at']) ? 'Быстрые уведомления включены' : 'Работает резервная сверка'; ?>
                                </span>
                                <?php $marketplace_key_health = is_array($account['token_health']['key'] ?? null) ? $account['token_health']['key'] : []; ?>
                                <?php if (!empty($marketplace_key_health['expires_label'])) { ?>
                                    <span class="<?php echo ($marketplace_key_health['status'] ?? '') === 'valid' ? 'is-ok' : 'is-warn'; ?>">
                                        <i class="fa <?php echo ($marketplace_key_health['status'] ?? '') === 'expired' ? 'fa-exclamation-triangle' : 'fa-clock-o'; ?>" aria-hidden="true"></i>
                                        <?php echo ($marketplace_key_health['status'] ?? '') === 'expired' ? 'Ключ истек' : 'Ключ действует до ' . $marketplace_escape($marketplace_key_health['expires_label']); ?>
                                    </span>
                                <?php } ?>
                            <?php } ?>
                            <?php if ($marketplace_is_yandex) { ?>
                                <span class="is-ok">
                                    <i class="fa fa-refresh" aria-hidden="true"></i>
                                    Уведомления + обязательная сверка
                                </span>
                            <?php } ?>
                            <?php if ($marketplace_is_wb) {
                                $marketplace_token_health = is_array($account['token_health'] ?? null) ? $account['token_health'] : [];
                                $marketplace_token_type = (string)($marketplace_token_health['type'] ?? 'unknown');
                                $marketplace_token_label = trim((string)($marketplace_token_health['label'] ?? ''));
                            ?>
                                <?php if ($marketplace_token_type === 'unknown' || $marketplace_token_label === '') { ?>
                                    <span>
                                        <i class="fa fa-info-circle" aria-hidden="true"></i>
                                        Тип токена определится при следующем подключении
                                    </span>
                                <?php } else { ?>
                                    <span class="<?php echo $marketplace_token_type === 'personal' ? 'is-ok' : 'is-warn'; ?>">
                                        <i class="fa <?php echo $marketplace_token_type === 'personal' ? 'fa-shield' : 'fa-exclamation-triangle'; ?>" aria-hidden="true"></i>
                                        <?php echo $marketplace_escape($marketplace_token_label); ?> токен
                                        <?php if ($marketplace_token_type === 'base') { ?> — безопасная редкая сверка<?php } ?>
                                    </span>
                                <?php } ?>
                            <?php } ?>
                            <?php if (!empty($account['last_error_message'])) { ?>
                                <span class="is-warn easychat-marketplaces__health-note"><i class="fa fa-exclamation-triangle" aria-hidden="true"></i> <?php echo $marketplace_escape($account['last_error_message']); ?></span>
                            <?php } ?>
                        </div>
                        <?php if ($marketplace_is_yandex) { ?>
                            <div class="easychat-marketplaces__yandex-settings">
                                <div class="easychat-marketplaces__webhook">
                                    <div>
                                        <strong>Адрес API-уведомлений</strong>
                                        <small>Добавьте его в кабинете Маркета. Повторные события безопасно объединяются, а polling страхует пропуски и стикеры.</small>
                                    </div>
                                    <div class="easychat-marketplaces__webhook-copy">
                                        <input type="text" readonly data-marketplace-webhook-url value="<?php echo $marketplace_escape($account['webhook_url'] ?? ''); ?>" aria-label="Адрес API-уведомлений Яндекс Маркета">
                                        <button type="button" class="btn btn-outline-secondary btn-sm" data-marketplace-copy-webhook>
                                            <i class="fa fa-copy" aria-hidden="true"></i><span>Копировать</span>
                                        </button>
                                    </div>
                                </div>
                                <div class="easychat-marketplaces__options" aria-label="Автоматизация Яндекс Маркета">
                                    <label class="easychat-marketplaces__option">
                                        <span>
                                            <strong>Автоответы ИИ в обычных чатах</strong>
                                            <small>По умолчанию выключены. Споры, вопросы и отзывы всегда остаются на проверке оператора.</small>
                                        </span>
                                        <input type="checkbox" class="form-check-input" data-marketplace-option="ai_auto_reply" <?php echo !empty($account['options']['ai_auto_reply']) ? 'checked' : ''; ?>>
                                    </label>
                                </div>
                            </div>
                        <?php } ?>
                        <div class="easychat-marketplaces__account-result" data-marketplace-account-result role="status" aria-live="polite" hidden></div>
                    <?php } else { ?>
                        <div class="easychat-marketplaces__reconnect" data-marketplace-reconnect role="group" aria-label="Подключить кабинет снова">
                            <input type="hidden" data-marketplace-field="channel_id" value="<?php echo (int)$account['channel_id']; ?>">
                            <?php if ($marketplace_provider === 'ozon') { ?>
                                <input data-marketplace-field="client_id" type="text" inputmode="numeric" autocomplete="off" spellcheck="false"
                                       autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                                       value="<?php echo $marketplace_escape($account['external_account_id'] ?? ''); ?>" aria-label="Client ID Ozon">
                                <input data-marketplace-field="api_key" type="password" autocomplete="new-password" spellcheck="false"
                                       autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                                       data-marketplace-required="1" aria-required="true"
                                       placeholder="Новый API key" aria-label="API key Ozon">
                                <div class="easychat-marketplaces__token-preview" data-ozon-key-preview role="status" aria-live="polite" hidden></div>
                            <?php } elseif ($marketplace_is_yandex) { ?>
                                <input data-marketplace-field="api_key" type="password" autocomplete="new-password" spellcheck="false"
                                       autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                                       data-marketplace-required="1" aria-required="true"
                                       placeholder="Новый API-Key Маркета" aria-label="API-Key Яндекс Маркета">
                            <?php } else { ?>
                                <input data-marketplace-field="api_token" type="password" autocomplete="new-password" spellcheck="false"
                                       autocapitalize="none" autocorrect="off" data-lpignore="true" data-1p-ignore="true" data-bwignore
                                       data-marketplace-required="1" aria-required="true"
                                       placeholder="Новый API-токен WB" aria-label="API-токен Wildberries">
                                <div class="easychat-marketplaces__token-preview" data-wb-token-preview role="status" aria-live="polite" hidden></div>
                            <?php } ?>
                            <button type="button" class="btn btn-primary btn-sm" data-marketplace-reconnect-submit><i class="fa fa-plug" aria-hidden="true"></i> Подключить снова</button>
                        </div>
                        <div class="easychat-marketplaces__account-result" data-marketplace-account-result role="status" aria-live="polite" hidden></div>
                    <?php } ?>
                </article>
                <?php } ?>
            </div>
        </section>
    <?php } ?>
</section>
