<?php
/**
 * Social icons — real network glyphs + per-item network/URL list.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;


use AuraBuilder\Support\Json;
use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class SocialIconsWidget extends WidgetBase {

	public function get_type(): string {
		return 'social_icons';
	}

	public function get_title(): string {
		return 'Ícones sociais';
	}

	public function get_icon(): string {
		return 'social';
	}

	/** @return array<string, array{label:string,color:string,glyph:string}> */
	public static function networks(): array {
		return array(
			'facebook'  => array( 'label' => 'Facebook', 'color' => '#1877f2', 'glyph' => 'f' ),
			'instagram' => array( 'label' => 'Instagram', 'color' => '#e4405f', 'glyph' => 'ig' ),
			'youtube'   => array( 'label' => 'YouTube', 'color' => '#ff0000', 'glyph' => '▶' ),
			'whatsapp'  => array( 'label' => 'WhatsApp', 'color' => '#25d366', 'glyph' => 'wa' ),
			'linkedin'  => array( 'label' => 'LinkedIn', 'color' => '#0a66c2', 'glyph' => 'in' ),
			'x'         => array( 'label' => 'X (Twitter)', 'color' => '#111111', 'glyph' => '𝕏' ),
			'twitter'   => array( 'label' => 'Twitter', 'color' => '#1da1f2', 'glyph' => '𝕏' ),
			'tiktok'    => array( 'label' => 'TikTok', 'color' => '#010101', 'glyph' => '♪' ),
			'telegram'  => array( 'label' => 'Telegram', 'color' => '#229ed9', 'glyph' => 'tg' ),
			'pinterest' => array( 'label' => 'Pinterest', 'color' => '#e60023', 'glyph' => 'p' ),
			'email'     => array( 'label' => 'E-mail', 'color' => '#64748b', 'glyph' => '@' ),
			'website'   => array( 'label' => 'Site', 'color' => '#0f172a', 'glyph' => '🌐' ),
		);
	}

	public function get_defaults(): array {
		return array(
			'items' => Json::encode(
				array(
					array( 'network' => 'facebook', 'url' => 'https://facebook.com', 'label' => '' ),
					array( 'network' => 'instagram', 'url' => 'https://instagram.com', 'label' => '' ),
					array( 'network' => 'youtube', 'url' => 'https://youtube.com', 'label' => '' ),
				)
			),
			'align'      => 'left',
			'shape'      => 'circle',
			'show_label' => '0',
			'size'       => '40',
		);
	}

	public function sanitize_settings( array $settings ): array {
		$align = in_array( ( $settings['align'] ?? '' ), array( 'left', 'center', 'right' ), true )
			? (string) $settings['align']
			: 'left';
		$shape = sanitize_key( (string) ( $settings['shape'] ?? 'circle' ) );
		if ( ! in_array( $shape, array( 'circle', 'rounded', 'square' ), true ) ) {
			$shape = 'circle';
		}
		$flag = static function ( $v, string $d = '0' ): string {
			if ( $v === null || $v === '' ) {
				return $d;
			}
			return ( $v === true || $v === 1 || $v === '1' || $v === 'true' || $v === 'yes' ) ? '1' : '0';
		};
		return array(
			'items'      => $this->sanitize_items( (string) ( $settings['items'] ?? '' ) ),
			'align'      => $align,
			'shape'      => $shape,
			'show_label' => $flag( $settings['show_label'] ?? null, '0' ),
			'size'       => (string) max( 28, min( 72, (int) ( $settings['size'] ?? 40 ) ) ),
		);
	}

	private function sanitize_items( string $raw ): string {
		$items = self::parse_items( $raw );
		$nets  = self::networks();
		$clean = array();
		foreach ( $items as $it ) {
			$net = sanitize_key( (string) ( $it['network'] ?? 'website' ) );
			if ( ! isset( $nets[ $net ] ) ) {
				// Map free-text labels to networks.
				$guess = sanitize_title( (string) ( $it['network'] ?? $it['label'] ?? '' ) );
				$net   = isset( $nets[ $guess ] ) ? $guess : 'website';
			}
			$url = (string) ( $it['url'] ?? '' );
			if ( $net === 'email' && $url !== '' && ! str_starts_with( $url, 'mailto:' ) && str_contains( $url, '@' ) ) {
				$url = 'mailto:' . sanitize_email( str_replace( 'mailto:', '', $url ) );
			} else {
				$url = esc_url_raw( $url );
			}
			$clean[] = array(
				'network' => $net,
				'url'     => $url !== '' ? $url : '#',
				'label'   => sanitize_text_field( (string) ( $it['label'] ?? '' ) ),
			);
		}
		if ( count( $clean ) > 20 ) {
			$clean = array_slice( $clean, 0, 20 );
		}
		$json = Json::encode( $clean );
		return is_string( $json ) ? $json : '[]';
	}

	/**
	 * @return list<array{network:string,url:string,label:string}>
	 */
	public static function parse_items( string $raw ): array {
		$raw = trim( $raw );
		if ( $raw === '' ) {
			return array();
		}
		if ( str_starts_with( $raw, '[' ) ) {
			$decoded = json_decode( $raw, true );
			if ( is_array( $decoded ) ) {
				$out = array();
				foreach ( $decoded as $row ) {
					if ( is_string( $row ) ) {
						$p = explode( '|', $row, 2 );
						$out[] = array(
							'network' => strtolower( trim( $p[0] ) ),
							'url'     => trim( $p[1] ?? '#' ),
							'label'   => '',
						);
						continue;
					}
					if ( is_array( $row ) ) {
						$out[] = array(
							'network' => (string) ( $row['network'] ?? $row['name'] ?? 'website' ),
							'url'     => (string) ( $row['url'] ?? '#' ),
							'label'   => (string) ( $row['label'] ?? '' ),
						);
					}
				}
				return $out;
			}
		}
		$out   = array();
		$lines = preg_split( '/\r\n|\r|\n/', $raw ) ?: array();
		foreach ( $lines as $line ) {
			$line = trim( $line );
			if ( $line === '' ) {
				continue;
			}
			$p = explode( '|', $line, 2 );
			$out[] = array(
				'network' => strtolower( trim( $p[0] ) ),
				'url'     => trim( $p[1] ?? '#' ),
				'label'   => '',
			);
		}
		return $out;
	}

	public function render( Node $node, array $context = array() ): string {
		$s     = $node->settings;
		$items = self::parse_items( (string) ( $s['items'] ?? '' ) );
		$nets  = self::networks();
		if ( ! $items ) {
			return ! empty( $context['editor'] )
				? '<div class="ab-social ab-empty">Ícones sociais — adicione redes</div>'
				: '';
		}
		$align  = esc_attr( (string) ( $s['align'] ?? 'left' ) );
		$shape  = esc_attr( (string) ( $s['shape'] ?? 'circle' ) );
		$size   = (int) ( $s['size'] ?? 40 );
		$labels = ( $s['show_label'] ?? '0' ) === '1';

		$html = '<div class="ab-social ab-social--' . $shape . ' ab-social--' . $align . '" style="--ab-social-size:' . esc_attr( (string) $size ) . 'px" data-ab-social="1">';
		foreach ( $items as $item ) {
			$net_key = sanitize_key( (string) ( $item['network'] ?? 'website' ) );
			$meta    = $nets[ $net_key ] ?? $nets['website'];
			// Fuzzy match free labels.
			if ( ! isset( $nets[ $net_key ] ) ) {
				foreach ( $nets as $k => $m ) {
					if ( strcasecmp( $m['label'], (string) $item['network'] ) === 0 || strcasecmp( $k, $net_key ) === 0 ) {
						$net_key = $k;
						$meta    = $m;
						break;
					}
				}
			}
			$url   = (string) ( $item['url'] ?? '#' );
			$label = (string) ( $item['label'] ?? '' );
			if ( $label === '' ) {
				$label = $meta['label'];
			}
			$color = esc_attr( $meta['color'] );
			$glyph = $meta['glyph'];
			$html .= '<a class="ab-social__item ab-social__item--' . esc_attr( $net_key ) . '" href="' . esc_url( $url !== '' ? $url : '#' ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr( $label ) . '" style="--ab-social-color:' . $color . '">';
			$html .= '<span class="ab-social__badge" aria-hidden="true">' . esc_html( $glyph ) . '</span>';
			if ( $labels ) {
				$html .= '<span class="ab-social__label">' . esc_html( $label ) . '</span>';
			}
			$html .= '</a>';
		}
		$html .= '</div>';
		return $html;
	}
}
