<?php

namespace SocialShare;

use WP_PowerSuite\Core\AbstractModule;
class Module extends AbstractModule {

	private const MODULE_ID = 'social-share';
	private const MODULE_VERSION = '1.2.7';

	/** Max share actions before a “+” overflow control on floating bars. */
	private const FLOATING_BAR_MAX_VISIBLE = 4;

	/** @var int */
	private static $share_render_seq = 0;

	/** @var list<string> */
	private const FLOATING_POSITIONS = [ 'float_bottom_center', 'float_left_center', 'float_right_center' ];

	/** Preset slugs (labels are translated in getButtonPresets() for display only). */
	private const BUTTON_PRESET_KEYS = [ 'flow', 'solid', 'minimal', 'pill', 'outline', 'glass' ];

	private const PLATFORMS = [
		'facebook'  => [ 'label' => 'Facebook', 'color' => '#1877f2', 'icon' => 'facebook' ],
		'x'         => [ 'label' => 'X (Twitter)', 'color' => '#000000', 'icon' => 'x-twitter' ],
		'linkedin'  => [ 'label' => 'LinkedIn', 'color' => '#0077b5', 'icon' => 'linkedin' ],
		'whatsapp'  => [ 'label' => 'WhatsApp', 'color' => '#25d366', 'icon' => 'whatsapp' ],
		'reddit'    => [ 'label' => 'Reddit', 'color' => '#ff4500', 'icon' => 'reddit' ],
		'pinterest' => [ 'label' => 'Pinterest', 'color' => '#bd081c', 'icon' => 'pinterest' ],
		'telegram'  => [ 'label' => 'Telegram', 'color' => '#0088cc', 'icon' => 'telegram' ],
		'tumblr'    => [ 'label' => 'Tumblr', 'color' => '#36465d', 'icon' => 'tumblr' ],
		'email'     => [ 'label' => 'Email', 'color' => '#666666', 'icon' => 'envelope' ],
	];

	private ?array $settings_cache = null;

	public function getId(): string {
		return self::MODULE_ID;
	}

	public function getName(): string {
		return __( 'Floating Social Share Buttons', 'wp-powersuite' );
	}

	public function getVersion(): string {
		return self::MODULE_VERSION;
	}

	public function getDescription(): string {
		return __( 'Share buttons for major networks and email—floating bars, inline before/after content, or shortcode—without third-party tracking widgets.', 'wp-powersuite' );
	}

	public function getContext(): string|array {
		return 'frontend';
	}

	public function getDependencies(): array {
		return [];
	}

	private function isLicenseActive(): bool {
		return function_exists( 'wp_powersuite_is_license_valid' ) && wp_powersuite_is_license_valid();
	}

