'use client';

import { useState, useEffect, useCallback } from 'react';
import DOMPurify from 'dompurify';
import { NavBar } from '@/components/layout/NavBar';
import { api } from '@/lib/api';

// ==========================================
// SVG Icons
// ==========================================

function IconWrench({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>
    </svg>
  );
}

function IconRocket({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/>
    </svg>
  );
}

function IconGift({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="8" width="18" height="4" rx="1"/><path d="M12 8v13"/><path d="M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7"/><path d="M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5"/>
    </svg>
  );
}

function IconPen({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M17 3a2.85 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5z"/>
    </svg>
  );
}

function IconNewspaper({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2"/><path d="M18 14h-8"/><path d="M15 18h-5"/><path d="M10 6h8v4h-8z"/>
    </svg>
  );
}

function IconEye({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"/><circle cx="12" cy="12" r="3"/>
    </svg>
  );
}

function IconUser({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/>
    </svg>
  );
}

function IconCalendar({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect width="18" height="18" x="3" y="4" rx="2"/><path d="M16 2v4"/><path d="M8 2v4"/><path d="M3 10h18"/>
    </svg>
  );
}

function IconArrowLeft({ size = 16, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="m12 19-7-7 7-7"/><path d="M19 12H5"/>
    </svg>
  );
}

function IconChevronRight({ size = 14, color = 'currentColor' }: { size?: number; color?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
      <path d="m9 18 6-6-6-6"/>
    </svg>
  );
}

// ==========================================
// Types & Data
// ==========================================

type ActuTab = 'all' | 'production' | 'release' | 'promo' | 'blog';

interface BlogPost {
  id: string;
  title: string;
  excerpt: string;
  slug: string;
  content?: string;
  cover_image_url: string | null;
  published_at: string;
  view_count: number;
  author: { username: string };
  category: 'production' | 'release' | 'promo' | 'blog';
}

interface BlogPostsResponse {
  posts: BlogPost[];
  total: number;
  page: number;
  totalPages: number;
}

const TABS: { id: ActuTab; label: string; icon: React.ReactNode; color: string }[] = [
  { id: 'all', label: 'Tout', icon: <IconNewspaper />, color: 'var(--text-secondary)' },
  { id: 'production', label: 'Notes de prod', icon: <IconWrench />, color: 'var(--color-gold)' },
  { id: 'release', label: 'Mises à jour', icon: <IconRocket />, color: '#22c55e' },
  { id: 'promo', label: 'Promotions', icon: <IconGift />, color: 'var(--color-red-light)' },
  { id: 'blog', label: 'Articles', icon: <IconPen />, color: '#60a5fa' },
];

// ==========================================
// HTML sanitizer helper
// ==========================================

function sanitizeHtml(html: string): string {
  return DOMPurify.sanitize(html, {
    ALLOWED_TAGS: [
      'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
      'p', 'br', 'hr',
      'ul', 'ol', 'li',
      'strong', 'em', 'b', 'i', 'u', 's', 'del',
      'a', 'img',
      'blockquote', 'pre', 'code',
      'table', 'thead', 'tbody', 'tr', 'th', 'td',
      'div', 'span',
    ],
    ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'target', 'rel', 'class'],
  });
}

// ==========================================
// Loading Skeleton
// ==========================================

function PostSkeleton() {
  return (
    <div
      className="w-full p-4 rounded-lg animate-pulse"
      style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}
    >
      <div className="flex items-start gap-4">
        <div className="w-11 h-11 rounded-lg flex-shrink-0" style={{ background: 'rgba(255,255,255,0.05)' }} />
        <div className="flex-1 space-y-2">
          <div className="flex items-center gap-2">
            <div className="h-4 w-16 rounded" style={{ background: 'rgba(255,255,255,0.05)' }} />
            <div className="h-3 w-20 rounded" style={{ background: 'rgba(255,255,255,0.03)' }} />
          </div>
          <div className="h-4 w-3/4 rounded" style={{ background: 'rgba(255,255,255,0.05)' }} />
          <div className="h-3 w-full rounded" style={{ background: 'rgba(255,255,255,0.03)' }} />
          <div className="h-3 w-2/3 rounded" style={{ background: 'rgba(255,255,255,0.03)' }} />
        </div>
      </div>
    </div>
  );
}

