<?php

declare(strict_types=1);

namespace Builder\Seo\Support;

use Builder\Core\Foundation\Definition\Field;

/**
 * Static registry for SEO compound field definitions.
 *
 * Other packages can call SeoField::extend() in their service provider boot()
 * to inject additional subfields into every Field::seo() instance.
 * The extra subfields are passed to the FieldSeoInput Vue component via
 * field.fields meta and will be rendered when DynamicField becomes
 * available from @builder/ui.
 */
final class SeoField
{
    /** @var list<Field> */
    private static array $extraFields = [];

    public static function extend(Field $field): void
    {
        self::$extraFields[] = $field;
    }

    /**
     * Returns the serialized field definitions for all SEO subfields.
     * Called at field-macro invocation time so any extend() calls made
     * before first use are captured.
     *
     * @return list<array<string, mixed>>
     */
    public static function getFields(): array
    {
        $fields = [
            Field::text('title')
                ->label((string) __('seo::seo.fields.title'))
                ->hint((string) __('seo::seo.hints.title'))
                ->rules(['nullable', 'string', 'max:70']),

            Field::textarea('description')
                ->label((string) __('seo::seo.fields.description'))
                ->hint((string) __('seo::seo.hints.description'))
                ->rules(['nullable', 'string', 'max:170']),

            Field::select('robots')
                ->label((string) __('seo::seo.fields.robots'))
                ->options([
                    'index' => (string) __('seo::seo.robots.index'),
                    'noindex' => (string) __('seo::seo.robots.noindex'),
                    'nofollow' => (string) __('seo::seo.robots.nofollow'),
                    'noindex,nofollow' => (string) __('seo::seo.robots.noindex_nofollow'),
                    'noarchive' => (string) __('seo::seo.robots.noarchive'),
                    'nosnippet' => (string) __('seo::seo.robots.nosnippet'),
                ])
                ->default('index'),
        ];

        foreach (self::$extraFields as $field) {
            $fields[] = $field;
        }

        return array_map(fn (Field $f): array => $f->toArray(), $fields);
    }

    /**
     * @internal Resets extended fields. For test isolation only.
     */
    public static function reset(): void
    {
        self::$extraFields = [];
    }
}
