@use '../../helpers';
@use '../../mixins';
@use '../icon/icon';
@use '../option-list/option-list';
@use '../popover/popover';

@mixin Select() {
  @include icon.Icon();
  @include option-list.OptionList();
  @include popover.Popover();

  @if not mixins.includes('Select') {
    @include _Select();
  }
}

@mixin _Select() {
  .ods-select {
    box-sizing: border-box;
    display: inline-flex;
    flex-direction: column;
    justify-content: center;
    max-width: helpers.space(50);
    position: relative;
    width: 100%;

    > * {
      box-sizing: inherit;
    }

    &.-borderless {
      width: fit-content;
    }

    &.-empty > * {
      color: helpers.color('content-placeholder');
    }

    > .ods-icon {
      transition: transform helpers.time(1) ease;
    }

    &.-open > .ods-icon {
      transform: rotateX(180deg);
    }
  }

  .ods-select-native {
    @include mixins.as-text-field();
    @include mixins.interactive();
    @include _display();
    @include _with-padding(1px); // border width set on `as-text-field` mixin

    appearance: none; // removes native arrow that opens the select

    &.-absolute {
      position: absolute;
    }

    ~ .ods-icon {
      pointer-events: none;
      position: absolute;
      right: helpers.space(2);
    }

    &.-invalid ~ *,
    &.-touched:invalid ~ * {
      color: helpers.color('content-negative');
    }

    &:disabled {
      &,
      ~ * {
        color: helpers.color('content-disabled');
      }
    }
  }

  :where(.ods-select.-borderless) > .ods-select-native {
    @include mixins.with-inner-focus('action');
    @include _with-padding(); // no border width because border will be unset

    background-color: transparent;
    border: 0;

    &:hover {
      background-color: helpers.color('background-action-subtle-hover');
    }

    &.-invalid,
    &.-touched:invalid {
      @include mixins.with-inner-focus('negative');

      &:hover {
        background-color: helpers.color('background-negative-subtle-hover');
      }
    }

    &:disabled,
    &:disabled:hover {
      background-color: helpers.color('background-disabled');
    }
  }

  .ods-select-output {
    @include helpers.font('300-regular');
    @include _display();
    @include _with-padding();

    pointer-events: none;
  }

  .ods-popover.ods-select-dropdown {
    --popover-gap: #{helpers.space(0.125)};
    width: 100%;

    &:where(.-borderless) {
      width: max-content;
    }
  }
}

@mixin _display() {
  overflow: hidden;
  position: relative;
  text-overflow: ellipsis;
  white-space: nowrap;
}

@mixin _with-padding($border-width: 0) {
  @if type-of($border-width) != number {
    @error '$border-width must be a number';
  }

  $padding-horizontal: helpers.space(2) - $border-width;
  $padding-vertical: helpers.space(1.5) - $border-width;

  padding: $padding-vertical $padding-horizontal;
  padding-right: $padding-horizontal + helpers.space(4); // extra space for icon
}
