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

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

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id       = sanitize_html_class( $node['id'] ?? '' );
        $content  = $node['content'] ?? [];
        $styles   = $node['styles']  ?? [];
        $items    = (array) ( $content['items']    ?? [] );
        $tab_style = in_array( $content['tabStyle'] ?? 'underline', [ 'underline','boxed','pill' ], true )
                     ? $content['tabStyle'] : 'underline';
        $a        = $renderer->get_css_attrs( $node );

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

        $cls = 'jalpi-el jalpi-tabs jalpi-tabs--' . esc_attr( $tab_style ) . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'];

        $nav   = '';
        $panes = '';
        foreach ( $items as $idx => $item ) {
            /* translators: %d: tab number */
            $label   = esc_html( $item['label']   ?? sprintf( __( 'Tab %d', 'jalpi-page-builder' ), $idx + 1 ) );
            $text    = wp_kses_post( $item['content'] ?? '' );
            $active  = 0 === $idx;
            $nav   .= '<button class="jalpi-tabs__btn' . ( $active ? ' is-active' : '' ) . '"'
                    . ' role="tab" aria-selected="' . ( $active ? 'true' : 'false' ) . '">'
                    . $label . '</button>';
            $panes .= '<div class="jalpi-tabs__pane"' . ( $active ? '' : ' hidden' ) . '>' . $text . '</div>';
        }

        return '<div class="' . $cls . '"' . $a['id_attr'] . '>'
             . '<div class="jalpi-tabs__nav" role="tablist">' . $nav . '</div>'
             . '<div class="jalpi-tabs__body">' . $panes . '</div>'
             . '</div>';
    }
}
