<?php
/**
 * Cards module — register variants + card design tokens from Theme Options.
 *
 * Not a Layout Engine. Cards are a shared visual system.
 *
 * @package Kutby
 * @since   2.9.0
 */

declare(strict_types=1);

namespace Kutby\Modules;

use Kutby\Cards\Services\CardRegistry;
use Kutby\Cards\Variants\CompactCard;
use Kutby\Cards\Variants\EditorialCard;
use Kutby\Cards\Variants\FeaturedCard;
use Kutby\Cards\Variants\GridCard;
use Kutby\Cards\Variants\HorizontalCard;
use Kutby\Contracts\ModuleInterface;
use Kutby\ThemeOptions\Manager;

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

/**
 * Class CardsModule
 */
final class CardsModule implements ModuleInterface {

	/**
	 * {@inheritdoc}
	 */
	public function register(): void {
		$registry = CardRegistry::instance();
		$registry->add( 'editorial', EditorialCard::class );
		$registry->add( 'compact', CompactCard::class );
		$registry->add( 'horizontal', HorizontalCard::class );
		$registry->add( 'grid', GridCard::class );
		$registry->add( 'featured', FeaturedCard::class );

		/**
		 * Register additional card variants.
		 *
		 * @since 2.9.0
		 *
		 * @param CardRegistry $registry Registry.
		 */
		do_action( 'kutby_cards_register_variants', $registry );

		add_filter( 'kutby_css_variables', array( $this, 'filter_css_variables' ) );

		/**
		 * Cards system ready.
		 *
		 * @since 2.9.0
		 */
		do_action( 'kutby_cards_module_ready' );
	}

	/**
	 * {@inheritdoc}
	 */
	public function boot(): void {}

	/**
	 * Map Theme Options cards group → CSS variables.
	 *
	 * @param array<string, string> $tokens Tokens.
	 * @return array<string, string>
	 */
	public function filter_css_variables( array $tokens ): array {
		$cards  = Manager::get_group( 'cards', array() );
		$radius = isset( $cards['radius'] ) ? (int) $cards['radius'] : 12;
		$pad    = isset( $cards['padding'] ) ? (int) $cards['padding'] : 20;
		$shadow = sanitize_key( (string) ( $cards['shadow'] ?? 'sm' ) );

		$tokens['--kutby-card-radius']  = max( 0, min( 32, $radius ) ) . 'px';
		$tokens['--kutby-card-padding'] = max( 8, min( 48, $pad ) ) . 'px';

		$shadow_map = array(
			'none' => 'none',
			'sm'   => 'var(--kutby-shadow-sm)',
			'md'   => 'var(--kutby-shadow-md)',
			'lg'   => 'var(--kutby-shadow-lg)',
		);
		$tokens['--kutby-card-shadow'] = $shadow_map[ $shadow ] ?? $shadow_map['sm'];

		return $tokens;
	}
}
