// Designer Panel - Integração na Dashboard
const DesignerPanel = () => {
  const [articles, setArticles] = React.useState([]);
  const [queue, setQueue] = React.useState([]);
  const [loading, setLoading] = React.useState(false);
  const [selectedArticle, setSelectedArticle] = React.useState(null);
  const [preview, setPreview] = React.useState(null);

  React.useEffect(() => {
    fetchArticles();
    fetchQueue();
    const interval = setInterval(fetchQueue, 5000);
    return () => clearInterval(interval);
  }, []);

  const fetchArticles = async () => {
    try {
      const res = await fetch('/api/articles');
      const data = await res.json();
      setArticles(data.slice(0, 20));
    } catch (err) {
      console.error('Erro ao buscar artigos:', err);
    }
  };

  const fetchQueue = async () => {
    try {
      const res = await fetch('/api/designer/queue');
      const data = await res.json();
      setQueue(data.posts || []);
    } catch (err) {
      console.error('Erro ao buscar fila:', err);
    }
  };

  const handlePreview = async (articleId) => {
    setLoading(true);
    try {
      const res = await fetch(`/api/designer/preview/${articleId}`);
      const data = await res.json();
      if (data.success) {
        setPreview(data.preview);
        setSelectedArticle(articleId);
      } else {
        alert('Erro: ' + data.error);
      }
    } catch (err) {
      alert('Erro ao gerar preview: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleCreatePost = async (articleId) => {
    setLoading(true);
    try {
      const res = await fetch('/api/designer/create-post', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ article_id: articleId })
      });
      const data = await res.json();
      if (data.success) {
        alert('Post adicionado a fila!');
        setPreview(null);
        setSelectedArticle(null);
        fetchQueue();
      } else {
        alert('Erro: ' + data.error);
      }
    } catch (err) {
      alert('Erro ao criar post: ' + err.message);
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteFromQueue = async (queueId) => {
    if (!confirm('Remover post da fila?')) return;
    try {
      const res = await fetch(`/api/designer/queue/${queueId}`, { method: 'DELETE' });
      const data = await res.json();
      if (data.success) {
        alert('Post removido');
        fetchQueue();
      }
    } catch (err) {
      alert('Erro: ' + err.message);
    }
  };

  return (
    React.createElement('div', { className: 'space-y-6' },
      React.createElement('div', { className: 'flex items-center justify-between' },
        React.createElement('h2', { className: 'text-2xl font-bold' }, 'Designer de Posts'),
        React.createElement('div', { className: 'text-sm text-gray-400' }, queue.length + ' posts na fila')
      ),
      React.createElement('div', { className: 'grid grid-cols-1 lg:grid-cols-3 gap-6' },
        React.createElement('div', { className: 'lg:col-span-2' },
          React.createElement('div', { className: 'card p-6' },
            React.createElement('h3', { className: 'text-lg font-semibold mb-4' }, 'Artigos para Designer'),
            React.createElement('div', { className: 'space-y-3 max-h-96 overflow-y-auto' },
              articles.length === 0
                ? React.createElement('p', { className: 'text-gray-500' }, 'Carregando artigos...')
                : articles.map(article =>
                    React.createElement('div', {
                      key: article.id,
                      className: 'p-4 rounded-lg border cursor-pointer transition ' + (selectedArticle === article.id ? 'border-purple-500 bg-purple-500/10' : 'border-gray-700 hover:border-gray-600'),
                      onClick: () => handlePreview(article.id)
                    },
                      React.createElement('div', { className: 'flex items-start justify-between' },
                        React.createElement('div', { className: 'flex-1' },
                          React.createElement('h4', { className: 'font-semibold text-sm' }, article.title),
                          React.createElement('p', { className: 'text-xs text-gray-400 mt-1' }, article.feedUrl || article.feed_name)
                        ),
                        React.createElement('div', { className: 'ml-2 text-right' },
                          React.createElement('span', { className: 'inline-block px-2 py-1 rounded text-xs font-bold bg-yellow-500/20 text-yellow-400' },
                            Math.round((article.relevanceScore || article.relevance_score || 0) * 100) / 100 + '%'
                          )
                        )
                      )
                    )
                  )
            )
          )
        ),
        React.createElement('div', null,
          React.createElement('div', { className: 'card p-6 sticky top-6' },
            React.createElement('h3', { className: 'text-lg font-semibold mb-4' }, 'Preview'),
            preview
              ? React.createElement('div', { className: 'space-y-4' },
                  React.createElement('img', { src: preview.image_url, alt: 'preview', className: 'w-full rounded-lg border border-gray-700' }),
                  React.createElement('div', { className: 'text-xs space-y-2' },
                    React.createElement('p', null, React.createElement('strong', null, 'Score: '), preview.score + '%'),
                    React.createElement('p', null, React.createElement('strong', null, 'Fonte: '), preview.source)
                  ),
                  React.createElement('button', {
                    onClick: () => handleCreatePost(selectedArticle),
                    disabled: loading,
                    className: 'w-full btn-grad text-white font-semibold py-2 rounded-lg disabled:opacity-50'
                  }, loading ? 'Criando...' : 'Adicionar a Fila'),
                  React.createElement('button', {
                    onClick: () => setPreview(null),
                    className: 'w-full bg-gray-700 hover:bg-gray-600 text-white font-semibold py-2 rounded-lg'
                  }, 'Fechar')
                )
              : React.createElement('p', { className: 'text-gray-500 text-sm' }, 'Clique em um artigo para ver preview')
          )
        )
      ),
      React.createElement('div', { className: 'card p-6' },
        React.createElement('h3', { className: 'text-lg font-semibold mb-4' }, 'Fila de Publicacao'),
        queue.length === 0
          ? React.createElement('p', { className: 'text-gray-500' }, 'Nenhum post na fila')
          : React.createElement('div', { className: 'overflow-x-auto' },
              React.createElement('table', { className: 'w-full text-sm' },
                React.createElement('thead', null,
                  React.createElement('tr', { className: 'border-b border-gray-700' },
                    React.createElement('th', { className: 'text-left py-2 px-4' }, 'ID'),
                    React.createElement('th', { className: 'text-left py-2 px-4' }, 'Artigo'),
                    React.createElement('th', { className: 'text-left py-2 px-4' }, 'Status'),
                    React.createElement('th', { className: 'text-left py-2 px-4' }, 'Criado em'),
                    React.createElement('th', { className: 'text-center py-2 px-4' }, 'Acoes')
                  )
                ),
                React.createElement('tbody', null,
                  queue.map(post =>
                    React.createElement('tr', { key: post.id, className: 'border-b border-gray-800 hover:bg-gray-900/50' },
                      React.createElement('td', { className: 'py-3 px-4' }, post.id),
                      React.createElement('td', { className: 'py-3 px-4 text-xs' }, post.title),
                      React.createElement('td', { className: 'py-3 px-4' },
                        React.createElement('span', { className: 'inline-block px-2 py-1 rounded text-xs bg-yellow-500/20 text-yellow-400' }, post.status)
                      ),
                      React.createElement('td', { className: 'py-3 px-4 text-xs text-gray-400' }, new Date(post.created_at).toLocaleString('pt-BR')),
                      React.createElement('td', { className: 'py-3 px-4 text-center' },
                        React.createElement('button', {
                          onClick: () => handleDeleteFromQueue(post.id),
                          className: 'text-red-400 hover:text-red-300 text-xs font-semibold'
                        }, 'Remover')
                      )
                    )
                  )
                )
              )
            )
      )
    )
  );
};