<?php
/**
 * PSR-4-like autoloader without Composer for the SuiteMkt3k namespace.
 *
 * @package SuiteMkt3k
 */

namespace SuiteMkt3k;

defined( 'ABSPATH' ) || exit;

final class Autoloader {

	public static function register(): void {
		spl_autoload_register( array( __CLASS__, 'load' ) );
	}

	public static function load( string $class_name ): void {
		if ( strpos( $class_name, 'SuiteMkt3k\\' ) !== 0 ) {
			return;
		}

		$relative = substr( $class_name, strlen( 'SuiteMkt3k\\' ) );
		$parts    = explode( '\\', $relative );
		$class    = array_pop( $parts );

		$dir_parts = array_map( array( __CLASS__, 'to_kebab' ), $parts );
		$dir       = $dir_parts ? implode( '/', $dir_parts ) . '/' : '';
		$base      = SUITEMKT3K_PATH . 'includes/' . $dir;

		$candidates = array(
			$base . 'class-' . self::to_kebab( $class ) . '.php',
			$base . 'class-' . self::to_kebab_compact( $class ) . '.php',
		);

		foreach ( $candidates as $file ) {
			if ( is_readable( $file ) ) {
				require_once $file;
				return;
			}
		}
	}

	private static function to_kebab( string $segment ): string {
		$segment = preg_replace( '/([a-z])([A-Z])/', '$1-$2', $segment );
		$segment = str_replace( '_', '-', (string) $segment );
		return strtolower( $segment );
	}

	/**
	 * Compact variant: keeps consecutive capitals together (WooCommerce -> woocommerce).
	 */
	private static function to_kebab_compact( string $segment ): string {
		$segment = str_replace( '_', '-', $segment );
		return strtolower( $segment );
	}
}
