<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Element_Image_Box extends Jalpi_Element {
    public static function type(): string { return 'image-box'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id      = sanitize_html_class( $node['id'] ?? '' );
        $content = $node['content'] ?? [];
        $styles  = $node['styles']  ?? [];
        $a       = $renderer->get_css_attrs( $node );

        $base_css = $renderer->styles_to_css( $styles );
        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{' . $base_css . '}' );

        $url      = esc_url(  $content['url']           ?? '' );
        $alt      = esc_attr( $content['alt']           ?? '' );
        $title    = esc_html( $content['title']         ?? '' );
        $desc     = wp_kses_post( $content['description'] ?? '' );
        $tag      = in_array( $content['titleTag'] ?? 'h3', [ 'h2','h3','h4','h5','h6' ], true ) ? $content['titleTag'] : 'h3';
        $pos      = in_array( $content['imagePosition'] ?? 'top', [ 'top','left','right' ], true ) ? $content['imagePosition'] : 'top';
        $link_url = esc_url( $content['linkUrl'] ?? '' );

        $img_html = $url
            ? '<img src="' . $url . '" alt="' . $alt . '" class="jalpi-imgbox__img" loading="lazy">'
            : '';

        $cls = 'jalpi-el jalpi-imgbox jalpi-imgbox--' . esc_attr( $pos ) . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        $inner = ( $img_html ? '<div class="jalpi-imgbox__media">' . $img_html . '</div>' : '' )
               . '<div class="jalpi-imgbox__body">'
               .   ( $title ? '<' . $tag . ' class="jalpi-imgbox__title">' . $title . '</' . $tag . '>' : '' )
               .   ( $desc  ? '<p class="jalpi-imgbox__desc">' . $desc . '</p>' : '' )
               . '</div>';

        if ( $link_url ) {
            $inner = '<a href="' . $link_url . '" class="jalpi-imgbox__link">' . $inner . '</a>';
        }

        return '<div class="' . $cls . '"' . $a['id_attr'] . '>' . $inner . '</div>';
    }
}
