<?php
/**
 * Tabs widget render layer.
 *
 * Shortcode: [rsmspark_tabs]
 * Attributes: items (JSON array of {title, content})
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Widget_Tabs
 *
 * Refactored in compat branch - Phase 1
 */
class Rsmspark_Content_Widgets_Widget_Tabs {

	const REGISTRY_ID = 'tabs';

	/**
	 * @return void
	 */
	public static function register() {
		Rsmspark_Content_Widgets_Shortcodes::add(
			Rsmspark_Content_Widgets_Registry::shortcode_tag( self::REGISTRY_ID ),
			array( __CLASS__, 'shortcode' ),
			self::REGISTRY_ID
		);

		Rsmspark_Content_Widgets_Blocks::add(
			'tabs',
			array(
				'api_version'     => 3,
				'title'           => __( 'RSM Tabs', 'rsm-content-widgets' ),
				'description'     => __( 'Tabbed content panels.', 'rsm-content-widgets' ),
				'category'        => Rsmspark_Content_Widgets_Blocks::BLOCK_CATEGORY,
				'icon'            => 'index-card',
				'keywords'        => array( 'tabs', 'panels', 'rsm' ),
				'supports'        => array( 'html' => false ),
				'attributes'      => self::block_attributes(),
				'render_callback' => array( __CLASS__, 'render_block' ),
			)
		);
	}

	/**
	 * @return array<string, array<string, mixed>>
	 */
	public static function block_attributes() {
		return array(
			'items'        => array(
				'type'    => 'array',
				'default' => self::default_items(),
			),
		);
	}

	/**
	 * @param array<string, mixed> $atts Shortcode attributes.
	 * @param string               $content Inner content (unused).
	 * @return string
	 */
	public static function shortcode( $atts, $content = '' ) {
		unset( $content );
		$atts = is_array( $atts ) ? $atts : array();
		return self::render( self::normalize_atts( $atts ) );
	}

	/**
	 * @param array<string, mixed> $attributes Block attributes.
	 * @return string
	 */
	public static function render_block( $attributes ) {
		$attributes = is_array( $attributes ) ? $attributes : array();
		return self::render( self::normalize_atts( $attributes ) );
	}

	/**
	 * @param array<string, mixed> $atts Raw attributes.
	 * @return array<string, mixed>
	 */
	public static function normalize_atts( array $atts ) {
		$defaults = array(
			'items' => '',
		);

		$parsed = Rsmspark_Content_Widgets_Render::parse_atts( $atts, $defaults, 'rsmspark_tabs' );
		$items  = self::coerce_items( $parsed['items'] );

		return array(
			'items'        => self::sanitize_items( $items ),
			'remember_tab' => false,
			'widget_uid'   => 'rsmspark-cw-tabs-' . wp_unique_id(),
		);
	}

	/**
	 * Whether last-opened tab persistence is active (Pro + setting).
	 *
	 * @param mixed $requested Raw remember_tab value.
	 * @return bool
	 */
	public static function remember_tab_enabled( $requested ) {
		unset( $requested );
		return false;
	}

	/**
	 * Stable localStorage key for a tabs instance on this page.
	 *
	 * @param array<int, array<string, mixed>> $items Sanitized tab items.
	 * @return string
	 */
	public static function storage_key_for_items( array $items ) {
		$slugs = array();
		foreach ( $items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			$slug = sanitize_title( (string) ( $item['slug'] ?? '' ) );
			if ( '' !== $slug ) {
				$slugs[] = $slug;
			}
		}

		$post_id = (int) get_queried_object_id();
		$seed    = $post_id . '|' . wp_json_encode( $slugs );

		return 'rsmspark-cw-tabs-' . substr( hash( 'sha256', $seed ), 0, 16 );
	}

	/**
	 * @param array<string, mixed> $content SiteOrigin content section.
	 * @return array<string, mixed>
	 */
	public static function prepare_from_instance( array $content ) {
		$items = isset( $content['items'] ) && is_array( $content['items'] ) ? $content['items'] : array();
		$items = self::sanitize_items( $items );

		return array(
			'items'        => $items,
			'remember_tab' => false,
			'widget_uid'   => 'rsmspark-cw-tabs-' . wp_unique_id(),
			'storage_key'  => self::storage_key_for_items( $items ),
		);
	}

