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

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

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

        // Style-tab is authoritative; content values are legacy fallbacks only
        $size         = sanitize_text_field( $styles['iconSize']   ?? $content['size']  ?? '48px' );
        $color        = self::sanitize_color_val( $styles['color'] ?? 'currentColor' );
        $align        = sanitize_text_field( $styles['textAlign']  ?? 'center' );
        $icon_padding = sanitize_text_field( $styles['iconPadding'] ?? '' );
        $rotate       = sanitize_text_field( $styles['iconRotate']  ?? '' );
        $view         = sanitize_key( $content['view'] ?? 'default' );
        // Secondary Color (style tab) with legacy viewColor fallback for backwards compat
        $view_color   = self::sanitize_color_val( $styles['iconBoxColor'] ?? $content['viewColor'] ?? '#e8e8e8' );
        $border_radius= sanitize_text_field( $content['borderRadius'] ?? '50%' );
        $link         = ! empty( $content['link'] ) ? esc_url( $content['link'] ) : '';
        $new_tab      = ! empty( $content['newTab'] );

        // Hover state colors
        $color_hover     = self::sanitize_color_val( $styles['iconColorHover']    ?? '' );
        $box_color_hover = self::sanitize_color_val( $styles['iconBoxColorHover'] ?? '' );

        $inner_style = 'display:inline-flex;align-items:center;line-height:1;font-size:' . esc_attr( $size ) . ';color:' . esc_attr( $color ) . ';';
        if ( $rotate ) $inner_style .= 'transform:rotate(' . esc_attr( $rotate ) . ');';
        $icon_html = '<span class="jalpi-icon-inner" style="' . $inner_style . '">' . $renderer->render_icon_value( $content['icon'] ?? 'star' ) . '</span>';

        $has_view  = in_array( $view, [ 'stacked', 'framed' ], true );

        // Box auto-sizes from icon + padding (no explicit width/height -- matches Elementor)
        $pad_css = $icon_padding ? 'padding:' . esc_attr( $icon_padding ) . ';' : '';

        if ( $view === 'stacked' ) {
            $box_style = 'display:inline-flex;align-items:center;justify-content:center;line-height:1;' . $pad_css . 'background:' . esc_attr( $view_color ) . ';border-radius:' . esc_attr( $border_radius ) . ';';
            $icon_html = '<span class="jalpi-icon-box" style="' . $box_style . '">' . $icon_html . '</span>';
        } elseif ( $view === 'framed' ) {
            $box_style = 'display:inline-flex;align-items:center;justify-content:center;line-height:1;' . $pad_css . 'border:2px solid ' . esc_attr( $view_color ) . ';border-radius:' . esc_attr( $border_radius ) . ';';
            $icon_html = '<span class="jalpi-icon-box" style="' . $box_style . '">' . $icon_html . '</span>';
        }

        // Wrap in link
        if ( $link ) {
            $target    = $new_tab ? ' target="_blank" rel="noopener noreferrer"' : '';
            $icon_html = '<a href="' . $link . '"' . $target . ' style="display:inline-block;line-height:0;">' . $icon_html . '</a>';
        }

        // Build container CSS -- strip all custom icon-* keys before the generic helper
        $generic_styles = array_diff_key( $styles, array_flip( [ 'iconSize','iconPadding','iconRotate','iconBoxColor','iconBoxColorHover','iconColorHover','color','textAlign' ] ) );
        $container_css  = 'display:block;text-align:' . esc_attr( $align ) . ';';
        $container_css .= $renderer->styles_to_css( $generic_styles );
        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{' . $container_css . '}' );

        // SVG dimensions -- size is set via font-size on .jalpi-icon-inner; also constrain SVG element dimensions
        $renderer->add_css( '.jalpi-el.jalpi-' . $id . ' svg{width:' . esc_attr( $size ) . ';height:' . esc_attr( $size ) . ';}' );

        // Hover rules -- !important overrides the inline color on .jalpi-icon-inner
        if ( $color_hover ) {
            $renderer->add_css( '.jalpi-el.jalpi-' . $id . ':hover .jalpi-icon-inner{color:' . esc_attr( $color_hover ) . ' !important;}' );
        }
        if ( $box_color_hover && $view === 'stacked' ) {
            $renderer->add_css( '.jalpi-el.jalpi-' . $id . ':hover .jalpi-icon-box{background:' . esc_attr( $box_color_hover ) . ' !important;}' );
        }
        if ( $box_color_hover && $view === 'framed' ) {
            $renderer->add_css( '.jalpi-el.jalpi-' . $id . ':hover .jalpi-icon-box{border-color:' . esc_attr( $box_color_hover ) . ' !important;}' );
        }

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

    private static function sanitize_color_val( string $val ): string {
        if ( preg_match( '/^#[0-9a-fA-F]{3,8}$/', $val ) ) return $val;
        if ( preg_match( '/^rgba?\([\d,.\s%]+\)$/', $val )  ) return $val;
        if ( preg_match( '/^hsla?\([\d,.\s%]+\)$/', $val )  ) return $val;
        if ( preg_match( '/^[a-z]{2,30}$/', $val )           ) return $val;
        return '#f0f0f0';
    }
}
