import type { StoryData } from './story-data';

// Deep link generator for story sharing
export function generateStoryDeepLink(
  countryCode: string,
  type: 'ciianalysis' | 'convergence' | 'brief' = 'ciianalysis',
  score?: number,
  level?: string
): string {
  const params = new URLSearchParams({
    c: countryCode,
    t: type,
    ts: Date.now().toString()
  });
  if (score !== undefined) params.set('s', String(score));
  if (level) params.set('l', level);
  return `https://worldmonitor.app/api/story?${params.toString()}`;
}

// Parse deep link parameters
export function parseStoryParams(url: URL): { countryCode: string; type: string } | null {
  const countryCode = url.searchParams.get('c');
  if (!countryCode) return null;
  return {
    countryCode,
    type: url.searchParams.get('t') || 'ciianalysis'
  };
}

// Generate QR code data URL (simple implementation)
export function generateQRCode(data: string, size: number = 200): string {
  // Using a simple QR code library pattern
  // In production, use a library like qrcode or node-qrcode
  const canvas = document.createElement('canvas');
  canvas.width = size;
  canvas.height = size;
  const ctx = canvas.getContext('2d')!;
  
  // Placeholder - would use actual QR library
  ctx.fillStyle = '#ffffff';
  ctx.fillRect(0, 0, size, size);
  ctx.fillStyle = '#000000';
  ctx.font = '14px monospace';
  ctx.textAlign = 'center';
  ctx.fillText('Scan to view', size/2, size/2 - 10);
  ctx.fillText(data.substring(0, 20) + '...', size/2, size/2 + 10);
  
  return canvas.toDataURL('image/png');
}

// Convert 2-letter country code to flag emoji
function countryFlag(code: string): string {
  const upper = code.toUpperCase();
  if (upper.length !== 2) return '';
  return String.fromCodePoint(
    0x1F1E6 + upper.charCodeAt(0) - 65,
    0x1F1E6 + upper.charCodeAt(1) - 65
  );
}

// Share text templates for different platforms
export const shareTexts = {
  twitter: (data: StoryData) =>
    `${countryFlag(data.countryCode)} ${data.countryName} Intelligence Brief\n\n` +
    `Instability: ${data.cii?.score || 'N/A'}/100 (${data.cii?.level || 'N/A'})\n` +
    `${data.threats.critical > 0 ? `⚠️ ${data.threats.critical} critical threats\n` : ''}` +
    `\nGenerated by @WorldMonitorApp`,

  whatsapp: (data: StoryData) =>
    `${countryFlag(data.countryCode)} *${data.countryName} Intelligence Brief*\n\n` +
    `*Instability:* ${data.cii?.score || 'N/A'}/100 (${data.cii?.level || 'N/A'})\n` +
    `*Trend:* ${data.cii?.trend || 'stable'}\n` +
    `${data.threats.critical > 0 ? `*⚠️ Critical:* ${data.threats.critical}\n` : ''}` +
    `${data.threats.high > 0 ? `*🔴 High:* ${data.threats.high}\n` : ''}` +
    `\n📊 View full analysis: ${generateStoryDeepLink(data.countryCode, 'ciianalysis', data.cii?.score, data.cii?.level)}`,

  linkedin: (data: StoryData) =>
    `Intelligence Update: ${data.countryName}\n\n` +
    `Real-time instability assessment:\n` +
    `• Score: ${data.cii?.score || 'N/A'}/100 (${data.cii?.level || 'N/A'})\n` +
    `• 24h change: ${data.cii?.change24h ? (data.cii.change24h > 0 ? '+' : '') + data.cii.change24h : 'N/A'}%\n` +
    `${data.threats.critical > 0 ? `• Critical threats: ${data.threats.critical}\n` : ''}` +
    `\nData via World Monitor - Open source geopolitical intelligence`,

  telegram: (data: StoryData) =>
    `${countryFlag(data.countryCode)} *${data.countryName} Intelligence*\n\n` +
    `📊 Instability: *${data.cii?.score || 'N/A'}/100* (${data.cii?.level || 'N/A'})\n` +
    `📈 Trend: *${data.cii?.trend || 'stable'}*\n` +
    `${data.cii?.change24h ? `📉 24h: *${data.cii.change24h > 0 ? '+' : ''}${data.cii.change24h}*\n` : ''}` +
    `${data.threats.critical > 0 ? `🚨 Critical: *${data.threats.critical}*\n` : ''}` +
    `${data.threats.high > 0 ? `🔴 High: *${data.threats.high}*\n` : ''}` +
    `\n🔗 ${generateStoryDeepLink(data.countryCode, 'ciianalysis', data.cii?.score, data.cii?.level)}`
};

// Pre-generated share URLs
export function getShareUrls(data: StoryData): Record<string, string> {
  const url = generateStoryDeepLink(data.countryCode, 'ciianalysis', data.cii?.score, data.cii?.level);
  const text = encodeURIComponent(shareTexts.twitter(data));
  
  return {
    twitter: `https://twitter.com/intent/tweet?text=${text}&url=${encodeURIComponent(url)}`,
    linkedin: `https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`,
    reddit: `https://reddit.com/submit?url=${encodeURIComponent(url)}&title=${encodeURIComponent(`${data.countryName} Intelligence Brief - World Monitor`)}`,
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`,
    whatsapp: `https://wa.me/?text=${encodeURIComponent(shareTexts.whatsapp(data).replace('\n', '%0A'))}`,
    telegram: `https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(shareTexts.telegram(data).replace('\n', '%0A'))}`,
  };
}
