<?php
/**
 * BlockRegistry — holds the set of available block types.
 *
 * Built-in blocks ship as PHP templates in lib/blocks/. Other plugins
 * register their own blocks (with a 'render' callback) by hooking
 * 'content_register_blocks':
 *
 *   Hook::addAction('content_register_blocks', function ($registry) {
 *       $registry::register('contact-form', [
 *           'label'  => 'Contact Form',
 *           'group'  => 'Forms',
 *           'fields' => [ ['key'=>'formId','type'=>'select','label'=>'Form',
 *                          'options' => FormsAPI::optionList()] ],
 *           'render' => [FormsAPI::class, 'renderBlock'],
 *           'defaults' => ['formId' => 0],
 *       ]);
 *   });
 *
 * A block definition:
 *   label    string   human label in the palette
 *   group    string   palette grouping (optional, default 'Content')
 *   fields   array    field descriptors for the editor (see builder.js)
 *   defaults array    default props for a new block
 *   tpl      string   absolute path to a PHP template (built-in blocks)
 *   render   callable function(array $props): string (plugin blocks)
 */
class BlockRegistry {

    protected static array $blocks = [];

    public static function register(string $type, array $def): void {
        $def['group']    = $def['group']    ?? 'Content';
        $def['fields']   = $def['fields']   ?? [];
        $def['defaults'] = $def['defaults'] ?? [];
        self::$blocks[$type] = $def;
    }

