
import Theme from './CyberTheme';

const formatDateSafe = (value: any) => {
  if (!value) return '00:00:00';

  if (value instanceof Date) {
    return value.toLocaleDateString('pt-BR');
  }

  if (typeof value === 'string') {
    return value;
  }

  try {
    const parsed = new Date(value);
    if (!isNaN(parsed.getTime())) {
      return parsed.toLocaleDateString('pt-BR');
    }
  } catch {}

  return String(value);
};

export default function ThemeSwitcher({ themeId, posts = [], currentArticle, ...props }: any) {
  const normalizedPosts = (posts || []).map((p: any, i: number) => {
    const data = p?.data || {};

    return {
      ...p,
      ...data,
      id: p?.id || p?.slug || data?.slug || String(i),
      slug: p?.slug || data?.slug || p?.id || String(i),
      title: data?.title || p?.title || 'Sem título',
      excerpt: data?.excerpt || data?.description || p?.excerpt || '',
      date: formatDateSafe(data?.date || data?.pubDate || p?.date || p?.pubDate),
      author: data?.author || p?.author || 'AI_NODE',
      sev: data?.sev || p?.sev || (i % 2 === 0 ? 'CRITICAL' : 'HIGH'),
      content: p?.body || p?.content || ''
    };
  });

  const data = currentArticle?.data || {};

  const normalizedArticle = currentArticle
    ? {
        ...currentArticle,
        ...data,
        id: currentArticle?.id || currentArticle?.slug || data?.slug || 'article',
        slug: currentArticle?.slug || data?.slug || currentArticle?.id || 'article',
        title: data?.title || currentArticle?.title || 'Sem título',
        excerpt: data?.excerpt || data?.description || currentArticle?.excerpt || '',
        date: formatDateSafe(data?.date || data?.pubDate || currentArticle?.date || currentArticle?.pubDate),
        author: data?.author || currentArticle?.author || 'AI_NODE',
        sev: data?.sev || currentArticle?.sev || 'LOW',
        content: currentArticle?.body || currentArticle?.content || ''
      }
    : undefined;

  return (
    <Theme
      themeId={themeId}
      posts={normalizedPosts}
      currentArticle={normalizedArticle}
      {...props}
    />
  );
}