	/**
	 * @param mixed $items Raw items from shortcode or block.
	 * @return array<int, array{title: string, content: string}>
	 */
	public static function coerce_items( $items ) {
		if ( is_string( $items ) && '' !== $items ) {
			$items = Rsmspark_Content_Widgets_Render::parse_json_attr( $items, self::default_items() );
		}
		if ( ! is_array( $items ) ) {
			$items = self::default_items();
		}

		$clean = self::sanitize_items( $items );
		if ( empty( $clean ) ) {
			$clean = self::sanitize_items( self::default_items() );
		}

		return $clean;
	}

	/**
	 * @param array<int, mixed> $items Raw tab items.
	 * @return array<int, array{title: string, content: string}>
	 */
	public static function sanitize_items( array $items ) {
		$clean = array();
		$used  = array();
		foreach ( $items as $index => $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			$title   = sanitize_text_field( (string) ( $item['title'] ?? '' ) );
			$content = Rsmspark_Rich_Text_Body::sanitize( $item['content'] ?? '' );
			if ( '' === $title && '' === trim( wp_strip_all_tags( $content ) ) ) {
				continue;
			}
			$slug    = Rsmspark_Content_Widgets_Render::item_hash_slug( $title, (int) $index, $used );
			$used[]  = $slug;
			$clean[] = array(
				'title'   => $title,
				'content' => $content,
				'slug'    => $slug,
			);
		}
		return $clean;
	}

	/**
	 * @param array<string, mixed> $instance SiteOrigin widget instance.
	 * @return array<string, mixed>
	 */
	public static function prepare_from_siteorigin_instance( array $instance ) {
		$normalized = self::prepare_from_instance(
			Rsmspark_Content_Widgets_Render::section_instance( $instance, 'content' )
		);

		return array(
			'items'        => $normalized['items'],
			'remember_tab' => false,
		);
	}

	/**
	 * @param array<string, mixed> $attrs Block attributes.
	 * @return array<string, mixed>
	 */
	public static function instance_from_atts( array $attrs ) {
		$normalized = self::normalize_atts( $attrs );

		return array(
			'content' => array(
				'items'        => $normalized['items'],
				'remember_tab' => false,
			),
		);
	}

	/**
	 * @param array<string, mixed> $instance SiteOrigin or import instance.
	 * @return array<string, mixed>
	 */
	public static function sanitize_instance( array $instance ) {
		unset( $instance['import_export'], $instance['panels_info'] );

		if ( isset( $instance['content'] ) ) {
			return self::instance_from_atts( self::prepare_from_siteorigin_instance( $instance ) );
		}

		return self::instance_from_atts( $instance );
	}

	/**
	 * @return array<int, array{title: string, content: string}>
	 */
	public static function default_items() {
		return array(
			array(
				'title'   => __( 'First tab', 'rsm-content-widgets' ),
				'content' => __( 'Content for the first tab.', 'rsm-content-widgets' ),
			),
			array(
				'title'   => __( 'Second tab', 'rsm-content-widgets' ),
				'content' => __( 'Content for the second tab.', 'rsm-content-widgets' ),
			),
		);
	}

	/**
	 * @param array<string, mixed> $args Normalized render arguments.
	 * @return string
	 */
	public static function render( array $args ) {
		if ( empty( $args['items'] ) ) {
			return '';
		}

		$items = is_array( $args['items'] ) ? $args['items'] : array();
		$args['style_vars']   = Rsmspark_Content_Widgets_Render::inline_style_vars();
		$args['remember_tab'] = false;
		$args['storage_key']  = isset( $args['storage_key'] ) && is_string( $args['storage_key'] )
			? $args['storage_key']
			: self::storage_key_for_items( $items );

		return Rsmspark_Content_Widgets_Render::render_template(
			self::REGISTRY_ID,
			'tabs.php',
			$args
		);
	}
}

/**
 * @param array<string, mixed> $args Widget arguments.
 * @return string
 */
function rsmspark_cw_render_tabs( array $args ) {
	$prepared = isset( $args['items'] ) && is_array( $args['items'] )
		? array(
			'items'        => Rsmspark_Content_Widgets_Widget_Tabs::sanitize_items( $args['items'] ),
			'remember_tab' => false,
			'widget_uid'   => 'rsmspark-cw-tabs-' . wp_unique_id(),
		)
		: Rsmspark_Content_Widgets_Widget_Tabs::normalize_atts( $args );

	if ( empty( $prepared['storage_key'] ) ) {
		$prepared['storage_key'] = Rsmspark_Content_Widgets_Widget_Tabs::storage_key_for_items(
			is_array( $prepared['items'] ?? null ) ? $prepared['items'] : array()
		);
	}

	return Rsmspark_Content_Widgets_Widget_Tabs::render( $prepared );
}
