<?php
declare(strict_types=1);

namespace Celena\Core\Template\Tags;

use Celena\Core\Template\TagInterface;

/**
 * {async block="latest_news" url="/api/blocks/latest_news" placeholder="Загрузка..." trigger="load|visible"}
 *
 * Превращается в <div data-celena-async="..." data-celena-trigger="load|visible">
 * который celena.js (~3 КБ в /public/assets/runtime/celena.js) подгружает после
 * DOMContentLoaded (или при появлении в зоне видимости).
 */
final class AsyncTag implements TagInterface
{
    public function render(array $params, array $vars, ?string $body = null): string
    {
        $block = trim((string) ($params['block'] ?? ''));
        $url = trim((string) ($params['url'] ?? ''));
        if ($url === '' && $block !== '') {
            $url = '/api/blocks/' . rawurlencode($block);
        }
        if ($url === '') {
            return '';
        }
        $trigger = (string) ($params['trigger'] ?? 'load');
        if (!in_array($trigger, ['load', 'visible', 'manual'], true)) {
            $trigger = 'load';
        }
        $placeholder = (string) ($params['placeholder'] ?? '');
        $poll = (string) ($params['poll'] ?? '');
        $class = (string) ($params['class'] ?? 'celena-async');

        $attrs = 'class="' . e($class) . '" data-celena-async="' . e($url) . '" data-celena-trigger="' . e($trigger) . '"';
        if ($poll !== '') {
            $attrs .= ' data-celena-poll="' . e($poll) . '"';
        }
        if ($block !== '') {
            $attrs .= ' data-celena-block="' . e($block) . '"';
        }
        return '<div ' . $attrs . '>' . $placeholder . '</div>';
    }
}
