'use client'

import { useState, useEffect } from 'react'
import type { TrumpPost } from '@/types'
import { getPosts } from '@/lib/api'
import PostRow from '@/components/dashboard/PostCards'

export default function PostsPage() {
  const [posts, setPosts] = useState<TrumpPost[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState('all')

  useEffect(() => {
    getPosts(200, 1).then(setPosts).catch(() => {}).finally(() => setLoading(false))
  }, [])

  const filtered = posts.filter(p => {
    if (filter !== 'all' && p.sentiment !== filter) return false
    return true
  })

  const counts = {
    all: posts.length,
    bullish: posts.filter(p => p.sentiment === 'bullish').length,
    bearish: posts.filter(p => p.sentiment === 'bearish').length,
    neutral: posts.filter(p => p.sentiment === 'neutral').length,
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <h1 className="page-title">Signals feed</h1>
          <p className="page-sub">Every post we tracked, every prediction we made. {posts.length} posts in the last 30 days.</p>
        </div>
        <span className="chip"><span className="live-dot" />Streaming</span>
      </div>

      <div className="row between" style={{ marginBottom: 18 }}>
        <div className="nav-tabs" style={{ background: 'var(--bg-sunk)' }}>
          {(['all', 'bullish', 'bearish', 'neutral'] as const).map(f => (
            <button key={f} className={`nav-tab ${filter === f ? 'active' : ''}`} onClick={() => setFilter(f)}>
              {f.charAt(0).toUpperCase() + f.slice(1)} <span style={{ color: 'var(--ink-4)', marginLeft: 4 }}>{counts[f]}</span>
            </button>
          ))}
        </div>
      </div>

      {loading && <div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>Loading…</div>}

      {!loading && filtered.length === 0 ? (
        <div className="card" style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}>
          No posts match the current sentiment filter.
        </div>
      ) : (
        <div className="post-stream">
          {filtered.map(p => (
            <PostRow key={p.id} post={p} />
          ))}
        </div>
      )}
    </div>
  )
}
