import type { StoryData } from './story-data';
import { toFlagEmoji } from '@/utils/country-flag';
import { getCanonicalApiOrigin } from '@/services/runtime';

const VALID_STORY_TYPES = ['ciianalysis', 'convergence', 'brief'] as const;
type StoryType = typeof VALID_STORY_TYPES[number];

function sanitizeCountryCode(value: string): string {
  const code = String(value || '').trim().toUpperCase();
  return /^[A-Z]{2}$/.test(code) ? code : '';
}

function sanitizeStoryType(value: string | null): StoryType {
  const t = String(value || '').trim().toLowerCase();
  return (VALID_STORY_TYPES as readonly string[]).includes(t) ? (t as StoryType) : 'ciianalysis';
}

// Deep link generator for story sharing
export function generateStoryDeepLink(
  countryCode: string,
  type: 'ciianalysis' | 'convergence' | 'brief' = 'ciianalysis',
  score?: number,
  level?: string
): string {
  const safeCountryCode = sanitizeCountryCode(countryCode);
  const safeType = sanitizeStoryType(type);
  const params = new URLSearchParams({
    c: safeCountryCode,
    t: safeType,
    ts: Date.now().toString()
  });
  if (score !== undefined) params.set('s', String(score));
  if (level) params.set('l', String(level).trim().slice(0, 32));
  return `${getCanonicalApiOrigin()}/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;
  const safeCountryCode = sanitizeCountryCode(countryCode);
  if (!safeCountryCode) return null;
  return {
    countryCode: safeCountryCode,
    type: sanitizeStoryType(url.searchParams.get('t'))
  };
}

// 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');
}

// Share text templates for different platforms
export const shareTexts = {
  twitter: (data: StoryData) =>
    `${toFlagEmoji(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) =>
    `${toFlagEmoji(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) =>
    `${toFlagEmoji(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))}`,
    telegram: `https://t.me/share/url?url=${encodeURIComponent(url)}&text=${encodeURIComponent(shareTexts.telegram(data))}`,
  };
}
