use super::*;

pick! {
  if #[cfg(target_feature="avx2")] {
    #[derive(Default, Clone, Copy, PartialEq, Eq)]
    #[repr(C, align(32))]
    pub struct u8x32 { pub(crate) avx: m256i }
  } else {
    #[derive(Default, Clone, Copy, PartialEq, Eq)]
    #[repr(C, align(32))]
    pub struct u8x32 { pub(crate) a : u8x16, pub(crate) b : u8x16 }
  }
}

int_uint_consts!(u8, 32, u8x32, 256);

unsafe impl Zeroable for u8x32 {}
unsafe impl Pod for u8x32 {}

impl AlignTo for u8x32 {
  type Elem = u8;
}

impl Add for u8x32 {
  type Output = Self;
  #[inline]
  fn add(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: add_i8_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.add(rhs.a),
          b : self.b.add(rhs.b),
        }
      }
    }
  }
}

impl Sub for u8x32 {
  type Output = Self;
  #[inline]
  fn sub(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: sub_i8_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.sub(rhs.a),
          b : self.b.sub(rhs.b),
        }
      }
    }
  }
}

impl Mul for u8x32 {
  type Output = Self;

  #[inline]
  fn mul(self, rhs: Self) -> Self::Output {
    // For x86, this technically can be done explicitly by converting to `i16`
    // then converting back after multiplication, but that may not actually be
    // faster than auto-vectorization.
    let [self_a, self_b]: [u8x16; 2] = cast(self);
    let [rhs_a, rhs_b]: [u8x16; 2] = cast(rhs);
    cast([self_a * rhs_a, self_b * rhs_b])
  }
}

integer_impl_div_rem!(
  u8,
  u8x32,
  [
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
    21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  ],
);

impl Shl for u8x32 {
  type Output = Self;

  /// Shifts lanes by the corresponding lane.
  ///
  /// Bitwise shift-left; yields `self << mask(rhs)`, where mask removes any
  /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth
  /// of the type. (same as `wrapping_shl`)
  #[inline]
  fn shl(self, rhs: Self) -> Self::Output {
    // For x86, this technically can be done explicitly by converting to `u16`
    // or `u32` then converting back after multiplication, but that may not
    // actually be faster than auto-vectorization.
    let [self_a, self_b]: [u8x16; 2] = cast(self);
    let [rhs_a, rhs_b]: [u8x16; 2] = cast(rhs);
    cast([self_a << rhs_a, self_b << rhs_b])
  }
}

impl Shr for u8x32 {
  type Output = Self;

  /// Shifts lanes by the corresponding lane.
  ///
  /// Bitwise shift-right; yields `self >> mask(rhs)`, where mask removes any
  /// high-order bits of `rhs` that would cause the shift to exceed the bitwidth
  /// of the type. (same as `wrapping_shr`)
  #[inline]
  fn shr(self, rhs: Self) -> Self::Output {
    // For x86, this technically can be done explicitly by converting to `u16`
    // or `u32` then converting back after multiplication, but that may not
    // actually be faster than auto-vectorization.
    let [self_a, self_b]: [u8x16; 2] = cast(self);
    let [rhs_a, rhs_b]: [u8x16; 2] = cast(rhs);
    cast([self_a >> rhs_a, self_b >> rhs_b])
  }
}

impl Add<u8> for u8x32 {
  type Output = Self;
  #[inline]
  fn add(self, rhs: u8) -> Self::Output {
    self.add(Self::splat(rhs))
  }
}

impl Sub<u8> for u8x32 {
  type Output = Self;
  #[inline]
  fn sub(self, rhs: u8) -> Self::Output {
    self.sub(Self::splat(rhs))
  }
}

impl Mul<u8> for u8x32 {
  type Output = Self;

  #[inline]
  fn mul(self, rhs: u8) -> Self::Output {
    self * Self::splat(rhs)
  }
}