    public static function registerDefaults(string $blockDir): void {
        $blockDir = rtrim($blockDir, '/');

        self::register('heading', [
            'label'  => 'Heading', 'group' => 'Content',
            'tpl'    => "$blockDir/heading.php",
            'fields' => [
                ['key'=>'text','type'=>'text','label'=>'Text'],
                ['key'=>'level','type'=>'select','label'=>'Level',
                 'options'=>[['v'=>'1','l'=>'H1'],['v'=>'2','l'=>'H2'],['v'=>'3','l'=>'H3'],['v'=>'4','l'=>'H4']]],
            ],
            'defaults' => ['text'=>'Heading', 'level'=>'2'],
        ]);

        self::register('paragraph', [
            'label'  => 'Paragraph', 'group' => 'Content',
            'tpl'    => "$blockDir/paragraph.php",
            'fields' => [['key'=>'text','type'=>'textarea','label'=>'Text']],
            'defaults' => ['text'=>'Write something…'],
        ]);

        self::register('image', [
            'label'  => 'Image', 'group' => 'Content',
            'tpl'    => "$blockDir/image.php",
            'fields' => [
                ['key'=>'src','type'=>'image','label'=>'Image URL'],
                ['key'=>'alt','type'=>'text','label'=>'Alt text'],
                ['key'=>'width','type'=>'select','label'=>'Width',
                 'options'=>[['v'=>'full','l'=>'Full'],['v'=>'wide','l'=>'Wide'],['v'=>'normal','l'=>'Normal']]],
            ],
            'defaults' => ['src'=>'', 'alt'=>'', 'width'=>'full'],
        ]);

        self::register('button', [
            'label'  => 'Button', 'group' => 'Content',
            'tpl'    => "$blockDir/button.php",
            'fields' => [
                ['key'=>'text','type'=>'text','label'=>'Label'],
                ['key'=>'href','type'=>'text','label'=>'Link URL'],
                ['key'=>'style','type'=>'select','label'=>'Style',
                 'options'=>[['v'=>'primary','l'=>'Primary'],['v'=>'secondary','l'=>'Secondary']]],
            ],
            'defaults' => ['text'=>'Click me', 'href'=>'#', 'style'=>'primary'],
        ]);

        self::register('columns', [
            'label'  => 'Two Columns', 'group' => 'Layout',
            'tpl'    => "$blockDir/columns.php",
            'fields' => [],  // edited by nesting blocks inside each column in the canvas
            'defaults' => ['cols'=>[['blocks'=>[]],['blocks'=>[]]]],
        ]);

        self::register('html', [
            'label'  => 'Raw HTML', 'group' => 'Advanced',
            'tpl'    => "$blockDir/html.php",
            'fields' => [['key'=>'html','type'=>'textarea','label'=>'HTML (trusted roles only)']],
            'defaults' => ['html'=>'<!-- raw html -->'],
            'perm'   => 'content.publish',
        ]);

        self::register('post-list', [
            'label'  => 'Post List', 'group' => 'Dynamic',
            'tpl'    => "$blockDir/post-list.php",
            'fields' => [
                ['key'=>'postType','type'=>'text','label'=>'Post type','placeholder'=>'post'],
                ['key'=>'taxonomy','type'=>'text','label'=>'Taxonomy (optional)','placeholder'=>'category'],
                ['key'=>'term','type'=>'text','label'=>'Term slug (optional)'],
                ['key'=>'limit','type'=>'text','label'=>'Limit','placeholder'=>'6'],
            ],
            'defaults' => ['postType'=>'post','taxonomy'=>'','term'=>'','limit'=>'6'],
        ]);

        /* ---------- Section blocks (richer, prebuilt layouts) ---------- */

        self::register('hero', [
            'label'  => 'Hero', 'group' => 'Sections',
            'tpl'    => "$blockDir/hero.php",
            'fields' => [
                ['key'=>'pad','type'=>'select','label'=>'Section spacing','options'=>[['v'=>'compact','l'=>'Compact'],['v'=>'normal','l'=>'Normal'],['v'=>'spacious','l'=>'Spacious']]],
                
                ['key'=>'layout','type'=>'select','label'=>'Layout',
                 'options'=>[['v'=>'split','l'=>'Split (image + text)'],['v'=>'banner','l'=>'Banner (text over image)']]],
                ['key'=>'eyebrow','type'=>'text','label'=>'Eyebrow (small label above heading)'],
                ['key'=>'heading','type'=>'text','label'=>'Heading'],
                ['key'=>'subheading','type'=>'textarea','label'=>'Subheading'],
                ['key'=>'btnText','type'=>'text','label'=>'Button label'],
                ['key'=>'btnHref','type'=>'text','label'=>'Button link'],
                ['key'=>'btn2Text','type'=>'text','label'=>'Second button label (optional)'],
                ['key'=>'btn2Href','type'=>'text','label'=>'Second button link'],
                ['key'=>'image','type'=>'image','label'=>'Image'],
                ['key'=>'mediaSide','type'=>'select','label'=>'Image side (split only)',
                 'options'=>[['v'=>'left','l'=>'Left'],['v'=>'right','l'=>'Right']]],
                ['key'=>'overlay','type'=>'select','label'=>'Image darkness (banner only)',
                 'options'=>[['v'=>'light','l'=>'Light'],['v'=>'medium','l'=>'Medium'],['v'=>'dark','l'=>'Dark']]],
                ['key'=>'height','type'=>'select','label'=>'Height (banner only)',
                 'options'=>[['v'=>'normal','l'=>'Normal'],['v'=>'tall','l'=>'Tall'],['v'=>'short','l'=>'Short']]],
            ],
            'defaults' => ['pad'=>'normal','layout'=>'split','eyebrow'=>'','heading'=>'Your big headline',
                           'subheading'=>'A short supporting sentence that sells the idea.',
                           'btnText'=>'Get started','btnHref'=>'#','btn2Text'=>'','btn2Href'=>'',
                           'image'=>'','mediaSide'=>'left','overlay'=>'medium','height'=>'normal'],
        ]);

        self::register('icon-grid', [
            'label'  => 'Icon box grid', 'group' => 'Sections',
            'tpl'    => "$blockDir/icon-grid.php",
            'fields' => [
                ['key'=>'pad','type'=>'select','label'=>'Section spacing','options'=>[['v'=>'compact','l'=>'Compact'],['v'=>'normal','l'=>'Normal'],['v'=>'spacious','l'=>'Spacious']]],
                
                ['key'=>'eyebrow','type'=>'text','label'=>'Eyebrow'],
                ['key'=>'heading','type'=>'text','label'=>'Section heading'],
                ['key'=>'bg','type'=>'select','label'=>'Background',
                 'options'=>[['v'=>'white','l'=>'White'],['v'=>'page','l'=>'Page'],['v'=>'tint','l'=>'Tint'],['v'=>'tint2','l'=>'Tint 2'],['v'=>'dark','l'=>'Dark']]],
                ['key'=>'cols','type'=>'select','label'=>'Columns',
                 'options'=>[['v'=>'3','l'=>'Three'],['v'=>'4','l'=>'Four'],['v'=>'2','l'=>'Two']]],
                ['key'=>'items','type'=>'repeater','label'=>'Boxes',
                 'item'=>[
                    ['key'=>'icon','type'=>'text','label'=>'Icon (star, heart, bolt, shield, leaf, gift, check, clock, box, truck)','placeholder'=>'star'],
                    ['key'=>'title','type'=>'text','label'=>'Title'],
                    ['key'=>'text','type'=>'textarea','label'=>'Text'],
                    ['key'=>'linkText','type'=>'text','label'=>'Link label (optional)'],
                    ['key'=>'linkHref','type'=>'text','label'=>'Link URL'],
                 ]],
            ],
            'defaults' => ['pad'=>'normal','eyebrow'=>'','heading'=>'What we offer','bg'=>'white','cols'=>'3','items'=>[
                ['icon'=>'star','title'=>'Quality','text'=>'Describe this feature.','linkText'=>'','linkHref'=>''],
                ['icon'=>'box','title'=>'Reliable','text'=>'Describe this feature.','linkText'=>'','linkHref'=>''],
                ['icon'=>'truck','title'=>'Fast','text'=>'Describe this feature.','linkText'=>'','linkHref'=>''],
            ]],
        ]);

        self::register('image-grid', [
            'label'  => 'Image box grid', 'group' => 'Sections',
            'tpl'    => "$blockDir/image-grid.php",
            'fields' => [
                ['key'=>'pad','type'=>'select','label'=>'Section spacing','options'=>[['v'=>'compact','l'=>'Compact'],['v'=>'normal','l'=>'Normal'],['v'=>'spacious','l'=>'Spacious']]],
                
                ['key'=>'eyebrow','type'=>'text','label'=>'Eyebrow'],
                ['key'=>'heading','type'=>'text','label'=>'Section heading'],
                ['key'=>'bg','type'=>'select','label'=>'Background',
                 'options'=>[['v'=>'tint','l'=>'Tint'],['v'=>'page','l'=>'Page'],['v'=>'white','l'=>'White'],['v'=>'tint2','l'=>'Tint 2'],['v'=>'dark','l'=>'Dark']]],
                ['key'=>'cols','type'=>'select','label'=>'Columns',
                 'options'=>[['v'=>'3','l'=>'Three'],['v'=>'4','l'=>'Four'],['v'=>'2','l'=>'Two']]],
                ['key'=>'items','type'=>'repeater','label'=>'Cards',
                 'item'=>[
                    ['key'=>'image','type'=>'image','label'=>'Image'],
                    ['key'=>'title','type'=>'text','label'=>'Title'],
                    ['key'=>'text','type'=>'textarea','label'=>'Text'],
                    ['key'=>'href','type'=>'text','label'=>'Link (optional)'],
                 ]],
            ],
            'defaults' => ['pad'=>'normal','eyebrow'=>'','heading'=>'Gallery','bg'=>'tint','cols'=>'3','items'=>[
                ['image'=>'','title'=>'Item one','text'=>'Short caption.','href'=>''],
                ['image'=>'','title'=>'Item two','text'=>'Short caption.','href'=>''],
                ['image'=>'','title'=>'Item three','text'=>'Short caption.','href'=>''],
            ]],
        ]);

        self::register('cta', [
            'label'  => 'Call to action', 'group' => 'Sections',
            'tpl'    => "$blockDir/cta.php",
            'fields' => [
                ['key'=>'pad','type'=>'select','label'=>'Section spacing','options'=>[['v'=>'compact','l'=>'Compact'],['v'=>'normal','l'=>'Normal'],['v'=>'spacious','l'=>'Spacious']]],
                
                ['key'=>'heading','type'=>'text','label'=>'Heading'],
                ['key'=>'text','type'=>'textarea','label'=>'Text'],
                ['key'=>'btnText','type'=>'text','label'=>'Button label'],
                ['key'=>'btnHref','type'=>'text','label'=>'Button link'],
            ],
            'defaults' => ['pad'=>'normal','heading'=>'Ready to start?','text'=>'Join us today.','btnText'=>'Sign up','btnHref'=>'#'],
        ]);

        self::register('testimonial', [
            'label'  => 'Testimonial', 'group' => 'Sections',
            'tpl'    => "$blockDir/testimonial.php",
            'fields' => [
                ['key'=>'pad','type'=>'select','label'=>'Section spacing','options'=>[['v'=>'compact','l'=>'Compact'],['v'=>'normal','l'=>'Normal'],['v'=>'spacious','l'=>'Spacious']]],
                
                ['key'=>'quote','type'=>'textarea','label'=>'Quote'],
                ['key'=>'author','type'=>'text','label'=>'Author'],
                ['key'=>'role','type'=>'text','label'=>'Role / company'],
                ['key'=>'avatar','type'=>'image','label'=>'Avatar (optional)'],
            ],
            'defaults' => ['pad'=>'normal','quote'=>'This product changed how we work.','author'=>'Jane Doe','role'=>'CEO, Example Co','avatar'=>''],
        ]);
    }

    public static function all(): array {
        return self::$blocks;
    }

    public static function get(string $type): ?array {
        return self::$blocks[$type] ?? null;
    }

    /** Palette payload for the JS editor (no callbacks — not serializable). */
    public static function paletteJson(): string {
        $out = [];
        foreach (self::$blocks as $type => $def) {
            $out[$type] = [
                'label'    => $def['label'],
                'group'    => $def['group'],
                'fields'   => $def['fields'],
                'defaults' => $def['defaults'],
                'nest'     => $type === 'columns',
            ];
        }
        return json_encode($out);
    }
}