	protected function registerHooks(): void {
		if ( ! $this->isLicenseActive() ) {
			return;
		}

		add_shortcode( 'social_share', [ $this, 'renderShortcode' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueueAssets' ] );

		$settings = $this->getSettings();
		if ( empty( $settings['auto_display'] ) ) {
			return;
		}

		$position = $settings['position'] ?? 'after_content';
		if ( in_array( $position, self::FLOATING_POSITIONS, true ) ) {
			add_action( 'wp_footer', [ $this, 'maybeOutputFloatingShare' ] );
			return;
		}

		add_filter( 'the_content', [ $this, 'filterContent' ], 12 );
	}


	public function enqueueAssets(): void {
		if ( ! is_singular() ) {
			return;
		}

		$post = get_post();
		if ( ! $post instanceof \WP_Post ) {
			return;
		}

		$settings = $this->getSettings();
		$has_shortcode = has_shortcode( (string) $post->post_content, 'social_share' );
		$auto_ok       = ! empty( $settings['auto_display'] ) && $this->shouldShowOnPostType();
		if ( ! $auto_ok && ! $has_shortcode ) {
			return;
		}

		$base = defined( 'WP_POWERSUITE_PLUGIN_URL' ) ? WP_POWERSUITE_PLUGIN_URL : '';
		$css  = __DIR__ . '/assets/social-share.css';
		if ( is_readable( $css ) ) {
			wp_enqueue_style(
				'wpps-social-share',
				$base . 'modules/social-share/assets/social-share.css',
				[],
				$this->assetVersion( 'social-share.css' )
			);
		}

		if ( ! $this->needsShareScript( $settings, $auto_ok, $has_shortcode ) ) {
			return;
		}

		$js = __DIR__ . '/assets/social-share.js';
		if ( ! is_readable( $js ) ) {
			return;
		}

		wp_enqueue_script(
			'wpps-social-share',
			$base . 'modules/social-share/assets/social-share.js',
			[],
			$this->assetVersion( 'social-share.js' ),
			true
		);
		wp_localize_script(
			'wpps-social-share',
			'wppsSocialShare',
			[
				'copyLabel'   => __( 'Copy link', 'wp-powersuite' ),
				'copiedLabel' => __( 'Link copied', 'wp-powersuite' ),
				'copyFailed'  => __( 'Could not copy', 'wp-powersuite' ),
			]
		);
	}

	public function renderShortcode( array $atts = [] ): string {
		$platforms = isset( $atts['platforms'] ) ? $this->parsePlatforms( $atts['platforms'] ) : null;
		$overrides   = [];
		if ( isset( $atts['heading'] ) ) {
			$h = strtolower( trim( (string) $atts['heading'] ) );
			$overrides['show_heading'] = ! in_array( $h, [ '0', 'no', 'off', 'false', 'hide', '' ], true );
		}
		if ( isset( $atts['copy'] ) ) {
			$c                      = strtolower( trim( (string) $atts['copy'] ) );
			$overrides['show_copy'] = ! in_array( $c, [ '0', 'no', 'off', 'false', 'hide' ], true );
		}
		if ( isset( $atts['title'] ) && is_string( $atts['title'] ) && trim( $atts['title'] ) !== '' ) {
			$overrides['heading_text'] = sanitize_text_field( $atts['title'] );
		}
		if ( isset( $atts['preset'] ) ) {
			$p = sanitize_key( (string) $atts['preset'] );
			if ( in_array( $p, self::BUTTON_PRESET_KEYS, true ) ) {
				$overrides['preset'] = $p;
			}
		}
		if ( isset( $atts['icons'] ) ) {
			$ic = strtolower( trim( (string) $atts['icons'] ) );
			if ( in_array( $ic, [ '1', 'yes', 'true', 'on', 'only', 'icons' ], true ) ) {
				$overrides['icons_only'] = true;
			} elseif ( in_array( $ic, [ '0', 'no', 'off', 'false', 'labels' ], true ) ) {
				$overrides['icons_only'] = false;
			}
		}
		if ( isset( $atts['labels'] ) ) {
			$lb = strtolower( trim( (string) $atts['labels'] ) );
			if ( in_array( $lb, [ '0', 'no', 'off', 'false', 'hide' ], true ) ) {
				$overrides['icons_only'] = true;
			} elseif ( in_array( $lb, [ '1', 'yes', 'on', 'show' ], true ) ) {
				$overrides['icons_only'] = false;
			}
		}
		return $this->renderShareButtons( $platforms, false, '', $overrides );
	}

	public function filterContent( string $content ): string {
		static $in_filter = false;
		if ( $in_filter ) {
			return $content;
		}

		if ( ! is_singular() || trim( $content ) === '' ) {
			return $content;
		}

		// Only act on the primary content loop; skip related-posts/widget secondary loops.
		if ( ! in_the_loop() || ! is_main_query() ) {
			return $content;
		}

		$settings = $this->getSettings();
		if ( empty( $settings['auto_display'] ) ) {
			return $content;
		}

		if ( ! $this->shouldShowOnPostType() ) {
			return $content;
		}

		$raw_content = get_post()->post_content ?? '';
		if ( str_contains( $raw_content, '[social_share' ) ) {
			return $content;
		}

		$position = $settings['position'] ?? 'after_content';
		if ( in_array( $position, self::FLOATING_POSITIONS, true ) ) {
			return $content;
		}

		$in_filter = true;
		$buttons   = $this->renderShareButtons( null, false, '', [] );
		$in_filter = false;

		switch ( $position ) {
			case 'before_content':
				return "\n\n" . $buttons . "\n\n" . $content;
			case 'both':
				return "\n\n" . $buttons . "\n\n" . $content . "\n\n" . $buttons . "\n\n";
			case 'after_content':
			default:
				return $content . "\n\n" . $buttons . "\n\n";
		}
	}

	public function maybeOutputFloatingShare(): void {
		if ( ! is_singular() ) {
			return;
		}

		$settings = $this->getSettings();
		if ( empty( $settings['auto_display'] ) ) {
			return;
		}

		if ( ! $this->shouldShowOnPostType() ) {
			return;
		}

		$position = $settings['position'] ?? 'after_content';
		if ( ! in_array( $position, self::FLOATING_POSITIONS, true ) ) {
			return;
		}

		echo $this->renderShareButtons( null, true, $position, [] );
	}

	public function renderShareButtons( ?array $platforms = null, bool $floating = false, string $position = '', array $display_overrides = [] ): string {
		$post = get_post();
		if ( ! $post instanceof \WP_Post ) {
			return '';
		}

		$settings  = $this->getSettings();
		$platforms = $platforms ?? ( $settings['platforms'] ?? [ 'facebook', 'x', 'linkedin', 'email' ] );
		if ( ! is_array( $platforms ) || empty( $platforms ) ) {
			$platforms = [ 'facebook', 'x', 'linkedin', 'email' ];
		}

		$url = get_permalink( $post );
		$title = $post ? $post->post_title : '';
		$text  = $post && $post->post_excerpt ? wp_strip_all_tags( $post->post_excerpt ) : wp_trim_words( wp_strip_all_tags( $post->post_content ?? '' ), 55 );
		if ( empty( $text ) ) {
			$text = $title;
		}

		$show_web_share = ! empty( $settings['web_share_api'] );
		$icons_only     = $floating;
		if ( ! $floating ) {
			if ( array_key_exists( 'icons_only', $display_overrides ) ) {
				$icons_only = (bool) $display_overrides['icons_only'];
			} else {
				$icons_only = ! empty( $settings['inline_icons_only'] );
			}
		}

		$show_heading = array_key_exists( 'show_heading', $display_overrides )
			? (bool) $display_overrides['show_heading']
			: ! empty( $settings['show_heading'] );
		$show_copy = array_key_exists( 'show_copy', $display_overrides )
			? (bool) $display_overrides['show_copy']
			: ! empty( $settings['copy_link'] );

		if ( array_key_exists( 'heading_text', $display_overrides ) && is_string( $display_overrides['heading_text'] ) && $display_overrides['heading_text'] !== '' ) {
			$heading_display = $display_overrides['heading_text'];
		} else {
			$heading_custom = trim( (string) ( $settings['heading_text'] ?? '' ) );
			$heading_display = $heading_custom !== '' ? $heading_custom : __( 'Share', 'wp-powersuite' );
		}

		$preset_override = null;
		if ( array_key_exists( 'preset', $display_overrides ) && is_string( $display_overrides['preset'] ) && $display_overrides['preset'] !== '' ) {
			$candidate = sanitize_key( $display_overrides['preset'] );
			$preset_override = in_array( $candidate, self::BUTTON_PRESET_KEYS, true ) ? $candidate : null;
		}
		if ( $preset_override !== null ) {
			$preset = $this->sanitizeButtonPreset( $preset_override, 'flow' );
		} elseif ( $floating ) {
			$preset = $this->sanitizeButtonPreset( (string) ( $settings['button_preset_floating'] ?? 'solid' ), 'solid' );
		} else {
			$preset = $this->sanitizeButtonPreset( (string) ( $settings['button_preset_inline'] ?? 'flow' ), 'flow' );
		}
		if ( $floating && $preset === 'flow' ) {
			$preset = 'minimal';
		}

		$container_class = 'wpps-social-share wpps-social-share--preset-' . esc_attr( $preset );
		if ( ! $floating ) {
			$container_class .= ' wpps-social-share--inline';
			if ( ! $show_heading ) {
				$container_class .= ' wpps-social-share--no-heading';
			}
			if ( $icons_only ) {
				$container_class .= ' wpps-social-share--icons-only';
			}
		}
		if ( $floating ) {
			$container_class .= ' wpps-social-share--floating wpps-social-share--icons-only wpps-social-share--' . esc_attr( sanitize_key( $position ) );
		}

		$items = [];

		foreach ( $platforms as $key ) {
			$key = strtolower( trim( (string) $key ) );
			if ( $key === '' || ! isset( self::PLATFORMS[ $key ] ) ) {
				continue;
			}
			$info = self::PLATFORMS[ $key ];
			$href = $this->getShareUrl( $key, $url, $title, $text );
			if ( $href === '' ) {
				continue;
			}
			$label_attr = sprintf( __( 'Share on %s', 'wp-powersuite' ), $info['label'] );
			$icon_svg   = self::getPlatformIconSvg( $key );
			$link_text  = $icons_only ? $icon_svg : ( $icon_svg . '<span class="wpps-share-link__text">' . esc_html( $info['label'] ) . '</span>' );
			$items[]    = '<a href="' . esc_url( $href ) . '" class="wpps-share-link wpps-share-link--' . esc_attr( $key ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr( $label_attr ) . '" aria-label="' . esc_attr( $label_attr ) . '">' . $link_text . '</a>';
		}

		if ( $show_copy ) {
			$copy_icon  = self::getPlatformIconSvg( 'copy' );
			$copy_label = esc_html__( 'Copy link', 'wp-powersuite' );
			$copy_text  = $icons_only ? $copy_icon : ( $copy_icon . '<span class="wpps-share-link__text wpps-share-link__text--copy">' . $copy_label . '</span>' );
			$items[]    = '<button type="button" class="wpps-share-link wpps-share-link--copy wpps-copy-link-trigger" data-copy-url="' . esc_attr( $url ) . '" aria-label="' . esc_attr__( 'Copy page link to clipboard', 'wp-powersuite' ) . '">' . $copy_text . '</button>';
		}

		if ( $show_web_share ) {
			$native_icon   = self::getPlatformIconSvg( 'native' );
			$native_label  = __( 'Share using your device', 'wp-powersuite' );
			$native_inner  = $icons_only
				? $native_icon
				: ( $native_icon . '<span class="wpps-share-link__text">' . esc_html__( 'Share', 'wp-powersuite' ) . '</span>' );
			$items[]       = '<button type="button" class="wpps-share-link wpps-share-link--native wpps-web-share-trigger" data-share-title="' . esc_attr( $title ) . '" data-share-text="' . esc_attr( $text ) . '" data-share-url="' . esc_attr( $url ) . '" title="' . esc_attr( $native_label ) . '" aria-label="' . esc_attr( $native_label ) . '">' . $native_inner . '</button>';
		}

		$item_count             = count( $items );
		$use_floating_overflow = $floating && $item_count > self::FLOATING_BAR_MAX_VISIBLE;
		if ( $use_floating_overflow ) {
			$container_class .= ' wpps-social-share--has-overflow';
		}

		$out = '<div class="' . esc_attr( $container_class ) . '" role="group" aria-label="' . esc_attr__( 'Share this', 'wp-powersuite' ) . '">';
		if ( ! $icons_only && $show_heading ) {
			$out .= '<h4 class="wpps-social-share__heading">' . esc_html( $heading_display ) . '</h4>';
		}
		$out .= '<div class="wpps-social-share__buttons">';

		if ( $use_floating_overflow ) {
			$visible = array_slice( $items, 0, self::FLOATING_BAR_MAX_VISIBLE );
			$out    .= implode( '', $visible );
			$more_aria = esc_attr__( 'Open list of all sharing options', 'wp-powersuite' );
			$plus_svg  = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="22" height="22" fill="currentColor" aria-hidden="true"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/></svg>';
			$out .= '<button type="button" class="wpps-share-link wpps-share-link--overflow-more wpps-share-overflow-open" aria-label="' . $more_aria . '" aria-expanded="false" aria-haspopup="dialog">' . $plus_svg . '</button>';
		} else {
			$out .= implode( '', $items );
		}

		$out .= '</div>';

		if ( $use_floating_overflow ) {
			self::$share_render_seq++;
			$ov_heading_id = 'wpps-ss-overflow-h-' . (string) self::$share_render_seq;
			$dialog_label  = esc_html__( 'All sharing options', 'wp-powersuite' );
			$close_label   = esc_attr__( 'Close sharing options', 'wp-powersuite' );
			$out          .= '<div class="wpps-social-share__overflow" hidden>';
			$out          .= '<div class="wpps-social-share__overflow-backdrop wpps-share-overflow-close" tabindex="-1" role="presentation"></div>';
			$out          .= '<div class="wpps-social-share__overflow-panel" role="dialog" aria-modal="true" aria-labelledby="' . esc_attr( $ov_heading_id ) . '">';
			$out          .= '<div class="wpps-social-share__overflow-header">';
			$out          .= '<span id="' . esc_attr( $ov_heading_id ) . '" class="wpps-social-share__overflow-title">' . esc_html( $dialog_label ) . '</span>';
			$out         .= '<button type="button" class="wpps-social-share__overflow-close wpps-share-overflow-close" aria-label="' . $close_label . '"><span aria-hidden="true">&times;</span></button>';
			$out         .= '</div>';
			$out         .= '<div class="wpps-social-share__overflow-buttons">';
			$out         .= implode( '', $items );
			$out         .= '</div></div></div>';
		}

		$out .= '<span class="wpps-social-share__status wpps-sr-only" role="status" aria-live="polite" aria-atomic="true"></span>';
		$out .= '</div>';

		return $out;
	}

	public static function getPlatformIconSvg( string $platform ): string {
		$icons = [
			'facebook'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>',
			'x'         => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/></svg>',
			'linkedin'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/></svg>',
			'whatsapp'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>',
			'reddit'    => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z"/></svg>',
			'pinterest' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z"/></svg>',
			'telegram'  => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M11.944 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0a12 12 0 0 0-.056 0zm4.962 7.224c.1-.002.321.023.465.14a.506.506 0 0 1 .171.325c.016.093.036.306.02.472-.18 1.898-.962 6.502-1.36 8.627-.168.9-.499 1.201-.82 1.23-.696.065-1.225-.46-1.9-.902-1.056-.693-1.653-1.124-2.678-1.8-1.185-.78-.417-1.21.258-1.91.177-.184 3.247-2.977 3.307-3.23.007-.032.014-.15-.056-.212s-.174-.041-.249-.024c-.106.024-1.793 1.14-5.061 3.345-.48.33-.913.49-1.302.48-.428-.008-1.252-.241-1.865-.44-.752-.245-1.349-.374-1.297-.789.027-.216.325-.437.893-.663 3.498-1.524 5.83-2.529 6.998-3.014 3.332-1.386 4.025-1.627 4.476-1.635z"/></svg>',
			'tumblr'    => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M19.95 17.039c-.277 1.584-1.683 3.001-3.106 3.542-1.34.51-2.613.666-3.935.577-1.316-.091-2.588-.437-3.616-1.123-.408-.271-.767-.6-1.034-1.011-.267-.412-.405-.89-.403-1.372V7.495h-.023c-.027-1.357.052-2.718.234-4.068.183-1.35.543-2.568 1.05-3.697.507-1.13 1.164-2.13 1.921-3.019C10.52.848 11.78.192 13.006.028 1.232-.165 1.433 1.8 1.433 3.93v3.4h3.65v4.074h-3.65v6.377c.036.485.205.964.5 1.327.294.363.707.602 1.154.662 1.02.129 2.034-.004 2.99-.399.956-.395 1.834-1.012 2.472-1.798.089-.108.173-.222.252-.34.101-.15.196-.305.283-.465.088-.16.168-.324.24-.492.072-.168.136-.339.192-.514.056-.175.104-.353.145-.533.041-.18.075-.362.102-.545.027-.183.047-.367.06-.552.013-.185.02-.37.02-.556v-.11c-.002-.08.007-.16.026-.238.02-.078.048-.154.084-.226.037-.072.082-.14.136-.203.054-.063.116-.12.186-.17.069-.05.146-.094.228-.13.082-.037.17-.065.26-.086.09-.02.183-.032.277-.037.094-.005.19-.002.284.008.095.01.188.027.278.05.09.024.177.054.262.09.085.036.167.078.246.125.079.047.154.1.225.158.071.057.138.12.2.186.063.066.12.136.173.21.053.074.1.151.143.231.043.08.081.163.114.248.033.085.06.172.083.26.023.088.04.178.053.268z"/></svg>',
			'email'     => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z"/></svg>',
			'copy'      => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20" aria-hidden="true"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>',
			'native'    => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" width="20" height="20"><path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92-1.31-2.92-2.92-2.92z"/></svg>',
		];
		return $icons[ $platform ] ?? $icons['native'];
	}

	private function getShareUrl( string $platform, string $url, string $title, string $text ): string {
		$url_enc   = rawurlencode( $url );
		$title_enc = rawurlencode( $title );

		switch ( $platform ) {
			case 'facebook':
				return 'https://www.facebook.com/sharer/sharer.php?u=' . $url_enc;
			case 'x':
				return 'https://x.com/intent/tweet?url=' . $url_enc . '&text=' . $title_enc;
			case 'linkedin':
				return 'https://www.linkedin.com/sharing/share-offsite/?url=' . $url_enc;
			case 'whatsapp':
				return 'https://wa.me/?text=' . $title_enc . '%20' . $url_enc;
			case 'reddit':
				return 'https://www.reddit.com/submit?url=' . $url_enc . '&title=' . $title_enc;
			case 'pinterest':
				return 'https://pinterest.com/pin/create/button/?url=' . $url_enc . '&description=' . $title_enc;
			case 'telegram':
				return 'https://t.me/share/url?url=' . $url_enc . '&text=' . $title_enc;
			case 'tumblr':
				return 'https://www.tumblr.com/widgets/share/tool?canonicalUrl=' . $url_enc . '&title=' . $title_enc;
			case 'email':
				return 'mailto:?subject=' . $title_enc . '&body=' . $url_enc;
			default:
				return '';
		}
	}

	private function parsePlatforms( string $input ): array {
		$out = [];
		foreach ( array_map( 'trim', explode( ',', $input ) ) as $p ) {
			$p = strtolower( sanitize_key( $p ) );
			if ( $p !== '' && isset( self::PLATFORMS[ $p ] ) ) {
				$out[] = $p;
			}
		}
		return $out;
	}

	private function shouldShowOnPostType(): bool {
		$settings   = $this->getSettings();
		$post_types = $settings['post_types'] ?? [ 'post' ];
		if ( ! is_array( $post_types ) ) {
			$post_types = [ 'post' ];
		}
		return in_array( get_post_type(), $post_types, true );
	}

	private function getSettings(): array {
		if ( $this->settings_cache !== null ) {
			return $this->settings_cache;
		}

		$raw = $this->moduleSettings()->all( [] );
		$this->settings_cache = self::normalizeSettings( is_array( $raw ) ? $raw : [] );

		return $this->settings_cache;
	}

	public function getDefaultSettings(): array {
		return self::defaultSettings();
	}

	/**
	 * @param array<string, mixed> $raw
	 * @return array<string, mixed>
	 */
	public static function normalizeSettings( array $raw ): array {
		$merged = array_merge( self::defaultSettings(), $raw );

		if ( isset( $raw['button_preset'] ) && is_string( $raw['button_preset'] ) ) {
			$legacy = sanitize_key( $raw['button_preset'] );
			if ( ! isset( $raw['button_preset_inline'] ) ) {
				$merged['button_preset_inline'] = $legacy;
			}
			if ( ! isset( $raw['button_preset_floating'] ) ) {
				$merged['button_preset_floating'] = $legacy;
			}
		}

		$allowed_keys = array_keys( self::PLATFORMS );
		if ( isset( $merged['platforms'] ) && is_array( $merged['platforms'] ) ) {
			$clean_pf = [];
			foreach ( $merged['platforms'] as $p ) {
				$k = sanitize_key( (string) $p );
				if ( $k !== '' && in_array( $k, $allowed_keys, true ) ) {
					$clean_pf[] = $k;
				}
			}
			$merged['platforms'] = array_values( array_unique( $clean_pf ) );
		}
		if ( empty( $merged['platforms'] ) ) {
			$merged['platforms'] = [ 'facebook', 'x', 'linkedin', 'email' ];
		}

		$allow_pt = array_flip( self::getAllowedPostTypes() );
		if ( isset( $merged['post_types'] ) && is_array( $merged['post_types'] ) ) {
			$clean_pt = [];
			foreach ( $merged['post_types'] as $pt ) {
				$k = sanitize_key( (string) $pt );
				if ( $k !== '' && isset( $allow_pt[ $k ] ) && post_type_exists( $k ) ) {
					$clean_pt[] = $k;
				}
			}
			$merged['post_types'] = array_values( array_unique( $clean_pt ) );
		}
		if ( empty( $merged['post_types'] ) ) {
			$merged['post_types'] = [ 'post' ];
		}

		$merged['auto_display']        = ! empty( $merged['auto_display'] );
		$merged['web_share_api']       = ! empty( $merged['web_share_api'] );
		$merged['copy_link']           = ! empty( $merged['copy_link'] );
		$merged['inline_icons_only']   = ! empty( $merged['inline_icons_only'] );
		$merged['show_heading']        = ! array_key_exists( 'show_heading', $merged )
			? true
			: filter_var( $merged['show_heading'], FILTER_VALIDATE_BOOLEAN );

		$ht = isset( $merged['heading_text'] ) ? sanitize_text_field( (string) $merged['heading_text'] ) : '';
		$merged['heading_text'] = function_exists( 'mb_substr' ) ? mb_substr( $ht, 0, 80 ) : substr( $ht, 0, 80 );

		$allowed_pos = [
			'before_content',
			'after_content',
			'both',
			'float_bottom_center',
			'float_left_center',
			'float_right_center',
		];
		$pos = isset( $merged['position'] ) ? (string) $merged['position'] : 'after_content';
		$merged['position'] = in_array( $pos, $allowed_pos, true ) ? $pos : 'after_content';

		$allowed_presets = array_keys( self::getButtonPresets() );
		$bpi = isset( $merged['button_preset_inline'] ) ? sanitize_key( (string) $merged['button_preset_inline'] ) : 'flow';
		$merged['button_preset_inline'] = in_array( $bpi, $allowed_presets, true ) ? $bpi : 'flow';
		$bpf = isset( $merged['button_preset_floating'] ) ? sanitize_key( (string) $merged['button_preset_floating'] ) : 'solid';
		$merged['button_preset_floating'] = in_array( $bpf, $allowed_presets, true ) ? $bpf : 'solid';
		if ( $merged['button_preset_floating'] === 'flow' ) {
			$merged['button_preset_floating'] = 'minimal';
		}

		return $merged;
	}

	/**
	 * @return list<string>
	 */
	public static function getAllowedPostTypes(): array {
		static $cache = null;
		if ( is_array( $cache ) ) {
			return $cache;
		}

		$exclude = [ 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block' ];
		$types   = get_post_types( [ 'public' => true, 'show_ui' => true ], 'names' );
		$cache   = array_values( array_diff( $types, $exclude ) );

		return $cache;
	}

	/**
	 * @return array<string, mixed>
	 */
	private static function defaultSettings(): array {
		return [
			'platforms'              => [ 'facebook', 'x', 'linkedin', 'email' ],
			'post_types'             => [ 'post' ],
			'position'               => 'after_content',
			'auto_display'           => true,
			'web_share_api'          => true,
			'copy_link'              => true,
			'show_heading'           => true,
			'heading_text'           => '',
			'inline_icons_only'      => false,
			'button_preset_inline'   => 'flow',
			'button_preset_floating' => 'solid',
		];
	}

	private function needsShareScript( array $settings, bool $auto_ok, bool $has_shortcode ): bool {
		if ( $has_shortcode ) {
			return true;
		}

		if ( ! $auto_ok ) {
			return false;
		}

		if ( ! empty( $settings['copy_link'] ) || ! empty( $settings['web_share_api'] ) ) {
			return true;
		}

		$position = $settings['position'] ?? 'after_content';

		return in_array( $position, self::FLOATING_POSITIONS, true );
	}

	private function assetVersion( string $filename ): string {
		$path = __DIR__ . '/assets/' . $filename;

		return is_readable( $path ) ? (string) filemtime( $path ) : self::MODULE_VERSION;
	}

	private function sanitizeButtonPreset( string $key, string $fallback ): string {
		$key = sanitize_key( $key );
		return in_array( $key, self::BUTTON_PRESET_KEYS, true ) ? $key : $fallback;
	}


	public static function getPlatforms(): array {
		return self::PLATFORMS;
	}

	/**
	 * Visual style presets for share buttons.
	 *
	 * @return array<string, array{label: string}>
	 */
	public static function getButtonPresets(): array {
		return [
			'flow'     => [
				'label' => __( 'Inline strip (prose)', 'wp-powersuite' ),
			],
			'solid'    => [
				'label' => __( 'Classic solid', 'wp-powersuite' ),
			],
			'minimal'  => [
				'label' => __( 'Minimal light', 'wp-powersuite' ),
			],
			'pill'     => [
				'label' => __( 'Pill rounded', 'wp-powersuite' ),
			],
			'outline'  => [
				'label' => __( 'Outline', 'wp-powersuite' ),
			],
			'glass'    => [
				'label' => __( 'Glass (frosted)', 'wp-powersuite' ),
			],
		];
	}
}