macro_rules! impl_shl_scalar {
  ($Rhs:ident) => {
    impl Shl<$Rhs> for u8x32 {
      type Output = Self;

      /// Shifts all lanes by a uniform value.
      ///
      /// Bitwise shift-left; yields `self << mask(rhs)`, where mask removes any
      /// high-order bits of `rhs` that would cause the shift to exceed the
      /// bitwidth of the type. (same as `wrapping_shl`)
      #[inline]
      fn shl(self, rhs: $Rhs) -> Self::Output {
        // For x86, this technically can be done explicitly by converting
        // to `u16` or `u32` then converting back after multiplication, but that
        // may not actually be faster than auto-vectorization.
        let [self_a, self_b]: [u8x16; 2] = cast(self);
        cast([self_a << rhs, self_b << rhs])
      }
    }
  };
}
impl_shl_scalar!(i8);
impl_shl_scalar!(u8);
impl_shl_scalar!(i16);
impl_shl_scalar!(u16);
impl_shl_scalar!(i32);
impl_shl_scalar!(u32);
impl_shl_scalar!(i64);
impl_shl_scalar!(u64);
impl_shl_scalar!(i128);
impl_shl_scalar!(u128);

macro_rules! impl_shr_scalar {
  ($Rhs:ident) => {
    impl Shr<$Rhs> for u8x32 {
      type Output = Self;

      /// Shifts all lanes by a uniform value.
      ///
      /// Bitwise shift-right; yields `self >> mask(rhs)`, where mask removes
      /// any high-order bits of `rhs` that would cause the shift to exceed
      /// the bitwidth of the type. (same as `wrapping_shr`)
      #[inline]
      fn shr(self, rhs: $Rhs) -> Self::Output {
        // For x86, this technically can be done explicitly by converting
        // to `u16` or `u32` then converting back after multiplication, but that
        // may not actually be faster than auto-vectorization.
        let [self_a, self_b]: [u8x16; 2] = cast(self);
        cast([self_a >> rhs, self_b >> rhs])
      }
    }
  };
}
impl_shr_scalar!(i8);
impl_shr_scalar!(u8);
impl_shr_scalar!(i16);
impl_shr_scalar!(u16);
impl_shr_scalar!(i32);
impl_shr_scalar!(u32);
impl_shr_scalar!(i64);
impl_shr_scalar!(u64);
impl_shr_scalar!(i128);
impl_shr_scalar!(u128);

impl Add<u8x32> for u8 {
  type Output = u8x32;
  #[inline]
  fn add(self, rhs: u8x32) -> Self::Output {
    u8x32::splat(self).add(rhs)
  }
}

impl Sub<u8x32> for u8 {
  type Output = u8x32;
  #[inline]
  fn sub(self, rhs: u8x32) -> Self::Output {
    u8x32::splat(self).sub(rhs)
  }
}

impl Mul<u8x32> for u8 {
  type Output = u8x32;

  #[inline]
  fn mul(self, rhs: u8x32) -> Self::Output {
    u8x32::splat(self) * rhs
  }
}

impl BitAnd for u8x32 {
  type Output = Self;
  #[inline]
  fn bitand(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
          Self { avx : bitand_m256i(self.avx,rhs.avx) }
      } else {
          Self {
            a : self.a.bitand(rhs.a),
            b : self.b.bitand(rhs.b),
          }
      }
    }
  }
}

impl BitOr for u8x32 {
  type Output = Self;
  #[inline]
  fn bitor(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx : bitor_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.bitor(rhs.a),
          b : self.b.bitor(rhs.b),
        }
      }
    }
  }
}

impl BitXor for u8x32 {
  type Output = Self;
  #[inline]
  fn bitxor(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx : bitxor_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.bitxor(rhs.a),
          b : self.b.bitxor(rhs.b),
        }
      }
    }
  }
}

#[expect(deprecated)]
impl CmpEq for u8x32 {
  type Output = Self;
  #[inline]
  fn simd_eq(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx : cmp_eq_mask_i8_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.simd_eq(rhs.a),
          b : self.b.simd_eq(rhs.b),
        }
      }
    }
  }
}

#[expect(deprecated)]
impl CmpNe for u8x32 {
  type Output = Self;
  #[inline]
  fn simd_ne(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        !self.simd_eq(rhs)
      } else {
        Self {
          a : self.a.simd_ne(rhs.a),
          b : self.b.simd_ne(rhs.b),
        }
      }
    }
  }
}

