// 掲示板一覧ページ
function CommunityPage({ nav, progress }) {
  const [boards, setBoards] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(function() {
    fetch('/api/board/list')
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error) { setError(data.error); return; }
        setBoards(data.boards);
      })
      .catch(function() { setError('読み込みに失敗しました'); })
      .finally(function() { setLoading(false); });
  }, []);

  const isPaid = progress && progress.membershipStatus === 'active';

  const cardStyle = {
    background: '#fff',
    border: '1px solid #e8e4dc',
    borderRadius: 12,
    padding: '16px 20px',
    marginBottom: 12,
    cursor: 'pointer',
    display: 'flex',
    alignItems: 'center',
    gap: 14,
    transition: 'box-shadow 0.15s',
  };

  return (
    <main className="main-content" style={{ maxWidth: 680, margin: '0 auto', padding: '24px 16px 80px' }}>
      <div style={{ marginBottom: 24 }}>
        <h1 style={{ fontSize: 22, fontWeight: 700, color: '#13294B', marginBottom: 6 }}>掲示板</h1>
        <p style={{ fontSize: 14, color: '#666' }}>仲間と学びを共有しよう。質問・気づき・相談など気軽に投稿してください。</p>
      </div>

      {loading && (
        <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>読み込み中...</div>
      )}

      {error && (
        <div style={{ background: '#fff4f4', border: '1px solid #f5c6c6', borderRadius: 8, padding: 16, color: '#c0392b', fontSize: 14 }}>
          {error}
        </div>
      )}

      {boards && boards.map(function(board) {
        const locked = board.access_level === 'paid' && !isPaid;
        return (
          <div
            key={board.id}
            style={{ ...cardStyle, opacity: locked ? 0.6 : 1 }}
            onClick={function() {
              if (locked) {
                alert('この掲示板は有料プラン限定です。');
                return;
              }
              nav.goBoard(board.id);
            }}
          >
            <div style={{ fontSize: 32, lineHeight: 1 }}>{board.emoji}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontWeight: 700, fontSize: 15, color: '#13294B', marginBottom: 3 }}>
                {board.name}
                {locked && <span style={{ marginLeft: 8, fontSize: 11, background: '#C9731A', color: '#fff', borderRadius: 4, padding: '1px 6px', verticalAlign: 'middle' }}>有料</span>}
              </div>
              <div style={{ fontSize: 12, color: '#777', lineHeight: 1.5 }}>{board.description}</div>
            </div>
            <div style={{ color: '#ccc', fontSize: 18 }}>›</div>
          </div>
        );
      })}

      {boards && boards.length === 0 && !loading && (
        <div style={{ textAlign: 'center', padding: '40px 0', color: '#999', fontSize: 14 }}>
          掲示板はまだありません
        </div>
      )}
    </main>
  );
}

window.CommunityPage = CommunityPage;
