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

class Jalpi_Element_Logo extends Jalpi_Element {
    public static function type(): string { return 'logo'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id      = sanitize_html_class( $node['id'] ?? '' );
        $content = $node['content'] ?? [];
        $styles  = $node['styles']  ?? [];
        $src     = $renderer->tags( $renderer->get_current_post_id() )->resolve_url( $content['url'] ?? '' );
        $alt     = $renderer->tags( $renderer->get_current_post_id() )->resolve_attr( $content['alt'] ?? '' );
        $width   = sanitize_text_field( $content['width'] ?? 'auto' );
        $a       = $renderer->get_css_attrs( $node );

        if ( ! $src ) {
            return '';
        }

        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{display:block;' . $renderer->styles_to_css( $styles ) . '}' );
        $renderer->add_css( '.jalpi-el.jalpi-' . $id . ' img{width:' . esc_attr( $width ) . ';height:auto;display:block;}' );

        $lazy    = Jalpi_Settings::get( 'performance', 'enable_lazy_loading', '1' ) ? ' loading="lazy"' : '';
        $img     = '<img src="' . $src . '" alt="' . $alt . '"' . $lazy . '>';
        $cls     = 'jalpi-el jalpi-logo jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        $id_attr = $a['id_attr'];

        if ( ! empty( $content['linkUrl'] ) ) {
            $target = ! empty( $content['newTab'] ) ? ' target="_blank" rel="noopener noreferrer"' : '';
            return '<div class="' . $cls . '"' . $id_attr . '><a href="' . $renderer->tags( $renderer->get_current_post_id() )->resolve_url( $content['linkUrl'] ) . '"' . $target . '>' . $img . '</a></div>';
        }

        return '<div class="' . $cls . '"' . $id_attr . '>' . $img . '</div>';
    }
}
