import { useTranslation } from 'react-i18next';
import type { XPostData } from './types';

function formatNumber(n: number): string {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
  return String(n);
}

function formatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleString('ja-JP', {
      year: 'numeric', month: 'short', day: 'numeric',
      hour: '2-digit', minute: '2-digit',
    });
  } catch {
    return iso;
  }
}

export function XPostsDetail({ data }: { data: XPostData }) {
  const { t } = useTranslation('embed');
  const { query, posts } = data;

  return (
    <div className="p-6">
      <h2 className="text-lg font-bold text-slate-800 mb-4">
        <span style={{ fontSize: 20 }}>&#120143;</span> {t('searchResults.x', { query })}
      </h2>

      <div className="space-y-4">
        {posts.map((p) => (
          <div key={p.id} className="bg-canvas border border-slate-200 rounded-xl p-4">
            {/* Author header */}
            <div className="flex items-center gap-3 mb-3">
              <img
                src={p.authorImageUrl}
                alt={p.authorScreenName}
                className="rounded-full flex-shrink-0"
                style={{ width: 40, height: 40 }}
                loading="lazy"
              />
              <div>
                <div className="font-semibold text-slate-800" style={{ fontSize: 14 }}>{p.authorName}</div>
                <div className="text-slate-400" style={{ fontSize: 12 }}>@{p.authorScreenName}</div>
              </div>
              <div className="text-slate-400 ml-auto" style={{ fontSize: 11 }}>
                {formatDate(p.createdAt)}
              </div>
            </div>

            {/* Post text */}
            <div className="text-sm text-slate-700 leading-relaxed whitespace-pre-wrap mb-3">
              {p.text}
            </div>

            {/* Metrics */}
            <div className="flex gap-4 text-slate-400 mb-3" style={{ fontSize: 12 }}>
              <span title={t('metrics.likes')}>&#9829; {formatNumber(p.likes)}</span>
              <span title={t('metrics.retweets')}>&#128257; {formatNumber(p.retweets)}</span>
              <span title={t('metrics.replies')}>&#128172; {formatNumber(p.replies)}</span>
              <span title={t('metrics.views')}>&#128065; {formatNumber(p.views)}</span>
            </div>

            {/* Link */}
            <a
              href={p.postUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1 px-3 py-1.5 bg-slate-900 hover:bg-slate-700 text-white text-xs font-semibold rounded-lg no-underline transition-colors"
            >
              {t('viewOn.x')}
            </a>
          </div>
        ))}
      </div>
    </div>
  );
}
