<?php
/**
 * Unified [social_login] shortcode; assets only when shortcode runs.
 *
 * @package WP_PowerSuite\OAuth
 */

namespace WP_PowerSuite\OAuth;

use WP_PowerSuite\OAuth\UI\ButtonStyleHelper;
use WP_PowerSuite\OAuth\UI\SocialLoginFormGroup;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class SocialShortcodeService {

	/** @var array<string, callable> provider_slug => function(array $a): string */
	private static array $button_renderers = [];

	private static bool $shortcode_registered = false;

	private static bool $used_this_request   = false;

	/**
	 * @param callable(array<string, string>): string $button_html_cb
	 */
	public static function register( string $provider_slug, $button_html_cb ): void {
		$provider_slug = sanitize_key( $provider_slug );
		if ( $provider_slug === '' ) {
			return;
		}
		if ( is_callable( $button_html_cb ) ) {
			self::$button_renderers[ $provider_slug ] = $button_html_cb;
		}
		if ( ! self::$shortcode_registered ) {
			self::$shortcode_registered = true;
			add_shortcode( 'social_login', [ self::class, 'render' ] );
		}
	}

	/**
	 * @param array<string, string>|\string $atts
	 */
	public static function render( $atts ): string {
		$defaults = [
			'providers'     => 'google,facebook,github',
			'redirect'      => '',
			'type'          => 'button',
			'style'         => '',
			'size'          => 'medium',
			'show_text'     => '1',
			'width'         => '',
			'width_custom'  => '',
			'align'         => '',
			'c_align'       => '',
			'display'       => '',
		];
		$atts  = is_array( $atts ) ? $atts : [];
		$args  = shortcode_atts( $defaults, $atts, 'social_login' );
		$slugs = array_filter( array_map( 'trim', array_map( 'sanitize_key', explode( ',', (string) ( $args['providers'] ?? '' ) ) ) ) );
		if ( $slugs === [] ) {
			return '';
		}

		$c_align = (string) ( $args['c_align'] ?? '' );
		if ( $c_align === '' ) {
			$c_align = (string) ( $args['align'] ?? 'center' );
		}
		$c_align = ButtonStyleHelper::sanitizeAlign( $c_align );

		$opt = [
			'redirect'     => (string) $args['redirect'],
			'type'         => (string) $args['type'],
			'style'        => (string) $args['style'],
			'size'         => (string) $args['size'],
			'show_text'    => ( (string) $args['show_text'] === '1' || (string) $args['show_text'] === 'true' || (string) $args['show_text'] === 'yes' ),
			'width'        => (string) $args['width'],
			'width_custom' => (string) ( $args['width_custom'] ?? '' ),
			'align'        => (string) ( $args['align'] ?? '' ),
		];
		$display_in = (string) ( $args['display'] ?? '' );
		if ( $display_in !== '' ) {
			$d = ButtonStyleHelper::sanitizeDisplay( $display_in );
			if ( 'icon' === $d ) {
				$opt['type']       = 'icon';
				$opt['show_text']  = false;
			} else {
				$opt['type']      = (string) ( $opt['type'] !== '' ? $opt['type'] : 'button' );
				$opt['show_text'] = (bool) ( $opt['show_text'] ?? true );
			}
		}

		self::$used_this_request = true;

		$html    = '';
		$all_row = true;
		$per_slug = 0;
		$all_icon_only = true;
		foreach ( $slugs as $s ) {
			if ( ! isset( self::$button_renderers[ $s ] ) ) {
				continue;
			}
			$cb    = self::$button_renderers[ $s ];
			$one   = $opt;
			$one['provider'] = $s;
			if ( $one['align'] === '' ) {
				$one['align'] = $c_align;
			}
			$piece = (string) call_user_func( $cb, $one );
			if ( $piece === '' ) {
				continue;
			}
			if ( false === strpos( $piece, 'wpps-sl-btn--icon-only' ) ) {
				$all_icon_only = false;
			}
			++$per_slug;
			$in_row = ( false !== strpos( $piece, 'wpps-sl--w-auto' ) || false !== strpos( $piece, 'wpps-sl-btn--icon-only' ) );
			if ( ! $in_row ) {
				$all_row = false;
			}
			$html .= '<div class="wpps-sl-item wpps-sl-item--' . esc_attr( $s ) . '">' . $piece . '</div>';
		}
		if ( $html === '' ) {
			return '';
		}
		$mods = [ 'wpps-sl--c-align-' . $c_align ];
		if ( $all_row ) {
			$mods[] = 'wpps-sl--row';
		}
		$title = '';
		if ( $per_slug > 1 ) {
			$title = SocialLoginFormGroup::or_separator_html( $all_icon_only );
		}
		return '<div class="wpps-social-login ' . esc_attr( implode( ' ', $mods ) ) . '" data-wpps-social-login="1">'
			. $title . $html . '</div>';
	}

	public static function wasUsedThisRequest(): bool {
		return self::$used_this_request;
	}
}
