<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Frontend;

defined('ABSPATH') || exit;

/**
 * Registers a wide page template for block themes so a locator isn't squeezed
 * into the theme's narrow content column (620px in Twenty Twenty-Four). The
 * template widens the constrained content area; the locator block, which
 * supports wide/full alignment, can still break out further.
 *
 * Registered from the plugin via register_block_template() (WP 6.7+) so no theme
 * files are modified and it survives theme updates. Appears in the page editor's
 * "Template" panel as "Wide Page (Store Locator)".
 */
final class LocatorWideTemplate
{
    private const NAME = 'cliq-store-locator//wide-page';
    private const CONTENT_WIDTH = '1280px';

    public function register(): void
    {
        // register() is called from Plugin::bootUiLibrary which already runs on
        // `init`, so register the template DIRECTLY — a nested add_action('init')
        // is queued too late to fire, which is why the wide template disappeared.
        $this->registerTemplate();
        // Core's wp_get_post_content_block_attributes() (and other consumers) index
        // get_block_templates() results numerically, but plugin-registered templates
        // can come back keyed by name — yielding "Undefined array key 0" + null
        // parse_blocks() warnings. Normalise to a plain list.
        add_filter('get_block_templates', [$this, 'reindexTemplates'], 99);
    }

    /**
     * @param mixed $templates
     *
     * @return mixed
     */
    public function reindexTemplates($templates)
    {
        if (is_array($templates) && $templates !== [] && array_keys($templates) !== range(0, count($templates) - 1)) {
            return array_values($templates);
        }

        return $templates;
    }

    public function registerTemplate(): void
    {
        if (! function_exists('register_block_template')) {
            return;
        }

        register_block_template(self::NAME, [
            'title' => __('Wide Page (Store Locator)', 'cliq-store-locator'),
            'description' => __('Full-width content area for pages that embed the store locator.', 'cliq-store-locator'),
            'content' => $this->markup(),
            'post_types' => ['page'],
        ]);
    }

    private function markup(): string
    {
        $theme = get_template(); // active block theme slug (e.g. twentytwentyfour)
        $width = self::CONTENT_WIDTH;

        // The style attributes below are core's own block serialisation for
        // wp:spacer — this string has to match what the block editor writes or
        // the template stops parsing. Not our markup to restyle.
        $template = '<!-- wp:template-part {"slug":"header","theme":"%1$s","tagName":"header"} /-->

<!-- wp:group {"tagName":"main","layout":{"type":"constrained","contentSize":"%2$s"}} -->
<main class="wp-block-group">
<!-- wp:spacer {"height":"40px"} -->
<div style="height:40px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->

<!-- wp:post-title {"level":1} /-->

<!-- wp:post-content {"layout":{"type":"constrained","contentSize":"%2$s"}} /-->

<!-- wp:spacer {"height":"60px"} -->
<div style="height:60px" aria-hidden="true" class="wp-block-spacer"></div>
<!-- /wp:spacer -->
</main>
<!-- /wp:group -->

<!-- wp:template-part {"slug":"footer","theme":"%1$s","tagName":"footer"} /-->';

        return sprintf($template, $theme, $width);
    }
}
