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

class Jalpi_Element_Feature_Card extends Jalpi_Element {
    public static function type(): string { return 'feature-card'; }

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

        $dim = fn( $v, $d = '' ) => ( $v !== '' && $v !== null ) ? (string) $v : $d;
        $col = fn( $v, $d = '' ) => ( $v !== '' && $v !== null ) ? (string) $v : $d;
        // Normalize unitless numbers to px ("1"→"1px", "0"→"0", "12px"→"12px")
        $px  = fn( $v, $d = '' ) => ( $v !== '' && $v !== null )
            ? ( preg_match('/^-?[\d.]+$/', (string)$v) ? ( (string)$v === '0' ? '0' : $v . 'px' ) : (string)$v )
            : $d;

        // Box settings
        $icon_view    = $content['view'] ?? 'default';
        $icon_pos     = $settings['fc_iconPosition']   ?? 'top';
        $align        = $settings['fc_align']          ?? 'center';
        $icon_spacing = $dim( $settings['fc_iconSpacing']   ?? '', '15px' );
        $cont_spacing = $dim( $settings['fc_contentSpacing'] ?? '', '0px' );
        $is_horiz     = in_array( $icon_pos, [ 'left', 'right' ], true );
        $flex_dir     = $icon_pos === 'left' ? 'row' : ( $icon_pos === 'right' ? 'row-reverse' : 'column' );

        // Box style
        $bg       = $col( $settings['fc_bg']      ?? '', '#ffffff' );

        // Auto-contrast: choose default text colors based on background luminance
        $bg_dark  = false;
        if ( preg_match( '/^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i', $bg, $m ) ) {
            $lum     = 0.299 * hexdec($m[1]) + 0.587 * hexdec($m[2]) + 0.114 * hexdec($m[3]);
            $bg_dark = $lum < 128;
        }
        $default_title_color = $bg_dark ? '#ffffff' : '#111827';
        $default_desc_color  = $bg_dark ? '#cccccc' : '#6b7280';
        $bd_type  = $settings['fc_bdType']         ?? 'none';
        $bd_color = $col( $settings['fc_bdColor']  ?? '', '#f3f4f6' );
        $bd_css   = '';
        if ( $bd_type && $bd_type !== 'none' ) {
            $bw_top    = $px( $settings['fc_bdw_top']    ?? '', '1px' );
            $bw_right  = $px( $settings['fc_bdw_right']  ?? '', '1px' );
            $bw_bottom = $px( $settings['fc_bdw_bottom'] ?? '', '1px' );
            $bw_left   = $px( $settings['fc_bdw_left']   ?? '', '1px' );
            $bd_css    = 'border:' . $bw_top . ' ' . $bd_type . ' ' . $bd_color . ';'
                       . 'border-width:' . $bw_top . ' ' . $bw_right . ' ' . $bw_bottom . ' ' . $bw_left . ';';
        }
        $br_top    = $px( $settings['fc_br_top']    ?? '', '12px' );
        $br_right  = $px( $settings['fc_br_right']  ?? '', '12px' );
        $br_bottom = $px( $settings['fc_br_bottom'] ?? '', '12px' );
        $br_left   = $px( $settings['fc_br_left']   ?? '', '12px' );
        $pad_top    = $px( $settings['fc_pad_top']    ?? '', '20px' );
        $pad_right  = $px( $settings['fc_pad_right']  ?? '', '16px' );
        $pad_bottom = $px( $settings['fc_pad_bottom'] ?? '', '20px' );
        $pad_left   = $px( $settings['fc_pad_left']   ?? '', '16px' );

        // Icon settings
        $icon_color   = $col( $settings['fc_icon_color']   ?? '', '#6366f1' );
        $icon_bg      = $col( $settings['fc_icon_bg']      ?? '', '#f0f4ff' );
        $icon_size    = $px( $settings['fc_icon_size']    ?? '', '48px' );
        $icon_pad     = $px( $settings['fc_icon_padding'] ?? '', '12px' );
        $icon_br      = $px( $settings['fc_icon_br']      ?? '', '12px' );