// ==========================================
// Error State
// ==========================================

function ErrorState({ message, onRetry }: { message: string; onRetry: () => void }) {
  return (
    <div className="p-12 rounded-lg text-center" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
      <div className="mb-4 flex justify-center opacity-40">
        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--color-red-light)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>
        </svg>
      </div>
      <p className="text-sm mb-3" style={{ color: 'var(--text-muted)' }}>
        {message}
      </p>
      <button
        onClick={onRetry}
        className="px-4 py-2 rounded-lg text-xs font-medium transition-all hover:scale-105"
        style={{
          background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
          color: 'white',
        }}
      >
        Réessayer
      </button>
    </div>
  );
}

// ==========================================
// Page
// ==========================================

export default function ActuPage() {
  const [activeTab, setActiveTab] = useState<ActuTab>('all');
  const [selectedPost, setSelectedPost] = useState<BlogPost | null>(null);
  const [posts, setPosts] = useState<BlogPost[]>([]);
  const [allPosts, setAllPosts] = useState<BlogPost[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [detailLoading, setDetailLoading] = useState(false);

  const fetchPosts = useCallback(async (category?: string) => {
    setLoading(true);
    setError(null);
    try {
      const params: Record<string, string | number> = { limit: 50 };
      if (category && category !== 'all') {
        params.category = category;
      }
      const data = await api.blog.getPosts(params) as BlogPostsResponse;
      setPosts(data.posts || []);
      // Si on charge "all", on garde aussi une copie pour la sidebar
      if (!category || category === 'all') {
        setAllPosts(data.posts || []);
      }
    } catch {
      setError('Impossible de charger les articles. Vérifiez votre connexion.');
      setPosts([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // Charger les posts au montage et quand le tab change
  useEffect(() => {
    fetchPosts(activeTab);
  }, [activeTab, fetchPosts]);

  const handleSelectPost = async (post: BlogPost) => {
    setDetailLoading(true);
    try {
      const fullPost = await api.blog.getPost(post.id) as BlogPost;
      setSelectedPost(fullPost);
    } catch {
      // En cas d'erreur, on affiche quand même le post avec les données disponibles
      setSelectedPost(post);
    } finally {
      setDetailLoading(false);
    }
  };

  const handleBack = () => {
    setSelectedPost(null);
  };

  const handleTabChange = (tab: ActuTab) => {
    setActiveTab(tab);
    setSelectedPost(null);
  };

  return (
    <div className="min-h-screen" style={{ background: 'var(--bg-primary)' }}>
      <NavBar />

      <div className="max-w-[1100px] mx-auto px-4 py-6">
        {/* Header */}
        <div className="flex items-center justify-between mb-6">
          <div className="flex items-center gap-3">
            {selectedPost && (
              <button
                onClick={handleBack}
                className="p-2 rounded-lg transition-all hover:scale-105"
                style={{ background: 'rgba(255,255,255,0.05)', border: '1px solid var(--border-dark)' }}
              >
                <IconArrowLeft color="var(--text-secondary)" />
              </button>
            )}
            <div>
              <h2 className="font-gothic text-2xl text-gold-gradient">
                {selectedPost ? selectedPost.title : 'Actualités'}
              </h2>
              {!selectedPost && (
                <p className="text-xs mt-0.5" style={{ color: 'var(--text-muted)' }}>
                  Développement, mises à jour et annonces
                </p>
              )}
            </div>
          </div>
        </div>

        {/* Tabs */}
        {!selectedPost && (
          <div className="flex gap-1.5 mb-6 overflow-x-auto pb-1">
            {TABS.map((tab) => {
              const isActive = activeTab === tab.id;
              return (
                <button
                  key={tab.id}
                  onClick={() => handleTabChange(tab.id)}
                  className="flex items-center gap-2 px-4 py-2 rounded-lg text-xs font-medium whitespace-nowrap transition-all"
                  style={{
                    background: isActive
                      ? 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))'
                      : 'rgba(255,255,255,0.03)',
                    color: isActive ? 'white' : 'var(--text-secondary)',
                    border: isActive ? 'none' : '1px solid var(--border-dark)',
                  }}
                >
                  <span style={{ color: isActive ? 'white' : tab.color }}>{tab.icon}</span>
                  {tab.label}
                </button>
              );
            })}
          </div>
        )}

        {/* Content */}
        {detailLoading ? (
          <div className="flex items-center justify-center py-16">
            <div
              className="w-8 h-8 border-2 rounded-full animate-spin"
              style={{ borderColor: 'var(--border-dark)', borderTopColor: 'var(--color-gold)' }}
            />
          </div>
        ) : selectedPost ? (
          <PostDetail post={selectedPost} />
        ) : (
          <div className="grid grid-cols-1 lg:grid-cols-[1fr_300px] gap-5">
            {/* Main */}
            <div className="space-y-3">
              {loading ? (
                <>
                  <PostSkeleton />
                  <PostSkeleton />
                  <PostSkeleton />
                </>
              ) : error ? (
                <ErrorState message={error} onRetry={() => fetchPosts(activeTab)} />
              ) : posts.length === 0 ? (
                <EmptyState />
              ) : (
                posts.map((post) => (
                  <PostCard key={post.id} post={post} onClick={() => handleSelectPost(post)} />
                ))
              )}
            </div>

            {/* Sidebar Right */}
            <aside className="hidden lg:block space-y-4">
              <SidebarRecent posts={allPosts} onSelect={handleSelectPost} />
              <SidebarCategories tabs={TABS} posts={allPosts} onSelect={(id) => handleTabChange(id)} />
              <SidebarCTA />
            </aside>
          </div>
        )}
      </div>
    </div>
  );
}

// ==========================================
// Post Card
// ==========================================

function PostCard({ post, onClick }: { post: BlogPost; onClick: () => void }) {
  const tab = TABS.find(t => t.id === post.category);
  const typeLabels: Record<string, string> = {
    production: 'Production',
    release: 'Mise à jour',
    promo: 'Promotion',
    blog: 'Article',
  };

  return (
    <button
      onClick={onClick}
      className="w-full text-left p-4 rounded-lg transition-all hover:translate-x-1 group"
      style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}
    >
      <div className="flex items-start gap-4">
        <div
          className="w-11 h-11 rounded-lg flex items-center justify-center flex-shrink-0 transition-transform group-hover:scale-110"
          style={{ background: (tab?.color || '#666') + '12', color: tab?.color }}
        >
          {tab?.icon || <IconNewspaper />}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <span
              className="px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wide"
              style={{ background: (tab?.color || '#666') + '15', color: tab?.color }}
            >
              {typeLabels[post.category] || post.category}
            </span>
            <span className="flex items-center gap-1 text-[11px]" style={{ color: 'var(--text-muted)' }}>
              <IconCalendar size={10} />
              {new Date(post.published_at).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long' })}
            </span>
          </div>

          <h3 className="text-sm font-medium mb-1 group-hover:underline" style={{ color: 'var(--text-primary)' }}>
            {post.title}
          </h3>

          <p className="text-xs line-clamp-2 leading-relaxed" style={{ color: 'var(--text-muted)' }}>
            {post.excerpt}
          </p>

          <div className="flex items-center gap-4 mt-2">
            <span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
              <IconUser size={10} />{post.author?.username || 'Anonyme'}
            </span>
            <span className="flex items-center gap-1 text-[10px]" style={{ color: 'var(--text-muted)' }}>
              <IconEye size={10} />{post.view_count}
            </span>
            <span className="flex items-center gap-1 text-[10px] ml-auto" style={{ color: 'var(--color-gold)' }}>
              Lire<IconChevronRight size={10} />
            </span>
          </div>
        </div>
      </div>
    </button>
  );
}

// ==========================================
// Post Detail
// ==========================================

function PostDetail({ post }: { post: BlogPost }) {
  const tab = TABS.find(t => t.id === post.category);
  const typeLabels: Record<string, string> = {
    production: 'Production',
    release: 'Mise à jour',
    promo: 'Promotion',
    blog: 'Article',
  };

  return (
    <article
      className="rounded-lg overflow-hidden"
      style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}
    >
      <div
        className="px-6 py-3 flex items-center gap-3 flex-wrap"
        style={{ borderBottom: '1px solid var(--border-dark)', background: 'rgba(255,255,255,0.02)' }}
      >
        <span
          className="px-2 py-0.5 rounded text-[9px] font-bold uppercase tracking-wide"
          style={{ background: (tab?.color || '#666') + '15', color: tab?.color }}
        >
          {typeLabels[post.category] || post.category}
        </span>
        <span className="flex items-center gap-1.5 text-[11px]" style={{ color: 'var(--text-muted)' }}>
          <IconCalendar size={11} />
          {new Date(post.published_at).toLocaleDateString('fr-FR', { day: 'numeric', month: 'long', year: 'numeric' })}
        </span>
        <span className="flex items-center gap-1.5 text-[11px]" style={{ color: 'var(--text-muted)' }}>
          <IconUser size={11} />{post.author?.username || 'Anonyme'}
        </span>
        <span className="flex items-center gap-1.5 text-[11px]" style={{ color: 'var(--text-muted)' }}>
          <IconEye size={11} />{post.view_count} vues
        </span>
      </div>

      <div className="px-6 py-6">
        <div className="text-sm leading-relaxed space-y-4" style={{ color: 'var(--text-secondary)' }}>
          {post.content ? (
            <div
              className="prose prose-invert prose-sm max-w-none
                [&_h1]:text-lg [&_h1]:font-bold [&_h1]:text-[var(--text-primary)] [&_h1]:mb-3
                [&_h2]:text-base [&_h2]:font-bold [&_h2]:text-[var(--text-primary)] [&_h2]:mb-2
                [&_h3]:text-sm [&_h3]:font-semibold [&_h3]:text-[var(--text-primary)] [&_h3]:mb-2
                [&_p]:mb-3 [&_p]:leading-relaxed
                [&_a]:text-[var(--color-gold)] [&_a]:underline
                [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:mb-3
                [&_ol]:list-decimal [&_ol]:pl-5 [&_ol]:mb-3
                [&_li]:mb-1
                [&_blockquote]:border-l-2 [&_blockquote]:border-[var(--color-gold)] [&_blockquote]:pl-4 [&_blockquote]:italic [&_blockquote]:opacity-80
                [&_code]:bg-[rgba(255,255,255,0.05)] [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:rounded [&_code]:text-xs
                [&_pre]:bg-[rgba(255,255,255,0.03)] [&_pre]:p-4 [&_pre]:rounded-lg [&_pre]:overflow-x-auto
                [&_img]:rounded-lg [&_img]:max-w-full
                [&_hr]:border-[var(--border-dark)]"
              dangerouslySetInnerHTML={{ __html: sanitizeHtml(post.content) }}
            />
          ) : (
            <p>{post.excerpt}</p>
          )}
        </div>
      </div>
    </article>
  );
}

// ==========================================
// Sidebar Components
// ==========================================

function SidebarRecent({ posts, onSelect }: { posts: BlogPost[]; onSelect: (p: BlogPost) => void }) {
  return (
    <div className="rounded-lg p-4" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
      <h3 className="text-[10px] uppercase tracking-widest font-bold mb-3" style={{ color: 'var(--color-gold)' }}>
        Récents
      </h3>
      <div className="space-y-2.5">
        {posts.length === 0 ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun article récent.</p>
        ) : (
          posts.slice(0, 4).map(p => (
            <button key={p.id} onClick={() => onSelect(p)} className="w-full text-left group flex items-start gap-2">
              <div
                className="w-1.5 h-1.5 rounded-full mt-1.5 flex-shrink-0"
                style={{ background: TABS.find(t => t.id === p.category)?.color || 'var(--text-muted)' }}
              />
              <div className="min-w-0">
                <p className="text-xs font-medium truncate group-hover:underline" style={{ color: 'var(--text-primary)' }}>
                  {p.title}
                </p>
                <p className="text-[10px] mt-0.5" style={{ color: 'var(--text-muted)' }}>
                  {new Date(p.published_at).toLocaleDateString('fr-FR', { day: 'numeric', month: 'short' })}
                </p>
              </div>
            </button>
          ))
        )}
      </div>
    </div>
  );
}

function SidebarCategories({ tabs, posts, onSelect }: { tabs: typeof TABS; posts: BlogPost[]; onSelect: (id: ActuTab) => void }) {
  return (
    <div className="rounded-lg p-4" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
      <h3 className="text-[10px] uppercase tracking-widest font-bold mb-3" style={{ color: 'var(--color-gold)' }}>
        Catégories
      </h3>
      <div className="space-y-1.5">
        {tabs.filter(t => t.id !== 'all').map(tab => {
          const count = posts.filter(p => p.category === tab.id).length;
          return (
            <button
              key={tab.id}
              onClick={() => onSelect(tab.id)}
              className="w-full flex items-center justify-between px-2 py-1.5 rounded text-xs transition-all hover:bg-white/5"
            >
              <span className="flex items-center gap-2">
                <span style={{ color: tab.color }}>{tab.icon}</span>
                <span style={{ color: 'var(--text-secondary)' }}>{tab.label}</span>
              </span>
              <span className="font-mono text-[10px]" style={{ color: 'var(--text-muted)' }}>{count}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function SidebarCTA() {
  const [email, setEmail] = useState('');
  const [status, setStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [message, setMessage] = useState('');

  const handleSubscribe = async () => {
    if (!email.trim() || !email.includes('@')) {
      setStatus('error');
      setMessage('Entrez un e-mail valide');
      return;
    }
    setStatus('loading');
    try {
      const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'https://api.mafiaz.world'}/api/newsletter/subscribe-email`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email: email.trim() }),
      });
      const data = await res.json();
      if (res.ok) {
        setStatus('success');
        setMessage(data.message || 'Inscription confirmée !');
        setEmail('');
      } else {
        setStatus('error');
        setMessage(data.error || 'Erreur');
      }
    } catch {
      setStatus('error');
      setMessage('Serveur indisponible');
    }
  };

  return (
    <div
      className="rounded-lg p-4 text-center"
      style={{
        background: 'linear-gradient(135deg, rgba(196,30,30,0.08), rgba(196,30,30,0.02))',
        border: '1px solid rgba(196,30,30,0.2)',
      }}
    >
      <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="var(--color-gold)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="mx-auto mb-2">
        <rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>
      </svg>
      <p className="text-xs font-medium mb-1" style={{ color: 'var(--text-primary)' }}>Ne manquez rien</p>
      <p className="text-[10px] mb-3" style={{ color: 'var(--text-muted)' }}>
        Recevez les actualités par e-mail.
      </p>

      {status === 'success' ? (
        <div className="py-2 px-3 rounded-lg text-xs font-medium" style={{ background: 'rgba(34,197,94,0.1)', color: '#22c55e' }}>
          {message}
        </div>
      ) : (
        <>
          <input
            type="email"
            value={email}
            onChange={(e) => { setEmail(e.target.value); setStatus('idle'); }}
            onKeyDown={(e) => e.key === 'Enter' && handleSubscribe()}
            placeholder="votre@email.com"
            className="w-full px-3 py-2 rounded-lg text-xs mb-2"
            style={{
              background: 'var(--bg-card)',
              border: '1px solid var(--border-dark)',
              color: 'var(--text-primary)',
              outline: 'none',
            }}
          />
          {status === 'error' && (
            <p className="text-[10px] mb-2" style={{ color: 'var(--color-red-light)' }}>{message}</p>
          )}
          <button
            onClick={handleSubscribe}
            disabled={status === 'loading'}
            className="w-full py-2 rounded-lg text-xs font-bold transition-all hover:scale-105"
            style={{
              background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))',
              color: 'white',
              opacity: status === 'loading' ? 0.6 : 1,
            }}
          >
            {status === 'loading' ? 'Inscription...' : "S'inscrire"}
          </button>
        </>
      )}
    </div>
  );
}

function EmptyState() {
  return (
    <div className="p-12 rounded-lg text-center" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
      <div className="mb-4 flex justify-center opacity-20">
        <IconNewspaper size={48} color="var(--text-muted)" />
      </div>
      <p className="text-sm" style={{ color: 'var(--text-muted)' }}>
        Aucun article dans cette catégorie pour le moment.
      </p>
    </div>
  );
}
