import { getPayload } from 'payload'
import Link from 'next/link'
import config from '@payload-config'

export const dynamic = 'force-dynamic'

export default async function HomePage() {
  let posts: any[] = []
  try {
    const payload = await getPayload({ config })
    const { docs } = await payload.find({
      collection: 'posts',
      limit: 10,
      sort: '-createdAt',
    })
    posts = docs
  } catch (e) {
    // Table might not exist yet - that's OK for initial setup
    console.warn('Could not fetch posts:', e)
  }

  return (
    <main style={{ padding: '2rem', maxWidth: '1200px', margin: '0 auto' }}>
      <header style={{ marginBottom: '3rem', borderBottom: '1px solid #eee', paddingBottom: '1rem' }}>
        <h1 style={{ fontSize: '2.5rem', marginBottom: '0.5rem' }}>
          Next.js + Payload CMS
        </h1>
        <p style={{ color: '#666' }}>
          Welcome to your new website. Edit <code>src/app/(frontend)/page.tsx</code> to customize.
        </p>
      </header>

      <section>
        <h2 style={{ fontSize: '1.5rem', marginBottom: '1rem' }}>Recent Posts</h2>
        
        {posts.length === 0 ? (
          <p style={{ color: '#888' }}>
            No posts yet. Go to{' '}
            <Link href="/admin" style={{ color: '#0070f3' }}>
              Admin Panel
            </Link>{' '}
            to create your first post.
          </p>
        ) : (
          <ul style={{ listStyle: 'none', padding: 0 }}>
            {posts.map((post) => (
              <li
                key={post.id}
                style={{
                  padding: '1rem',
                  marginBottom: '1rem',
                  border: '1px solid #eee',
                  borderRadius: '8px',
                }}
              >
                <Link
                  href={`/posts/${post.slug || post.id}`}
                  style={{ textDecoration: 'none', color: 'inherit' }}
                >
                  <h3 style={{ margin: 0, marginBottom: '0.5rem' }}>{post.title as string}</h3>
                  {post.createdAt && (
                    <p style={{ margin: 0, fontSize: '0.875rem', color: '#888' }}>
                      {new Date(post.createdAt).toLocaleDateString('th-TH', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric',
                      })}
                    </p>
                  )}
                </Link>
              </li>
            ))}
          </ul>
        )}
      </section>

      <footer style={{ marginTop: '4rem', paddingTop: '2rem', borderTop: '1px solid #eee' }}>
        <Link href="/admin" style={{ color: '#0070f3' }}>
          Go to Admin Panel
        </Link>
      </footer>
    </main>
  )
}
