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

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

    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 );

        $target_date = sanitize_text_field( $content['targetDate'] ?? '' );
        $label       = esc_html( $content['label'] ?? '' );

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

        $units_html = '';
        $unit_labels = [
            'days'  => esc_html__( 'Days', 'jalpi-page-builder' ),
            'hours' => esc_html__( 'Hours', 'jalpi-page-builder' ),
            'mins'  => esc_html__( 'Mins', 'jalpi-page-builder' ),
            'secs'  => esc_html__( 'Secs', 'jalpi-page-builder' ),
        ];
        foreach ( $unit_labels as $key => $lbl ) {
            $units_html .= '<div class="jalpi-cd__unit">'
                         . '<span class="jalpi-cd__' . $key . '">00</span>'
                         . '<span class="jalpi-cd__label">' . $lbl . '</span>'
                         . '</div>';
        }

        $cls = 'jalpi-el jalpi-countdown jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        $target_attr = $target_date ? ' data-target="' . esc_attr( $target_date ) . '"' : '';
        return '<div class="' . $cls . '"' . $a['id_attr'] . $target_attr . '>'
             . ( $label ? '<div class="jalpi-countdown__label">' . $label . '</div>' : '' )
             . '<div class="jalpi-countdown__timer">' . $units_html . '</div>'
             . '</div>';
    }
}