        // Title typography
        $title_color  = $col( $settings['fc_title_color']        ?? '', $default_title_color );
        $title_family = sanitize_text_field( $settings['fc_title_fontFamily']     ?? '' );
        $title_size   = $dim( $settings['fc_title_fontSize']      ?? '', '14px' );
        $title_weight = $settings['fc_title_fontWeight']          ?? '700';
        $title_css    = 'color:' . esc_attr($title_color) . ';font-size:' . esc_attr($title_size) . ';font-weight:' . esc_attr($title_weight ?: '700') . ';';
        if ( $title_family  ) $title_css .= 'font-family:'      . esc_attr($title_family) . ';';
        if ( !empty($settings['fc_title_fontStyle'])      && $settings['fc_title_fontStyle']      !== 'normal' ) $title_css .= 'font-style:'       . esc_attr($settings['fc_title_fontStyle']) . ';';
        if ( !empty($settings['fc_title_textTransform'])  && $settings['fc_title_textTransform']  !== 'none'   ) $title_css .= 'text-transform:'   . esc_attr($settings['fc_title_textTransform']) . ';';
        if ( !empty($settings['fc_title_textDecoration']) && $settings['fc_title_textDecoration'] !== 'none'   ) $title_css .= 'text-decoration:'  . esc_attr($settings['fc_title_textDecoration']) . ';';
        if ( !empty($settings['fc_title_lineHeight'])     ) $title_css .= 'line-height:'    . esc_attr($settings['fc_title_lineHeight']) . ';';
        if ( !empty($settings['fc_title_letterSpacing'])  ) $title_css .= 'letter-spacing:' . esc_attr($settings['fc_title_letterSpacing']) . ';';

        // Description typography
        $desc_color  = $col( $settings['fc_desc_color']        ?? '', $default_desc_color );
        $desc_family = sanitize_text_field( $settings['fc_desc_fontFamily']     ?? '' );
        $desc_size   = $dim( $settings['fc_desc_fontSize']      ?? '', '12px' );
        $desc_weight = $settings['fc_desc_fontWeight']          ?? '400';
        $desc_css    = 'color:' . esc_attr($desc_color) . ';font-size:' . esc_attr($desc_size) . ';font-weight:' . esc_attr($desc_weight ?: '400') . ';line-height:1.5;';
        if ( $desc_family  ) $desc_css .= 'font-family:'      . esc_attr($desc_family) . ';';
        if ( !empty($settings['fc_desc_fontStyle'])      && $settings['fc_desc_fontStyle']      !== 'normal' ) $desc_css .= 'font-style:'       . esc_attr($settings['fc_desc_fontStyle']) . ';';
        if ( !empty($settings['fc_desc_textTransform'])  && $settings['fc_desc_textTransform']  !== 'none'   ) $desc_css .= 'text-transform:'   . esc_attr($settings['fc_desc_textTransform']) . ';';
        if ( !empty($settings['fc_desc_textDecoration']) && $settings['fc_desc_textDecoration'] !== 'none'   ) $desc_css .= 'text-decoration:'  . esc_attr($settings['fc_desc_textDecoration']) . ';';
        if ( !empty($settings['fc_desc_lineHeight'])     ) $desc_css .= 'line-height:'    . esc_attr($settings['fc_desc_lineHeight']) . ';';
        if ( !empty($settings['fc_desc_letterSpacing'])  ) $desc_css .= 'letter-spacing:' . esc_attr($settings['fc_desc_letterSpacing']) . ';';

