import { Capacitor } from "@capacitor/core";
import { Haptics, ImpactStyle } from "@capacitor/haptics";

export interface HapticsOptions {
  /**
   * 振动强度
   * - light: 轻微振动
   * - medium: 中等振动
   * - heavy: 强烈振动
   */
  impact?: ImpactStyle;
  /**
   * 振动时长 (毫秒)
   */
  duration?: number;
}

/**
 * 设备振动 Composable
 */
export function useHaptics() {
  /**
   * 检查设备是否支持振动
   */
  const isHapticsAvailable = computed(() => {
    return Capacitor.isNativePlatform();
  });

  /**
   * 触发振动反馈
   * @param options 振动配置选项
   */
  async function vibrate(options: HapticsOptions = {}) {
    if (!isHapticsAvailable.value) {
      console.warn("Haptics not available on this platform");
      return;
    }

    const { impact = ImpactStyle.Medium, duration } = options;

    try {
      if (duration) {
        // 自定义时长振动
        await Haptics.vibrate({ duration });
      }
      else {
        // 触觉反馈振动
        await Haptics.impact({ style: impact });
      }
    }
    catch (error) {
      console.error("Haptics error:", error);
    }
  }

  /**
   * 轻微振动 (适用于按钮点击)
   */
  async function lightVibrate() {
    await vibrate({ impact: ImpactStyle.Light });
  }

  /**
   * 中等振动 (适用于选择操作)
   */
  async function mediumVibrate() {
    await vibrate({ impact: ImpactStyle.Medium });
  }

  /**
   * 强烈振动 (适用于重要通知)
   */
  async function heavyVibrate() {
    await vibrate({ impact: ImpactStyle.Heavy });
  }

  /**
   * 成功振动模式
   */
  async function successVibrate() {
    await lightVibrate();
    await new Promise(resolve => setTimeout(resolve, 100));
    await lightVibrate();
  }

  /**
   * 错误振动模式
   */
  async function errorVibrate() {
    await heavyVibrate();
    await new Promise(resolve => setTimeout(resolve, 200));
    await heavyVibrate();
    await new Promise(resolve => setTimeout(resolve, 200));
    await heavyVibrate();
  }

  /**
   * 警告振动模式
   */
  async function warningVibrate() {
    await mediumVibrate();
    await new Promise(resolve => setTimeout(resolve, 150));
    await mediumVibrate();
  }

  return {
    isHapticsAvailable,
    vibrate,
    lightVibrate,
    mediumVibrate,
    heavyVibrate,
    successVibrate,
    errorVibrate,
    warningVibrate,
  };
}
