import { useApi } from '../hooks/useApi'
import { giteaApi } from '../api/clients'
import type { GitRepo } from '../api/types'

function timeAgo(s: string) {
  const d = Date.now() - new Date(s).getTime()
  if (d < 3600000) return `${Math.floor(d / 60000)}분 전`
  if (d < 86400000) return `${Math.floor(d / 3600000)}시간 전`
  return `${Math.floor(d / 86400000)}일 전`
}

export default function Repos() {
  const { data, loading } = useApi<{ data: GitRepo[] }>(giteaApi, '/repos/search?limit=20')
  const repos = data?.data ?? []

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(340px, 1fr))', gap: 14 }}>
      {loading && <div style={{ color: '#94a3b8', padding: 24 }}>로딩 중...</div>}
      {repos.map(r => (
        <div key={r.id} style={{ background: '#fff', border: '1px solid #e2e8f0',
          borderRadius: 10, padding: '18px 20px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 8 }}>
            <div>
              <div style={{ fontWeight: 600, fontSize: 14, color: '#1a3a6b' }}>{r.name}</div>
              <div style={{ fontSize: 11, color: '#94a3b8', marginTop: 2 }}>{r.full_name}</div>
            </div>
            <span style={{ fontSize: 10, background: '#e8ecff', color: '#4f6ef7',
              padding: '2px 8px', borderRadius: 10, whiteSpace: 'nowrap' }}>git</span>
          </div>
          {r.description && (
            <div style={{ fontSize: 12, color: '#64748b', marginTop: 8, lineHeight: 1.5 }}>{r.description}</div>
          )}
          <div style={{ marginTop: 12, display: 'flex', gap: 10, alignItems: 'center',
            fontSize: 11, color: '#94a3b8' }}>
            <span>🕐 {timeAgo(r.updated_at)}</span>
            <a href={r.clone_url} target="_blank" rel="noreferrer"
              style={{ color: '#4f6ef7', marginLeft: 'auto' }}>저장소 열기 →</a>
          </div>
        </div>
      ))}
      {!loading && repos.length === 0 && (
        <div style={{ padding: 40, color: '#94a3b8', textAlign: 'center' }}>
          Gitea 저장소를 불러올 수 없습니다. 네트워크 설정을 확인하세요.
        </div>
      )}
    </div>
  )
}