        // Emit CSS
        // Column mode: stretch so body fills full card width; icon uses align-self for horizontal placement.
        // Horizontal mode: flex-start so icon and body align at top.
        $box_css = $renderer->styles_to_css( $styles )
                 . 'display:flex;flex-direction:' . $flex_dir . ';align-items:' . ( $is_horiz ? 'flex-start' : 'stretch' ) . ';'
                 . 'text-align:' . esc_attr($align) . ';background:' . esc_attr($bg) . ';'
                 . 'border-radius:' . esc_attr($br_top) . ' ' . esc_attr($br_right) . ' ' . esc_attr($br_bottom) . ' ' . esc_attr($br_left) . ';'
                 . 'padding:' . esc_attr($pad_top) . ' ' . esc_attr($pad_right) . ' ' . esc_attr($pad_bottom) . ' ' . esc_attr($pad_left) . ';'
                 . $bd_css;

        // In column mode, icon aligns itself horizontally via align-self
        $icon_self = ! $is_horiz
            ? 'align-self:' . ( $align === 'center' ? 'center' : ( $align === 'right' ? 'flex-end' : 'flex-start' ) ) . ';'
            : '';
        if ( $icon_view === 'framed' ) {
            $icon_box_css = 'background:transparent;border:2px solid ' . esc_attr($icon_bg) . ';border-radius:' . esc_attr($icon_br) . ';padding:' . esc_attr($icon_pad) . ';';
        } elseif ( $icon_view === 'default' ) {
            $icon_box_css = 'background:transparent;padding:0;';
        } else { // stacked
            $icon_box_css = 'background:' . esc_attr($icon_bg) . ';border-radius:' . esc_attr($icon_br) . ';padding:' . esc_attr($icon_pad) . ';';
        }
        $icon_wrap_css = 'display:inline-flex;align-items:center;justify-content:center;flex-shrink:0;line-height:1;'
                       . $icon_self
                       . 'font-size:' . esc_attr($icon_size) . ';color:' . esc_attr($icon_color) . ';'
                       . $icon_box_css
                       . ( $is_horiz ? ( $icon_pos === 'right' ? 'margin-left:' : 'margin-right:' ) . esc_attr($icon_spacing) . ';' : 'margin-bottom:' . esc_attr($icon_spacing) . ';' );

        $renderer->add_css( $prefix . '{' . $box_css . '}' );
        $renderer->add_css( $prefix . ' .jalpi-feature__icon{' . $icon_wrap_css . '}' );
        $title_mb = $cont_spacing && $cont_spacing !== '0px' ? $cont_spacing : '6px';
        $renderer->add_css( $prefix . ' .jalpi-feature__title{' . $title_css . 'margin-bottom:' . esc_attr($title_mb) . ';}' );
        $renderer->add_css( $prefix . ' .jalpi-feature__text{' . $desc_css . 'margin:0;}' );

        // Build HTML
        $title    = esc_html( $content['title'] ?? '' );
        $text     = esc_html( $content['text']  ?? '' );
        $icon_html = $renderer->render_icon_value( $content['icon'] ?? '' );
        $link_url  = esc_url( $content['linkUrl']    ?? '' );
        $new_tab   = ! empty( $content['linkNewTab'] );

        $inner = '<div class="jalpi-el jalpi-feature jalpi-' . esc_attr($id) . $a['extra_cls'] . '"' . $a['id_attr'] . '>'
               . ( $icon_html ? '<div class="jalpi-feature__icon" aria-hidden="true">' . $icon_html . '</div>' : '' )
               . '<div class="jalpi-feature__body">'
               . ( $title ? '<h3 class="jalpi-feature__title">' . $title . '</h3>' : '' )
               . ( $text  ? '<p class="jalpi-feature__text">'   . $text  . '</p>'  : '' )
               . '</div>'
               . '</div>';

        if ( $link_url ) {
            $target = $new_tab ? ' target="_blank" rel="noopener noreferrer"' : '';
            return '<a href="' . $link_url . '"' . $target . ' style="display:block;text-decoration:none;color:inherit;">' . $inner . '</a>';
        }
        return $inner;
    }
}
