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

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

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

        $icons = [
            'info'    => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
            'success' => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><polyline points="9 12 11 14 15 10"/></svg>',
            'warning' => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
            'error'   => '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
        ];
        $icon = $icons[ $variant ] ?? $icons['info'];

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

        $title_html = $title ? '<strong class="jalpi-alert__title">' . $title . '</strong>' : '';
        $text_html  = $text  ? '<p class="jalpi-alert__text">'  . $text  . '</p>' : '';

        return '<div class="jalpi-el jalpi-alert jalpi-alert--' . esc_attr( $variant ) . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'] . '" role="alert"' . $a['id_attr'] . '>'
             . '<span class="jalpi-alert__icon" aria-hidden="true">' . $icon . '</span>'
             . '<div class="jalpi-alert__body">' . $title_html . $text_html . '</div>'
             . '</div>';
    }
}
