import * as Haptics from 'expo-haptics';
import { Platform } from 'react-native';

import type { GlideDecision } from '@/domain/glide';

function canVibrate() {
  return Platform.OS !== 'web';
}

function ignoreHapticFailure(error: unknown) {
  if (__DEV__) {
    console.debug('Haptic feedback unavailable', error);
  }
}

export function selectionHaptic() {
  if (!canVibrate()) return;
  void Haptics.selectionAsync().catch(ignoreHapticFailure);
}

export function decisionHaptic(decision: GlideDecision) {
  if (!canVibrate()) return;

  if (Platform.OS === 'android') {
    const type =
      decision === 'clear' ? Haptics.AndroidHaptics.Confirm : Haptics.AndroidHaptics.Reject;
    void Haptics.performAndroidHapticsAsync(type).catch(ignoreHapticFailure);
    return;
  }

  const feedback =
    decision === 'clear'
      ? Haptics.NotificationFeedbackType.Success
      : Haptics.NotificationFeedbackType.Warning;
  void Haptics.notificationAsync(feedback).catch(ignoreHapticFailure);
}

export function completionHaptic() {
  if (!canVibrate()) return;

  if (Platform.OS === 'android') {
    void Haptics.performAndroidHapticsAsync(Haptics.AndroidHaptics.Confirm).catch(
      ignoreHapticFailure
    );
    return;
  }

  void Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success).catch(
    ignoreHapticFailure
  );
}

export function gestureStartHaptic() {
  if (!canVibrate()) return;

  const feedback =
    Platform.OS === 'android'
      ? Haptics.performAndroidHapticsAsync(Haptics.AndroidHaptics.Gesture_Start)
      : Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
  void feedback.catch(ignoreHapticFailure);
}
