<?php
declare(strict_types=1);

namespace Celena\Core\Template;

/**
 * Реестр описаний всех конструкций шаблонизатора Celena.
 * Используется страницей /admin/docs/tags-panel (выезжающим drawer'ом
 * в редакторе шаблонов) и редактором шаблонов.
 *
 * Категории (group):
 *   - var     — переменные {var} и фильтры |raw |thumb |medium |large
 *   - control — управляющие конструкции: [if], [else if], [else], [foreach]
 *   - core    — встроенные inline-теги ядра
 *   - plugin  — теги от плагинов
 */
final class TagDocs
{
    /**
     * @var array<string, array{
     *   group:string,
     *   syntax:string,
     *   params:array<int,array{name:string,required:bool,key:string,example:string}>,
     *   example:string
     * }>
     */
    private const TAGS = [
        // ========== Переменные ==========
        'var' => [
            'group'  => 'var',
            'syntax' => '{name}',
            'params' => [],
            'example' => "{news.title}\n{user.name}\n{site.url}",
        ],
        'var_raw' => [
            'group'  => 'var',
            'syntax' => '{name|raw}',
            'params' => [],
            'example' => "{post.body|raw}",
        ],
        'var_thumb' => [
            'group'  => 'var',
            'syntax' => '{url|thumb}',
            'params' => [],
            'example' => "<img src=\"{news.cover|thumb}\" alt=\"\">\n<img src=\"{news.cover|medium}\">\n<img src=\"{news.cover|large}\">",
        ],

        // ========== Управление потоком ==========
        'if' => [
            'group'  => 'control',
            'syntax' => '[if EXPR] … [else if EXPR] … [else] … [/if]',
            'params' => [
                ['name' => 'EXPR', 'required' => true, 'key' => 'tags.if.p_expr', 'example' => '{var}, {a}={b}, {a}!="x", {n}>"5"'],
            ],
            'example' => "[if {user.role}=\"admin\"]\n  Привет, админ!\n[else if {user.id}>\"0\"]\n  Привет, пользователь.\n[else]\n  Гость.\n[/if]",
        ],
        'foreach' => [
            'group'  => 'control',
            'syntax' => '[foreach var="ARRAY" as="ITEM"] … [/foreach]',
            'params' => [
                ['name' => 'var', 'required' => true,  'key' => 'tags.foreach.p_var', 'example' => 'items, news, products'],
                ['name' => 'as',  'required' => false, 'key' => 'tags.foreach.p_as',  'example' => 'item (по умолчанию)'],
            ],
            'example' => "[foreach var=\"news\" as=\"n\"]\n  <article>\n    <h2>{n.title}</h2>\n    <p>{n.short}</p>\n    <small>{_index} из {_total}</small>\n  </article>\n[/foreach]",
        ],

        // ========== Списки контента ==========
        'news' => [
            'group'  => 'lists',
            'syntax' => '[news category="..." limit="N" sort="..." order="..."] … [/news]',
            'params' => [
                ['name' => 'category', 'required' => false, 'key' => 'tags.news.p_category', 'example' => 'world,tech (slug или id, через запятую)'],
                ['name' => 'limit',    'required' => false, 'key' => 'tags.news.p_limit',    'example' => '10 (по умолчанию)'],
                ['name' => 'offset',   'required' => false, 'key' => 'tags.news.p_offset',   'example' => '0'],
                ['name' => 'sort',     'required' => false, 'key' => 'tags.news.p_sort',     'example' => 'published_at | views | comments_count | id | title'],
                ['name' => 'order',    'required' => false, 'key' => 'tags.news.p_order',    'example' => 'desc (default) | asc'],
                ['name' => 'status',   'required' => false, 'key' => 'tags.news.p_status',   'example' => 'published (default) | draft | all'],
                ['name' => 'ids',      'required' => false, 'key' => 'tags.news.p_ids',      'example' => '12,18,42'],
                ['name' => 'as',       'required' => false, 'key' => 'tags.news.p_as',       'example' => 'item — даёт доступ через {item.title}'],
            ],
            'example' => "[news category=\"tech\" limit=\"5\" sort=\"views\"]\n  <article>\n    <a href=\"{url}\">\n      [if {cover}]<img src=\"{cover|medium}\" alt=\"{title}\">[/if]\n      <h3>{title}</h3>\n    </a>\n    <p>{short}</p>\n    <small>{date} · {views} просмотров</small>\n  </article>\n[/news]",
        ],
        'products' => [
            'group'  => 'lists',
            'syntax' => '[products category="..." limit="N" sort="..." order="..."] … [/products]',
            'params' => [
                ['name' => 'category', 'required' => false, 'key' => 'tags.products.p_category', 'example' => 'electronics,books (slug или id)'],
                ['name' => 'limit',    'required' => false, 'key' => 'tags.products.p_limit',    'example' => '12 (по умолчанию)'],
                ['name' => 'offset',   'required' => false, 'key' => 'tags.products.p_offset',   'example' => '0'],
                ['name' => 'sort',     'required' => false, 'key' => 'tags.products.p_sort',     'example' => 'id | price | title | created_at | updated_at | stock'],
                ['name' => 'order',    'required' => false, 'key' => 'tags.products.p_order',    'example' => 'desc (default) | asc'],
                ['name' => 'ids',      'required' => false, 'key' => 'tags.products.p_ids',      'example' => '7,9,15'],
                ['name' => 'include_inactive', 'required' => false, 'key' => 'tags.products.p_include_inactive', 'example' => '1 — показать скрытые'],
                ['name' => 'as',       'required' => false, 'key' => 'tags.products.p_as',       'example' => 'item'],
            ],
            'example' => "[products category=\"electronics\" limit=\"6\" sort=\"price\" order=\"asc\"]\n  <a class=\"card\" href=\"{url}\">\n    [if {cover}]<img src=\"{cover|medium}\" alt=\"{title}\">[/if]\n    <h3>{title}</h3>\n    <div class=\"price\">{price_fmt} $</div>\n  </a>\n[/products]",
        ],

        // ========== Inline-теги ядра ==========
        'include' => [
            'group'   => 'core',
            'syntax'  => '{include file="PATH"}',
            'params'  => [
                ['name' => 'file', 'required' => true, 'key' => 'tags.include.p_file', 'example' => '_partials/head.tpl'],
            ],
            'example' => '{include file="_partials/head.tpl"}',
        ],
        'lang' => [
            'group'   => 'core',
            'syntax'  => '{lang key="KEY"}',
            'params'  => [
                ['name' => 'key', 'required' => true, 'key' => 'tags.lang.p_key', 'example' => 'admin.save'],
            ],
            'example' => '<button>{lang key="admin.save"}</button>',
        ],
        'csrf' => [
            'group'   => 'core',
            'syntax'  => '{csrf [format="meta"]}',
            'params'  => [
                ['name' => 'format', 'required' => false, 'key' => 'tags.csrf.p_format', 'example' => 'field (default) | meta'],
            ],
            'example' => "<form method=\"post\">\n  {csrf}\n  <button>OK</button>\n</form>\n\n<head>\n  {csrf format=\"meta\"}\n</head>",
        ],
        'async' => [
            'group'   => 'core',
            'syntax'  => '{async block="NAME" url="URL" trigger="..."}',
            'params'  => [
                ['name' => 'block',       'required' => true,  'key' => 'tags.async.p_block',       'example' => 'latest_news'],
                ['name' => 'url',         'required' => false, 'key' => 'tags.async.p_url',         'example' => '/api/blocks/latest-news'],
                ['name' => 'trigger',     'required' => false, 'key' => 'tags.async.p_trigger',     'example' => 'load | visible | manual'],
                ['name' => 'placeholder', 'required' => false, 'key' => 'tags.async.p_placeholder', 'example' => '<em>Загрузка…</em>'],
            ],
            'example' => '{async block="latest_news" url="/api/blocks/latest-news" trigger="visible"}',
        ],
        'icon' => [
            'group'   => 'core',
            'syntax'  => '{icon name="NAME" size="20"}',
            'params'  => [
                ['name' => 'name',   'required' => true,  'key' => 'tags.icon.p_name',   'example' => 'settings, bell, cart, news, …'],
                ['name' => 'size',   'required' => false, 'key' => 'tags.icon.p_size',   'example' => '20 (по умолчанию)'],
                ['name' => 'class',  'required' => false, 'key' => 'tags.icon.p_class',  'example' => 'icon (по умолчанию)'],
                ['name' => 'stroke', 'required' => false, 'key' => 'tags.icon.p_stroke', 'example' => '1.75 (по умолчанию)'],
            ],
            'example' => "{icon name=\"settings\" size=\"22\"}\n{icon name=\"bell\" size=\"18\" class=\"notif-ico\"}",
        ],
        'plugin_assets' => [
            'group'   => 'core',
            'syntax'  => '{plugin_assets}',
            'params'  => [],
            'example' => "<head>\n  …\n  {plugin_assets}\n</head>",
        ],
        'gdpr_banner' => [
            'group'   => 'core',
            'syntax'  => '{gdpr_banner}',
            'params'  => [],
            'example' => "<body>\n  …\n  {gdpr_banner}\n</body>",
        ],

        // ========== Теги плагинов ==========
        'price' => [
            'group'   => 'plugin',
            'syntax'  => '{price amount="N" currency="$"}',
            'params'  => [
                ['name' => 'amount',   'required' => true,  'key' => 'tags.price.p_amount',   'example' => '1234.5'],
                ['name' => 'currency', 'required' => false, 'key' => 'tags.price.p_currency', 'example' => '$ (по умолчанию)'],
            ],
            'example' => '<div class="price">{price amount="{product.price}" currency="$"}</div>',
        ],
    ];

    /**
     * @return array<int, array{
     *   name:string,
     *   group:string,
     *   syntax:string,
     *   label:string,
     *   desc:string,
     *   params:array<int,array{name:string,required:bool,desc:string,example:string}>,
     *   example:string
     * }>
     */
    public static function all(): array
    {
        $out = [];
        $tr = \Celena\Core\Kernel::container()->make(\Celena\Core\I18n\Translator::class);
        foreach (self::TAGS as $name => $meta) {
            $params = [];
            foreach ($meta['params'] as $p) {
                $params[] = [
                    'name'     => $p['name'],
                    'required' => $p['required'],
                    'desc'     => $tr->translate($p['key']),
                    'example'  => $p['example'],
                ];
            }
            $out[] = [
                'name'    => $name,
                'group'   => $meta['group'],
                'syntax'  => $meta['syntax'],
                'label'   => $tr->translate('tags.' . $name . '.label'),
                'desc'    => $tr->translate('tags.' . $name . '.desc'),
                'params'  => $params,
                'example' => $meta['example'],
            ];
        }
        return $out;
    }
}
