import { type ClassValue, clsx } from 'clsx';
import { NextRequest } from 'next/server';
import { twMerge } from 'tailwind-merge';

/**
 * 合并Tailwind CSS类名的工具函数
 */
export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}

/**
 * 格式化时间显示（秒转换为 mm:ss 格式）
 */
export function formatTime(seconds: number): string {
  if (!seconds || isNaN(seconds)) return '0:00';
  
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
}

/**
 * 格式化文件大小
 */
export function formatFileSize(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

/**
 * 格式化相对时间显示
 */
export function formatRelativeTime(date: string | Date): string {
  const now = new Date();
  const targetDate = new Date(date);
  const diffInSeconds = Math.floor((now.getTime() - targetDate.getTime()) / 1000);
  
  if (diffInSeconds < 60) {
    return '刚刚';
  } else if (diffInSeconds < 3600) {
    const minutes = Math.floor(diffInSeconds / 60);
    return `${minutes}分钟前`;
  } else if (diffInSeconds < 86400) {
    const hours = Math.floor(diffInSeconds / 3600);
    return `${hours}小时前`;
  } else if (diffInSeconds < 2592000) {
    const days = Math.floor(diffInSeconds / 86400);
    return `${days}天前`;
  } else {
    return targetDate.toLocaleDateString('zh-CN');
  }
}

/**
 * 生成唯一ID
 */
export function generateId(): string {
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
}

/**
 * 防抖函数
 */
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  wait: number
): (...args: Parameters<T>) => void {
  let timeout: NodeJS.Timeout;
  
  return (...args: Parameters<T>) => {
    clearTimeout(timeout);
    timeout = setTimeout(() => func(...args), wait);
  };
}

/**
 * 节流函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  limit: number
): (...args: Parameters<T>) => void {
  let inThrottle: boolean;
  
  return (...args: Parameters<T>) => {
    if (!inThrottle) {
      func(...args);
      inThrottle = true;
      setTimeout(() => (inThrottle = false), limit);
    }
  };
}

/**
 * 深拷贝对象
 */
export function deepClone<T>(obj: T): T {
  if (obj === null || typeof obj !== 'object') return obj;
  if (obj instanceof Date) return new Date(obj.getTime()) as unknown as T;
  if (obj instanceof Array) return obj.map(item => deepClone(item)) as unknown as T;
  if (typeof obj === 'object') {
    const clonedObj = {} as { [key: string]: any };
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key]);
      }
    }
    return clonedObj as T;
  }
  return obj;
}

/**
 * 验证文件类型
 */
export function validateFileType(file: File, allowedTypes: string[]): boolean {
  return allowedTypes.some(type => {
    if (type.startsWith('.')) {
      return file.name.toLowerCase().endsWith(type.toLowerCase());
    }
    return file.type.toLowerCase().includes(type.toLowerCase());
  });
}

/**
 * 下载文件
 */
export function downloadFile(url: string, filename: string): void {
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

/**
 * 复制文本到剪贴板
 */
export async function copyToClipboard(text: string): Promise<boolean> {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (err) {
    // 降级方案
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    const success = document.execCommand('copy');
    document.body.removeChild(textArea);
    return success;
  }
}

import { fallbackLng, languages } from '../i18n/settings';

/**
 * 从 NextRequest 中获取语言
 * 检查 'lang' 查询参数或 'Accept-Language' 请求头
 */
export function getLanguageFromRequest(request: NextRequest): string {
  // 优先使用 URL 查询参数中的 'lang'
  const langParam = request.nextUrl.searchParams.get('lang');
  if (langParam && languages.includes(langParam)) {
    return langParam;
  }

  // 否则，尝试从 'Accept-Language' 请求头中获取
  const acceptLanguage = request.headers.get('x-next-locale');
  if (acceptLanguage) {
    const detectedLng = acceptLanguage
      .split(',')
      .map(l => l.split(';')[0])
      .find(l => languages.includes(l));
    if (detectedLng) {
      return detectedLng;
    }
  }
  console.log(fallbackLng)
  // 如果未找到支持的语言，则返回默认语言
  return fallbackLng;
}

import { ReadonlyHeaders } from 'next/dist/server/web/spec-extension/adapters/headers';
import path from 'path';

/**
 * 从请求头和参数中获取真实的路径
 */
export async function getTruePathFromHeaders(headersList: ReadonlyHeaders, langParam: string, isRoot: boolean = false): Promise<string> {
  const pathname = headersList.get('x-next-pathname') || '';
  // console.log('Current pathname (from server):', pathname);
  // console.log('langParam:', langParam);
  if (pathname === '' || !languages.includes(pathname)) {
    if (isRoot) {
      return '/';
    }
    return '';
  }
  return pathname !== langParam ? "/" : "/"+langParam;
}

/**
 * 根据 pathname 和初始语言获取正确的语言路径
 */
export function getTruePathFromPathname(pathname: string, initialLang: string): string {
  const rootPathname = pathname.split('/')[1];
  // console.log('rootPathname:', rootPathname);
  // 处理根路径
  if (pathname === '/' || !languages.includes(rootPathname)) {
    return '';
  }
  // 处理其他路径
  return pathname === '/' ? '/' : '/'+initialLang;
}