<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_Store_Hero_Block {

    const STYLE_HANDLE = 'aieo-dmm-category-extras';

    private static $registered = false;

    public static function register() {
        if (self::$registered) { return; }
        self::$registered = true;
        add_action('init', array(__CLASS__, 'register_block'));
        add_shortcode('aieo_store_hero', array(__CLASS__, 'shortcode'));
    }

    public static function register_block() {
        
        
        
        if (!wp_style_is(self::STYLE_HANDLE, 'registered')) {
            $css_rel  = 'assets/css/aieo-dmm-category-extras.css';
            $css_path = defined('AIEO_DIR') ? AIEO_DIR . $css_rel : '';
            $css_ver  = ($css_path && file_exists($css_path)) ? (string) filemtime($css_path) : (defined('AIEO_VERSION') ? AIEO_VERSION : '1.0');
            wp_register_style(self::STYLE_HANDLE, AIEO_URI . $css_rel, array(), $css_ver);
        }
        register_block_type('aieo/store-hero', array(
            'api_version'     => 3,
            'title'           => __('AIEO Store Hero', 'ai-eshop-optimizer'),
            'description'     => __('Shop-page header hero in the category-hero style (centred image, title, horizontal line). Listing title, heading and description come from the bound location. Auto-resolves on a store page, or set a location slug.', 'ai-eshop-optimizer'),
            'category'        => 'widgets',
            'icon'            => 'store',
            'keywords'        => array('store', 'shop', 'hero', 'header', 'location'),
            'supports'        => array('align' => array('wide', 'full'), 'anchor' => true),
            'attributes'      => array(
                'locationSlug' => array('type' => 'string', 'default' => ''),
            ),
            'uses_context'    => array('postId'),
            'style'           => self::STYLE_HANDLE,
            'render_callback' => array(__CLASS__, 'render'),
        ));
    }

    public static function shortcode($atts) {
        $atts = shortcode_atts(array('location' => ''), $atts, 'aieo_store_hero');
        return self::render(array('locationSlug' => (string) $atts['location']));
    }

    public static function render($attrs, $content = '', $block = null) {
        if (!class_exists('AIEO_Google_Reviews_Helpers')) { return ''; }
        $attrs = wp_parse_args(is_array($attrs) ? $attrs : array(), array('locationSlug' => ''));
        $loc   = AIEO_Google_Reviews_Helpers::resolve_single($attrs['locationSlug'], $block);
        if (!$loc) { return ''; }

        $title    = trim((string) ($loc['listing_title'] ?? ''));
        $headline = trim((string) ($loc['hero_heading'] ?? ''));
        $desc     = trim((string) ($loc['hero_description'] ?? ''));
        $image    = trim((string) ($loc['image_url'] ?? ''));

        
        
        if ($title === '') {
            $title = (string) ($loc['label'] ?? '');
        }
        if ($title === '' && is_singular()) {
            $title = (string) get_the_title(get_queried_object_id());
        }
        if ($title === '' && $headline === '' && $desc === '') { return ''; }

        $img_html = '';
        if ($image !== '') {
            $img_html = '<img class="aieo-category-hero__img" src="' . esc_url($image) . '" alt="' . esc_attr($title) . '" loading="eager" />';
        }

        
        
        
        $classes = array('aieo-category-hero', 'aieo-category-hero--default', 'aieo-store-hero');
        if ($headline === '') { $classes[] = 'aieo-category-hero--no-headline'; }
        if ($desc === '')     { $classes[] = 'aieo-category-hero--no-description'; }

        $wrap_class = function_exists('get_block_wrapper_attributes')
            ? get_block_wrapper_attributes(array('class' => implode(' ', $classes)))
            : 'class="' . esc_attr(implode(' ', $classes)) . '"';

        ob_start();
        ?>
<section <?php echo $wrap_class; ?> data-template="default">
    <header class="aieo-category-hero__title">
        <h1><?php echo esc_html($title); ?></h1>
    </header>
    <div class="aieo-category-hero__image<?php echo $img_html ? '' : ' aieo-category-hero__image--placeholder'; ?>">
        <?php echo wp_kses($img_html, array('img' => array('src' => array(), 'alt' => array(), 'class' => array(), 'loading' => array(), 'width' => array(), 'height' => array()))); ?>
    </div>
    <?php if ($headline !== '' || $desc !== '') : ?>
        <div class="aieo-category-hero__body">
            <?php if ($headline !== '') : ?>
                <div class="aieo-category-hero__headline"><?php echo wp_kses_post($headline); ?></div>
            <?php endif; ?>
            <?php if ($desc !== '') : ?>
                <div class="aieo-category-hero__description"><?php echo wp_kses_post(wpautop($desc)); ?></div>
            <?php endif; ?>
        </div>
    <?php endif; ?>
    <hr class="aieo-category-hero__divider" />
</section>
        <?php
        $html = (string) ob_get_clean();
        self::print_band_style_once();
        return $html;
    }

    
    private static function print_band_style_once() {
        static $done = false;
        if ($done) { return; }
        $done = true;
        echo '<style id="aieo-store-band-css">@media(min-width:768px){'
            
            . '.ff-store-band{max-width:clamp(360px,calc(59vw - 60px),1180px)!important;margin-left:auto!important;margin-right:auto!important}'
            
            
            
            
            
            . '.ff-store-row{display:grid!important;grid-template-columns:3fr 1fr 3fr 1fr 3fr;gap:0!important;align-items:start}'
            . '.ff-store-row>.wp-block-column{min-width:0;max-width:none;margin:0;flex:none}'
            . '.ff-store-row>.wp-block-column:nth-of-type(1){grid-column:1}'
            . '.ff-store-row>.wp-block-column:nth-of-type(2){grid-column:3}'
            . '.ff-store-row>.wp-block-column:nth-of-type(3){grid-column:5}'
            
            
            . '.ff-store-row .aieo-loc-hours-block .aieo-loc__hours{justify-content:end}'
            
            
            . '.ff-store-row>.wp-block-column:nth-of-type(2)>.wp-block-heading{text-align:center!important}'
            . '.ff-store-row>.wp-block-column:nth-of-type(3)>.wp-block-heading{text-align:right!important}'
            . '}</style>'; 
    }
}
