import { useState, useEffect } from 'react'
import { useTranslation } from 'react-i18next'
import { useStore } from '../store'
import ReportButton from './ui/ReportButton'
import type { CommunityPuzzleItem } from '../api'

export default function CommunityToday() {
  const { t } = useTranslation()
  const [puzzles, setPuzzles] = useState<CommunityPuzzleItem[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    fetch('/api/community-puzzles/today')
      .then(r => r.json())
      .then(d => { setPuzzles(d.puzzles || []); setLoading(false) })
      .catch(() => setLoading(false))
  }, [])

  const play = (id: string) => {
    useStore.getState().loadCommunityPuzzle(id)
    window.history.replaceState(null, '', '/')
    window.location.reload()
  }

  return (
    <div className="app" style={{ minHeight: '100vh' }}>
      <div style={{ maxWidth: '40rem', margin: '0 auto', padding: '2rem 1rem' }}>
        <a href="/" style={{ color: 'var(--text-secondary)', fontSize: '0.7rem', textDecoration: 'none' }}>
          {t('common.back')}
        </a>
        <h1 style={{ fontSize: '1.2rem', margin: '0.5rem 0 0.25rem', fontFamily: 'var(--font-display)' }}>
          {t('communityToday.title')}
        </h1>
        <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)', margin: '0 0 1.5rem' }}>
          {t('communityToday.subtitle')}
        </p>

        {loading && <p style={{ fontSize: '0.7rem', color: 'var(--text-secondary)' }}>{t('common.loading')}</p>}

        {!loading && puzzles.length === 0 && (
          <p style={{ fontSize: '0.7rem', color: 'var(--text-tertiary)' }}>{t('communityToday.none')}</p>
        )}

        <div className="ed-puzzle-grid">
          {puzzles.map(p => (
            <button key={p.id} type="button" className="ed-puzzle-card" onClick={() => play(p.id)}>
              <span className="ed-puzzle-size">{p.width}x{p.height}</span>
              <span className="ed-puzzle-title">{p.title}</span>
              <span className="ed-puzzle-by">
                {p.origin ? `from ${p.origin}` : p.author ? `by ${p.author}` : ''}
              </span>
              <span className="ed-puzzle-report"><ReportButton contentType="puzzle" contentId={p.id} /></span>
            </button>
          ))}
        </div>
      </div>
    </div>
  )
}