#[expect(deprecated)]
impl CmpLt for u8x32 {
  type Output = Self;
  #[inline]
  fn simd_lt(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        // Convert from u8 to i8.
        let offset = Self::splat(0x80);
        let self_i8 = self.bitxor(offset).avx;
        let rhs_i8 = rhs.bitxor(offset).avx;
        Self { avx: cmp_gt_mask_i8_m256i(rhs_i8, self_i8)}
      } else {
        Self { a: self.a.simd_lt(rhs.a), b: self.b.simd_lt(rhs.b) }
      }
    }
  }
}

#[expect(deprecated)]
impl CmpLe for u8x32 {
  type Output = Self;
  #[inline]
  fn simd_le(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        // Convert from u8 to i8.
        let offset = Self::splat(0x80);
        let self_i8 = self.bitxor(offset).avx;
        let rhs_i8 = rhs.bitxor(offset).avx;
        let gt_mask = Self { avx : cmp_gt_mask_i8_m256i(self_i8,rhs_i8) };
        Self { avx: gt_mask.bitxor(Self::splat(0xFF)).avx }
      } else {
        Self { a: self.a.simd_le(rhs.a), b: self.b.simd_le(rhs.b) }
      }
    }
  }
}

#[expect(deprecated)]
impl CmpGe for u8x32 {
  type Output = Self;
  #[inline]
  fn simd_ge(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        // Convert from u8 to i8.
        let offset = Self::splat(0x80);
        let self_i8 = self.bitxor(offset).avx;
        let rhs_i8 = rhs.bitxor(offset).avx;
        let lt_mask = Self { avx: cmp_gt_mask_i8_m256i(rhs_i8, self_i8)};
        Self { avx: lt_mask.bitxor(Self::splat(0xFF)).avx }
      } else {
        Self { a: self.a.simd_ge(rhs.a), b: self.b.simd_ge(rhs.b) }
      }
    }
  }
}

#[expect(deprecated)]
impl CmpGt for u8x32 {
  type Output = Self;
  #[inline]
  fn simd_gt(self, rhs: Self) -> Self::Output {
    pick! {
      if #[cfg(target_feature="avx2")] {
        // Convert from u8 to i8.
        let offset = Self::splat(0x80);
        let self_i8 = self.bitxor(offset).avx;
        let rhs_i8 = rhs.bitxor(offset).avx;
        Self { avx : cmp_gt_mask_i8_m256i(self_i8,rhs_i8) }
      } else {
        Self { a: self.a.simd_gt(rhs.a), b: self.b.simd_gt(rhs.b) }
      }
    }
  }
}

impl Not for u8x32 {
  type Output = Self;
  #[inline]
  fn not(self) -> Self {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: self.avx.not()  }
      } else {
        Self {
          a : self.a.not(),
          b : self.b.not(),
        }
      }
    }
  }
}

impl u8x32 {
  #[inline]
  #[must_use]
  pub const fn new(array: [u8; 32]) -> Self {
    unsafe { core::mem::transmute(array) }
  }

  simd_comparison_fns!();

