<?php
/**
 * Design systems (tokens) from library/design-systems + apply without wiping content.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Templates;

use AuraBuilder\Globals\SiteGlobals;

final class DesignSystemLibrary {

	/**
	 * @return list<array<string, mixed>>
	 */
	public static function list(): array {
		$dir = trailingslashit( AURA_BUILDER_PATH ) . 'library/design-systems';
		if ( ! is_dir( $dir ) ) {
			return array();
		}
		$out   = array();
		$files = glob( $dir . '/*.json' ) ?: array();
		foreach ( $files as $file ) {
			$raw = CoreLibrary::read_json( $file );
			if ( ! $raw ) {
				continue;
			}
			$id = (string) ( $raw['id'] ?? pathinfo( $file, PATHINFO_FILENAME ) );
			$out[] = array(
				'id'       => $id,
				'name'     => (string) ( $raw['name'] ?? $id ),
				'category' => (string) ( $raw['category'] ?? 'general' ),
				'colors'   => is_array( $raw['colors'] ?? null ) ? $raw['colors'] : array(),
				'preview'  => (string) ( $raw['colors']['primary'] ?? '#7c3aed' ),
			);
		}
		usort(
			$out,
			static fn( $a, $b ) => strcasecmp( (string) $a['name'], (string) $b['name'] )
		);
		return $out;
	}

	/**
	 * @return array<string, mixed>|null
	 */
	public static function get( string $id ): ?array {
		$id   = sanitize_file_name( $id );
		$file = trailingslashit( AURA_BUILDER_PATH ) . 'library/design-systems/' . $id . '.json';
		return CoreLibrary::read_json( $file );
	}

	/**
	 * Merge design system into SiteGlobals.
	 *
	 * @return array<string, mixed>|\WP_Error
	 */
	public static function apply( string $id ) {
		$ds = self::get( $id );
		if ( ! $ds ) {
			return new \WP_Error( 'ab_ds', 'Design system não encontrado.', array( 'status' => 404 ) );
		}
		$current = SiteGlobals::get();
		foreach ( array( 'colors', 'typography', 'radius', 'layout', 'chrome' ) as $group ) {
			if ( empty( $ds[ $group ] ) || ! is_array( $ds[ $group ] ) ) {
				continue;
			}
			if ( ! is_array( $current[ $group ] ?? null ) ) {
				$current[ $group ] = array();
			}
			foreach ( $ds[ $group ] as $k => $v ) {
				if ( is_scalar( $v ) && (string) $v !== '' ) {
					$current[ $group ][ $k ] = $v;
				}
			}
		}
		return SiteGlobals::save( $current );
	}
}
