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

class Jalpi_Element_Social_Icons extends Jalpi_Element {
    public static function type(): string { return 'social-icons'; }

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

        $icon_style   = in_array( $content['iconStyle'] ?? 'circle', [ 'circle','square','minimal' ], true ) ? $content['iconStyle'] : 'circle';
        $icon_size    = Jalpi_Sanitizer::sanitize_dimension( $content['iconSize'] ?? '40px' ) ?: '40px';
        $align        = in_array( $content['align'] ?? 'center', [ 'left','center','right' ], true ) ? $content['align'] : 'center';
        $custom_color = Jalpi_Sanitizer::sanitize_color( $content['color'] ?? '' );

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

        $platform_colors = [
            'facebook'  => '#1877f2', 'instagram' => '#e4405f', 'twitter'   => '#000000',
            'linkedin'  => '#0a66c2', 'youtube'   => '#ff0000', 'tiktok'    => '#010101',
            'pinterest' => '#e60023', 'github'    => '#181717', 'email'     => '#ea4335',
            'whatsapp'  => '#25d366',
        ];
        $platform_labels = [
            'facebook'  => 'f',  'instagram' => '◎', 'twitter'   => 'X',
            'linkedin'  => 'in', 'youtube'   => '▶', 'tiktok'    => '♪',
            'pinterest' => 'P',  'github'    => '◉', 'email'     => '@',
            'whatsapp'  => 'W',
        ];

        $icons_html = '';
        foreach ( $items as $item ) {
            $platform   = sanitize_key( $item['platform'] ?? 'facebook' );
            $url        = esc_url( $item['url'] ?? '#' );
            $bg         = $custom_color ?: ( $platform_colors[ $platform ] ?? '#6b7280' );
            $letter     = $platform_labels[ $platform ] ?? strtoupper( $platform[0] ?? '?' );
            $label      = ucfirst( $platform );
            $icons_html .= '<a href="' . $url . '" class="jalpi-social__icon jalpi-social__icon--' . esc_attr( $icon_style ) . '" '
                         . 'aria-label="' . esc_attr( $label ) . '" '
                         . 'style="--jalpi-si-bg:' . esc_attr( $bg ) . ';--jalpi-si-size:' . esc_attr( $icon_size ) . ';" '
                         . 'target="_blank" rel="noopener noreferrer">'
                         . esc_html( $letter )
                         . '</a>';
        }

        $cls = 'jalpi-el jalpi-social-icons jalpi-social-icons--' . esc_attr( $align ) . ' jalpi-' . esc_attr( $id ) . $a['extra_cls'];
        return '<div class="' . $cls . '"' . $a['id_attr'] . '>' . $icons_html . '</div>';
    }
}