  #[inline]
  #[must_use]
  pub fn blend(self, t: Self, f: Self) -> Self {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: blend_varying_i8_m256i(f.avx, t.avx, self.avx) }
      } else {
        Self {
          a : self.a.blend(t.a, f.a),
          b : self.b.blend(t.b, f.b),
        }
      }
    }
  }

  #[inline]
  #[must_use]
  pub fn reduce_add(self) -> u8 {
    cast(i8x32::reduce_add(cast(self)))
  }

  #[inline]
  #[must_use]
  pub fn reduce_max(self) -> u8 {
    let array: [u8x16; 2] = cast(self);
    array[0].max(array[1]).reduce_max()
  }

  #[inline]
  #[must_use]
  pub fn reduce_min(self) -> u8 {
    let array: [u8x16; 2] = cast(self);
    array[0].min(array[1]).reduce_min()
  }

  #[inline]
  #[must_use]
  pub fn max(self, rhs: Self) -> Self {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: max_u8_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.max(rhs.a),
          b : self.b.max(rhs.b),
        }
      }
    }
  }
  #[inline]
  #[must_use]
  pub fn min(self, rhs: Self) -> Self {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: min_u8_m256i(self.avx,rhs.avx) }
      } else {
        Self {
          a : self.a.min(rhs.a),
          b : self.b.min(rhs.b),
        }
      }
    }
  }

  integer_fn_clamp!();

  #[inline]
  #[must_use]
  pub fn saturating_add(self, rhs: Self) -> Self {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: add_saturating_u8_m256i(self.avx, rhs.avx) }
      } else {
        Self {
          a : self.a.saturating_add(rhs.a),
          b : self.b.saturating_add(rhs.b),
        }
      }
    }
  }
  #[inline]
  #[must_use]
  pub fn saturating_sub(self, rhs: Self) -> Self {
    pick! {
      if #[cfg(target_feature="avx2")] {
        Self { avx: sub_saturating_u8_m256i(self.avx, rhs.avx) }
      } else {
        Self {
          a : self.a.saturating_sub(rhs.a),
          b : self.b.saturating_sub(rhs.b),
        }
      }
    }
  }

  /// Lanewise saturating multiply.
  #[inline]
  #[must_use]
  pub fn saturating_mul(self, rhs: Self) -> Self {
    let [self_a, self_b]: [u8x16; 2] = cast(self);
    let [rhs_a, rhs_b]: [u8x16; 2] = cast(rhs);
    cast([self_a.saturating_mul(rhs_a), self_b.saturating_mul(rhs_b)])
  }

  integer_fn_saturating_div!([
    0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
    21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31,
  ]);

  #[inline]
  #[must_use]
  #[doc(alias("movemask", "move_mask"))]
  pub fn to_bitmask(self) -> u32 {
    i8x32::to_bitmask(cast(self)) as u32
  }

  #[inline]
  #[must_use]
  pub fn any(self) -> bool {
    i8x32::any(cast(self))
  }

  #[inline]
  #[must_use]
  pub fn all(self) -> bool {
    i8x32::all(cast(self))
  }

  /// Returns a new vector with lanes selected from the lanes of the first input
  /// vector a specified in the second input vector `rhs`.
  /// The indices i in range `[0, 15]` select the i-th element of `self`. For
  /// indices outside of the range the resulting lane is `0`.
  ///
  /// This note that is the equivalent of two parallel swizzle operations on the
  /// two halves of the vector, and the indexes each refer to the
  /// corresponding half.
  #[inline]
  pub fn swizzle_half(self, rhs: i8x32) -> i8x32 {
    cast(i8x32::swizzle_half(cast(self), cast(rhs)))
  }

  /// Indices in the range `[0, 15]` will select the i-th element of `self`. If
  /// the high bit of any element of `rhs` is set (negative) then the
  /// corresponding output lane is guaranteed to be zero. Otherwise if the
  /// element of `rhs` is within the range `[32, 127]` then the output lane is
  /// either `0` or `self[rhs[i] % 16]` depending on the implementation.
  ///
  /// This is the equivalent to two parallel swizzle operations on the two
  /// halves of the vector, and the indexes each refer to their corresponding
  /// half.
  #[inline]
  pub fn swizzle_half_relaxed(self, rhs: u8x32) -> u8x32 {
    cast(i8x32::swizzle_half_relaxed(cast(self), cast(rhs)))
  }

  #[inline]
  #[must_use]
  pub fn none(self) -> bool {
    !self.any()
  }

  /// Transpose matrix of 32x32 `u8` matrix. Currently not accelerated.
  #[must_use]
  #[inline]
  pub fn transpose(data: [u8x32; 32]) -> [u8x32; 32] {
    cast(i8x32::transpose(cast(data)))
  }

  #[inline]
  pub fn to_array(self) -> [u8; 32] {
    cast(self)
  }

  #[inline]
  pub fn as_array(&self) -> &[u8; 32] {
    cast_ref(self)
  }

  #[inline]
  pub fn as_mut_array(&mut self) -> &mut [u8; 32] {
    cast_mut(self)
  }
}
