import PublicLayout from '../../components/PublicLayout.jsx'
import PageHeader from '../../components/PageHeader.jsx'
import { Loading, ErrorState, EmptyState } from '../../components/PageState.jsx'
import { useAsync } from '../../lib/useAsync.js'
import { longDate } from '../../lib/format.js'
import { api } from '../../api/client.js'

export default function News() {
  const { loading, error, data } = useAsync(() => api.posts('news'))
  const posts = data || []

  return (
    <PublicLayout section="website">
      <div className="shell-mid page-body">
        <PageHeader
          eyebrow="Development"
          title="News & Updates"
          lead="Progress notes and announcements as Mysticmoon takes shape."
        />
        <section style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {loading && <Loading />}
          {error && <ErrorState message="Could not load news right now." />}
          {!loading && !error && posts.length === 0 && <EmptyState>No news posts yet — check back soon.</EmptyState>}
          {posts.map((p) => (
            <article key={p.id} className="panel" style={{ padding: 28 }}>
              <div
                className="sans"
                style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12, fontSize: '0.74rem', letterSpacing: '0.08em', textTransform: 'uppercase' }}
              >
                <span style={{ color: 'var(--accent)', fontWeight: 700 }}>News</span>
                <span className="dim">{longDate(p.published_at || p.created_at)}</span>
              </div>
              <h2 className="display" style={{ margin: '0 0 10px', fontSize: '1.55rem', color: 'var(--head)' }}>
                {p.title}
              </h2>
              {(p.excerpt || p.body) && (
                <p style={{ margin: 0, color: 'var(--text)', fontSize: '1.04rem' }}>{p.excerpt || stripHtml(p.body)}</p>
              )}
            </article>
          ))}
        </section>
      </div>
    </PublicLayout>
  )
}

function stripHtml(html) {
  if (!html) return ''
  const text = html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim()
  return text.length > 280 ? text.slice(0, 280) + '…' : text
}
