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

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

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

        // Resolve items array — support new format and legacy single-counter
        if ( ! empty( $content['items'] ) && is_array( $content['items'] ) ) {
            $items = $content['items'];
        } else {
            // Legacy: single-counter saved as flat fields
            $items = [ $content ];
        }

        // Dimension helper
        $dim = static function( $v ) {
            $v = trim( sanitize_text_field( (string) $v ) );
            if ( $v === '' ) return '';
            if ( preg_match( '/^-?[\d.]+(px|em|rem|%|vh|vw)$/', $v ) ) return $v;
            if ( preg_match( '/^-?[\d.]+$/', $v ) ) return $v . 'px';
            return '';
        };
        $col = static function( $v ) {
            $v = sanitize_text_field( (string) $v );
            return preg_match( '/^#[0-9a-fA-F]{3,8}$|^rgba?\(/', $v ) ? $v : '';
        };
        $sep_map = [ 'dot' => '.', 'comma' => ',', 'space' => ' ' ];

        // Outer wrapper CSS — flex row so multiple counters sit side by side
        $item_gap = $dim( $settings['cnt_gap'] ?? '' ) ?: '24px';
        $wrap_css = 'display:flex;flex-direction:row;flex-wrap:wrap;justify-content:center;align-items:flex-start;gap:' . esc_attr( $item_gap ) . ';' . $renderer->styles_to_css( $styles );
        $bg_n     = $col( $settings['cnt_bg_normal'] ?? '' );
        if ( $bg_n ) $wrap_css .= 'background:' . $bg_n . ';';
        $bd_type  = sanitize_key( $settings['cnt_bdType'] ?? '' );
        if ( $bd_type && $bd_type !== 'default' && $bd_type !== 'none' ) {
            $bd_w   = $dim( $settings['cnt_bdw_top'] ?? '' ) ?: '1px';
            $bd_col = $col( $settings['cnt_bdColor'] ?? '' ) ?: '#e5e7eb';
            $wrap_css .= 'border:' . $bd_w . ' ' . $bd_type . ' ' . $bd_col . ';';
        } elseif ( $bd_type === 'none' ) {
            $wrap_css .= 'border:none;';
        }
        $br_tl = $dim( $settings['cnt_br_top']    ?? '' );
        if ( $br_tl ) {
            $br_tr = $dim( $settings['cnt_br_right']  ?? '' ) ?: $br_tl;
            $br_br = $dim( $settings['cnt_br_bottom'] ?? '' ) ?: $br_tl;
            $br_bl = $dim( $settings['cnt_br_left']   ?? '' ) ?: $br_tl;
            $wrap_css .= 'border-radius:' . "$br_tl $br_tr $br_br $br_bl" . ';overflow:hidden;';
        }
        $pad_t = $dim( $settings['cnt_pad_top']    ?? '' );
        $pad_r = $dim( $settings['cnt_pad_right']  ?? '' );
        $pad_b = $dim( $settings['cnt_pad_bottom'] ?? '' );
        $pad_l = $dim( $settings['cnt_pad_left']   ?? '' );
        if ( $pad_t || $pad_r || $pad_b || $pad_l ) {
            $wrap_css .= 'padding:' . ( $pad_t ?: '16px' ) . ' ' . ( $pad_r ?: '16px' ) . ' ' . ( $pad_b ?: '16px' ) . ' ' . ( $pad_l ?: '16px' ) . ';';
        }
        $renderer->add_css( '.jalpi-el' . $prefix . '{' . $wrap_css . '}' );

        // Hover background
        $bg_h = $col( $settings['cnt_bg_hover'] ?? '' );
        if ( $bg_h ) $renderer->add_css( '.jalpi-el' . $prefix . ':hover{background:' . $bg_h . ';}' );

        // Item layout — Title Position / Alignment / Gap / Number Position
        $title_pos   = sanitize_key( $settings['cnt_titlePos']   ?? 'bottom' );
        $title_align = sanitize_key( $settings['cnt_titleAlign'] ?? 'center' );
        $title_gap   = $dim( $settings['cnt_titleGap'] ?? '' ) ?: '6px';
        $num_pos     = sanitize_key( $settings['cnt_numPos'] ?? 'center' );

        $flex_dir_map = [ 'top' => 'column-reverse', 'bottom' => 'column', 'left' => 'row-reverse', 'right' => 'row' ];
        $item_flex    = $flex_dir_map[ $title_pos ] ?? 'column';
        $item_align   = $title_align === 'left' ? 'flex-start' : ( $title_align === 'right' ? 'flex-end' : 'center' );
        $item_css     = 'display:flex;flex-direction:' . $item_flex . ';align-items:' . $item_align . ';gap:' . esc_attr( $title_gap ) . ';';
        $renderer->add_css( $prefix . ' .jalpi-counter__item{' . $item_css . '}' );

        // Number text-align
        $num_text_align_map = [ 'left' => 'left', 'right' => 'right', 'justify' => 'justify', 'center' => 'center' ];
        $num_ta = $num_text_align_map[ $num_pos ] ?? 'center';
        $renderer->add_css( $prefix . ' .jalpi-counter__number{text-align:' . $num_ta . ';}' );

        // Shared number + title styles (applied via class — same for all items)
        $num_css = '';
        $nc = $col( $settings['cnt_num_color'] ?? '' );       if ( $nc ) $num_css .= 'color:' . $nc . ';';
        $nf = $dim( $settings['cnt_num_fontSize'] ?? '' );    if ( $nf ) $num_css .= 'font-size:' . $nf . ';';
        $nw = sanitize_text_field( $settings['cnt_num_fontWeight'] ?? '' );
        if ( $nw ) $num_css .= 'font-weight:' . $nw . ';';
        if ( $num_css ) $renderer->add_css( $prefix . ' .jalpi-counter__number{' . $num_css . '}' );

        $ttl_css = '';
        $tc = $col( $settings['cnt_title_color'] ?? '' );       if ( $tc ) $ttl_css .= 'color:' . $tc . ';';
        $tf = $dim( $settings['cnt_title_fontSize'] ?? '' );    if ( $tf ) $ttl_css .= 'font-size:' . $tf . ';';
        $tw = sanitize_text_field( $settings['cnt_title_fontWeight'] ?? '' );
        if ( $tw ) $ttl_css .= 'font-weight:' . $tw . ';';
        if ( $ttl_css ) $renderer->add_css( $prefix . ' .jalpi-counter__label{' . $ttl_css . '}' );

        $renderer->set_needs_js( 'counter' );

        $items_html = '';
        foreach ( $items as $item ) {
            $start    = esc_attr( $item['startNumber'] ?? '0' );
            $end      = esc_attr( $item['endNumber']   ?? $item['number'] ?? '100' );
            $num_pfx  = esc_html( $item['prefix']  ?? '' );
            $num_sfx  = esc_html( $item['suffix']  ?? '' );
            $duration = absint( $item['duration']  ?? 2000 );
            $thou_sep = (bool) ( $item['thousandSep'] ?? false );
            $sep_char = $item['separator'] ?? 'dot';
            $title    = esc_html( $item['title'] ?? $item['label'] ?? '' );
            $sep      = $thou_sep ? ( $sep_map[ $sep_char ] ?? ',' ) : '';

            $items_html .= '<div class="jalpi-counter__item">'
                         . '<span class="jalpi-counter__number"'
                         .   ' data-start="'    . $start    . '"'
                         .   ' data-end="'      . $end      . '"'
                         .   ' data-duration="' . $duration . '"'
                         .   ' data-sep="'      . esc_attr( $sep ) . '"'
                         .   ' data-prefix="'   . esc_attr( $num_pfx ) . '"'
                         .   ' data-suffix="'   . esc_attr( $num_sfx ) . '"'
                         . '>'
                         . ( $num_pfx ? '<span class="jalpi-counter__prefix">' . $num_pfx . '</span>' : '' )
                         . '<span class="jalpi-counter__val">' . esc_html( $end ) . '</span>'
                         . ( $num_sfx ? '<span class="jalpi-counter__suffix">' . $num_sfx . '</span>' : '' )
                         . '</span>'
                         . ( $title ? '<span class="jalpi-counter__label">' . $title . '</span>' : '' )
                         . '</div>';
        }

        return '<div class="jalpi-el jalpi-counter jalpi-' . esc_attr( $id ) . $a['extra_cls'] . '"' . $a['id_attr'] . '>'
             . $items_html
             . '</div>';
    }
}
