/**
 * Timezone utilities for formatting dates in user's preferred timezone
 */

// Get user's timezone from localStorage or detect from browser
export function getUserTimezone() {
  try {
    const stored = localStorage.getItem('sociowire:timezone');
    if (stored && stored !== 'null' && stored !== 'undefined') {
      return stored;
    }
  } catch {}
  // Fallback to browser timezone
  try {
    return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
  } catch {
    return 'UTC';
  }
}

// Save user's timezone preference
export function setUserTimezone(tz) {
  try {
    localStorage.setItem('sociowire:timezone', tz || '');
  } catch {}
}

// Format a date string or Date object in the user's timezone
export function formatInUserTimezone(dateInput, options = {}) {
  if (!dateInput) return '';

  const tz = getUserTimezone();
  const date = typeof dateInput === 'string' ? new Date(dateInput) : dateInput;

  if (isNaN(date.getTime())) return '';

  const defaultOptions = {
    timeZone: tz,
    ...options,
  };

  try {
    return new Intl.DateTimeFormat(undefined, defaultOptions).format(date);
  } catch {
    return date.toLocaleString();
  }
}

// Format relative time (e.g., "2 hours ago")
export function formatRelativeTime(dateInput, locale = 'en') {
  if (!dateInput) return '';

  const date = typeof dateInput === 'string' ? new Date(dateInput) : dateInput;
  if (isNaN(date.getTime())) return '';

  const now = new Date();
  const diffMs = now - date;
  const diffSec = Math.floor(diffMs / 1000);
  const diffMin = Math.floor(diffSec / 60);
  const diffHour = Math.floor(diffMin / 60);
  const diffDay = Math.floor(diffHour / 24);

  // Less than 1 minute
  if (diffSec < 60) return locale === 'fr' ? "à l'instant" : 'just now';

  // Less than 1 hour
  if (diffMin < 60) {
    if (locale === 'fr') return `il y a ${diffMin} min`;
    return `${diffMin}m ago`;
  }

  // Less than 24 hours
  if (diffHour < 24) {
    if (locale === 'fr') return `il y a ${diffHour}h`;
    return `${diffHour}h ago`;
  }

  // Less than 7 days
  if (diffDay < 7) {
    if (locale === 'fr') return `il y a ${diffDay}j`;
    return `${diffDay}d ago`;
  }

  // More than 7 days - show formatted date in user's timezone
  return formatInUserTimezone(date, {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

// Format date for display (short format)
export function formatShortDate(dateInput) {
  return formatInUserTimezone(dateInput, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  });
}

// Format datetime for display
export function formatDateTime(dateInput) {
  return formatInUserTimezone(dateInput, {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}

// Format time only
export function formatTime(dateInput) {
  return formatInUserTimezone(dateInput, {
    hour: '2-digit',
    minute: '2-digit',
  });
}

// Format for chat messages (show time, or date+time if different day)
export function formatChatTime(dateInput) {
  if (!dateInput) return '';

  const date = typeof dateInput === 'string' ? new Date(dateInput) : dateInput;
  if (isNaN(date.getTime())) return '';

  const now = new Date();
  const isToday = date.toDateString() === now.toDateString();

  if (isToday) {
    return formatTime(date);
  }

  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  const isYesterday = date.toDateString() === yesterday.toDateString();

  if (isYesterday) {
    return 'Yesterday ' + formatTime(date);
  }

  return formatInUserTimezone(date, {
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
  });
}
