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

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

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

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

        $track_bg    = $col( $settings['pb_track_bg']       ?? '', '#e5e7eb' );
        $track_h     = $dim( $settings['pb_track_height']   ?? '', '8px' );
        $track_r     = $dim( $settings['pb_track_radius']   ?? '', '999px' );
        $title_color = $col( $settings['pb_title_color']    ?? '', '' );
        $title_fs    = $dim( $settings['pb_title_fontSize'] ?? '', '' );
        $title_fw    = sanitize_text_field( $settings['pb_title_fontWeight'] ?? '' );
        $pct_color   = $col( $settings['pb_pct_color']      ?? '', '' );
        $pct_fs      = $dim( $settings['pb_pct_fontSize']   ?? '', '' );
        $inner_color = $col( $settings['pb_inner_color']    ?? '', '' );
        $inner_fs    = $dim( $settings['pb_inner_fontSize'] ?? '', '' );

        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{display:block;' . $renderer->styles_to_css( $styles ) . '}' );
        $renderer->add_css( $pfx . ' .jalpi-progress__track{height:' . $track_h . ';background:' . $track_bg . ';border-radius:' . $track_r . ';overflow:hidden;}' );
        $renderer->add_css( $pfx . ' .jalpi-progress__fill{border-radius:' . $track_r . ';}' );

        // Helper to build CSS from prefixed typography settings
        $typo_css = function( string $sp ) use ( $settings, $dim, $col ): string {
            $css = '';
            $color = $col( $settings[ $sp . '_color' ] ?? '', '' );
            if ( $color ) $css .= 'color:' . $color . ';';
            $ff = sanitize_text_field( $settings[ $sp . '_fontFamily' ]    ?? '' ); if ( $ff ) $css .= "font-family:$ff;";
            $fs = $dim( $settings[ $sp . '_fontSize' ]     ?? '', '' );               if ( $fs ) $css .= "font-size:$fs;";
            $fw = sanitize_text_field( $settings[ $sp . '_fontWeight' ]    ?? '' ); if ( $fw ) $css .= "font-weight:$fw;";
            $tt = sanitize_text_field( $settings[ $sp . '_textTransform' ] ?? '' ); if ( $tt ) $css .= "text-transform:$tt;";
            $fi = sanitize_text_field( $settings[ $sp . '_fontStyle' ]     ?? '' ); if ( $fi ) $css .= "font-style:$fi;";
            $td = sanitize_text_field( $settings[ $sp . '_textDecoration' ]?? '' ); if ( $td ) $css .= "text-decoration:$td;";
            $lh = $dim( $settings[ $sp . '_lineHeight' ]   ?? '', '' );               if ( $lh ) $css .= "line-height:$lh;";
            $ls = $dim( $settings[ $sp . '_letterSpacing' ]?? '', '' );               if ( $ls ) $css .= "letter-spacing:$ls;";
            $ws = $dim( $settings[ $sp . '_wordSpacing' ]  ?? '', '' );               if ( $ws ) $css .= "word-spacing:$ws;";
            // Text shadow
            $sh = $dim( $settings[ $sp . '_textShadowH' ]    ?? '', '' );
            $sv = $dim( $settings[ $sp . '_textShadowV' ]    ?? '', '' );
            $sb = $dim( $settings[ $sp . '_textShadowBlur' ] ?? '', '' );
            $sc = $col( $settings[ $sp . '_textShadowColor' ]?? '', '' );
            if ( $sc ) $css .= 'text-shadow:' . ( $sh ?: '0px' ) . ' ' . ( $sv ?: '0px' ) . ' ' . ( $sb ?: '0px' ) . ' ' . $sc . ';';
            return $css;
        };

        $title_css = $typo_css( 'pb_title' );
        if ( $title_color ) $title_css .= 'color:' . $title_color . ';'; // color picker overrides typo color
        if ( $title_css ) $renderer->add_css( $pfx . ' .jalpi-progress__title{' . $title_css . '}' );

        $pct_css = $typo_css( 'pb_pct' );
        if ( $pct_color ) $pct_css .= 'color:' . $pct_color . ';';
        if ( $pct_css ) $renderer->add_css( $pfx . ' .jalpi-progress__pct{' . $pct_css . '}' );

        $inner_css = $typo_css( 'pb_inner' );
        if ( $inner_color ) $inner_css .= 'color:' . $inner_color . ';';
        if ( $inner_css ) $renderer->add_css( $pfx . ' .jalpi-progress__inner{' . $inner_css . '}' );

        $allowed_tags = [ 'h1','h2','h3','h4','h5','h6','div','span' ];
        $rows = '';
        foreach ( (array) $items as $item ) {
            $title      = esc_html( $item['title'] ?? $item['label'] ?? '' );
            $title_tag  = in_array( $item['titleTag'] ?? 'h3', $allowed_tags, true ) ? $item['titleTag'] : 'h3';
            $show_title = isset( $item['showTitle'] )      ? (bool) $item['showTitle']      : true;
            $pct        = min( 100, max( 0, intval( $item['percentage'] ?? 0 ) ) );
            $show_pct   = isset( $item['showPercentage'] ) ? (bool) $item['showPercentage'] : true;
            $inner_text = esc_html( $item['innerText'] ?? '' );
            $fill_color = esc_attr( $col( $item['color'] ?? '', '#6366f1' ) );

            $head_html = '';
            if ( $show_title && $title ) {
                $head_html .= '<' . $title_tag . ' class="jalpi-progress__title">' . $title . '</' . $title_tag . '>';
            }
            if ( $show_pct ) {
                $head_html .= '<span class="jalpi-progress__pct">' . $pct . '%</span>';
            }

            $rows .= '<div class="jalpi-progress__row">'
                   . ( $head_html ? '<div class="jalpi-progress__head">' . $head_html . '</div>' : '' )
                   . '<div class="jalpi-progress__track" role="progressbar" aria-valuenow="' . $pct . '" aria-valuemin="0" aria-valuemax="100">'
                   .   '<div class="jalpi-progress__fill" data-pct="' . $pct . '" style="width:0%;background:' . $fill_color . '"></div>'
                   . '</div>'
                   . ( $inner_text ? '<span class="jalpi-progress__inner">' . $inner_text . '</span>' : '' )
                   . '</div>';
        }

        $renderer->set_needs_js( 'progress' );

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