/**
 * 原生能力抽象层 (Native Bridge)
 * ------------------------------------------------------------
 * 目标：业务代码只依赖此模块，未来接入 Capacitor / 微信小程序 webview
 *      时无需改动调用方。
 *
 * 当前实现：纯 Web fallback（浏览器 API / DOM）。
 * 未来切换原生：在 isNative() === true 的分支里替换为
 *   - @capacitor/camera / @capacitor/share / @capacitor/haptics / ...
 *   - 或通过 window.JSBridge 调微信/H5 容器
 *
 * 使用示例：
 *   import { native } from '@/lib/native';
 *   const file = await native.pickImage();
 *   await native.share({ title: '商品', url: location.href });
 *   await native.haptic('light');
 */

export type HapticStyle = 'light' | 'medium' | 'heavy' | 'success' | 'warning' | 'error';

export interface ShareOptions {
  title?: string;
  text?: string;
  url?: string;
}

/** 是否运行在 Capacitor / 原生容器里 */
export function isNative(): boolean {
  if (typeof window === 'undefined') return false;
  return Boolean(
    (window as any).Capacitor?.isNativePlatform?.() ||
      (window as any).__NATIVE_BRIDGE__ ||
      /Capacitor/i.test(navigator.userAgent || '')
  );
}

/** 在 <html> 上挂载 .is-native 标记，供 CSS 适配 */
export function markNativeEnvironment() {
  if (typeof document === 'undefined') return;
  if (isNative()) document.documentElement.classList.add('is-native');
}

/** 拍照 / 从相册选图 —— Web 端走 <input type="file"> */
export function pickImage(opts?: { camera?: boolean }): Promise<File | null> {
  // TODO(capacitor): if (isNative()) return import('@capacitor/camera').then(...);
  return new Promise((resolve) => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*';
    if (opts?.camera) input.capture = 'environment';
    input.onchange = () => resolve(input.files?.[0] ?? null);
    input.click();
  });
}

/** 系统级分享 —— Web Share API → fallback 复制链接 */
export async function share(options: ShareOptions): Promise<boolean> {
  // TODO(capacitor): if (isNative()) return import('@capacitor/share').then(...);
  if (typeof navigator !== 'undefined' && (navigator as any).share) {
    try {
      await (navigator as any).share(options);
      return true;
    } catch {
      return false;
    }
  }
  if (options.url && navigator.clipboard) {
    await navigator.clipboard.writeText(options.url);
    return true;
  }
  return false;
}

/** 触感反馈 —— Web 端走 vibration API */
export function haptic(_style: HapticStyle = 'light') {
  // TODO(capacitor): if (isNative()) return import('@capacitor/haptics').then(...);
  if (typeof navigator !== 'undefined' && 'vibrate' in navigator) {
    const ms = _style === 'heavy' ? 30 : _style === 'medium' ? 15 : 8;
    try {
      navigator.vibrate(ms);
    } catch {
      /* noop */
    }
  }
}

/** 复制到剪贴板 */
export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
}

/** 扫码 —— Web 端暂不支持，返回 null（业务方应回退到手动输入） */
export async function scanBarcode(): Promise<string | null> {
  // TODO(capacitor): if (isNative()) return import('@capacitor/barcode-scanner').then(...);
  console.warn('[native.scanBarcode] 当前 Web 环境暂不支持扫码，请使用原生壳');
  return null;
}

/** 打开外部链接 / 拨号 / 邮件 */
export function openExternal(url: string) {
  // TODO(capacitor): if (isNative()) return import('@capacitor/browser').then(...);
  window.open(url, '_blank', 'noopener,noreferrer');
}

export const native = {
  isNative,
  markNativeEnvironment,
  pickImage,
  share,
  haptic,
  copyToClipboard,
  scanBarcode,
  openExternal,
};

export default native;
