// 工具函数集合
function generateId(prefix = '') {
  const timestamp = Date.now().toString(36);
  const randomStr = Math.random().toString(36).substr(2, 9);
  return `${prefix}${timestamp}_${randomStr}`;
}

function generateLogoFromTitle(title) {
  if (!title || !title.trim()) return '?';
  
  const cleanTitle = title.trim();
  
  // 检查是否包含中文字符
  const chineseMatch = cleanTitle.match(/[\u4e00-\u9fa5]/);
  if (chineseMatch) return chineseMatch[0];
  
  // 处理英文单词
  const words = cleanTitle.split(/\s+/).filter(word => word.length > 0);
  if (words.length >= 2) {
    return (words[0][0] + words[1][0]).toUpperCase();
  } else if (words.length === 1) {
    const word = words[0];
    if (word.length >= 2) {
      return word.substring(0, 1).toUpperCase() + word.substring(1, 2).toLowerCase();
    } else {
      return word.charAt(0).toUpperCase();
    }
  }
  
  return '?';
}

function debounce(func, wait) {
  let timeout;
  return function(...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), wait);
  };
}

function extractDomain(url) {
  try {
    return new URL(url).hostname;
  } catch (_) {
    return '';
  }
}

function formatDate(date) {
  const d = new Date(date);
  return d.toLocaleString('zh-CN');
}

function getRelativeTime(date) {
  const now = new Date();
  const diffMs = now - new Date(date);
  const diffMins = Math.floor(diffMs / 60000);
  const diffHours = Math.floor(diffMs / 3600000);
  const diffDays = Math.floor(diffMs / 86400000);
  
  if (diffMins < 1) return '刚刚';
  if (diffMins < 60) return `${diffMins}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  return formatDate(date);
}

const TextUtils = {
  truncate(text, maxLength, suffix = '...') {
    if (!text || text.length <= maxLength) return text;
    return text.substring(0, maxLength - suffix.length) + suffix;
  }
};

async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch (err) {
    return false;
  }
}

// 验证URL格式
function isValidURL(string) {
  try {
    new URL(string);
    return true;
  } catch (_) {
    // 如果不是完整URL，检查是否是域名格式
    const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
    return domainRegex.test(string) || string.includes('.');
  }
}