// Copyright 2025 (c) MatteuSan and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

@use 'sass:meta';
@use 'sass:selector';
@use 'sass:string';

@use 'validators';

$ds-prefix: '' !default;

/// Creates a selector with your design system prefix.
/// @param {string} $selector
/// @return {*} returns a selector with content block inside.
@mixin create($selector) {
  #{_prepend-selector-type($selector)} {
    @content;
  }
}

/// Determines the selector type and composes the selector name with your design system prefix.
/// @access private
/// @param {string} $selector
/// @return {string|error} returns a cleaned and prefixed selector.
@function _prepend-selector-type($selector) {
  @if string.slice($selector, 1, 1) == '&' {
    @if string.slice($selector, 2, 2) == '.' {
      @return string.unquote('&.#{_sanitize-prefix($ds-prefix)}#{string.slice($selector, 3)}');
    } @else if string.slice($selector, 2, 2) == '#' {
      @return string.unquote('&##{_sanitize-prefix($ds-prefix)}#{string.slice($selector, 3)}');
    } @else {
      @error 'Invalid selector type: #{string.slice($selector, 1, 1)}. Please prefix your selector by using a class selector (.) or an id selector (#).';
    }
  } @else if string.slice($selector, 1, 1) != '&' {
    @if string.slice($selector, 1, 1) == '.' {
      @return string.unquote('.#{_sanitize-prefix($ds-prefix)}#{string.slice($selector, 2)}');
    } @else if string.slice($selector, 1, 1) == '#' {
      @return string.unquote('##{_sanitize-prefix($ds-prefix)}#{string.slice($selector, 2)}');
    } @else {
      @error 'Invalid selector type: #{string.slice($selector, 1, 1)}. Please prefix your selector by using a class selector (.) or an id selector (#).';
    }
  }
}

/// Sanitizes and verifies a prefix.
/// @param {string} $prefix
/// @return {string} sanitized and validated prefix.
@function _sanitize-prefix($prefix) {
  @if validators.is-empty($prefix) {
    @return '';
  }
  @return '#{$prefix}-';
}