// スレッド一覧ページ（掲示板詳細）
function BoardPage({ nav, progress, boardId }) {
  const [board, setBoard] = React.useState(null);
  const [posts, setPosts] = React.useState([]);
  const [hasMore, setHasMore] = React.useState(false);
  const [page, setPage] = React.useState(1);
  const [loading, setLoading] = React.useState(true);
  const [loadingMore, setLoadingMore] = React.useState(false);
  const [error, setError] = React.useState(null);

  // ニックネームモーダル
  const [nickModal, setNickModal] = React.useState(false);
  const [nickInput, setNickInput] = React.useState('');
  const [nickSaving, setNickSaving] = React.useState(false);
  const [nickError, setNickError] = React.useState('');
  const [displayName, setDisplayName] = React.useState(null);

  // 投稿フォーム
  const [showForm, setShowForm] = React.useState(false);
  const [postTitle, setPostTitle] = React.useState('');
  const [postBody, setPostBody] = React.useState('');
  const [postImage, setPostImage] = React.useState('');
  const [imageFile, setImageFile] = React.useState(null);
  const [uploading, setUploading] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [formError, setFormError] = React.useState('');

  function fetchPosts(pageNum, replace) {
    var fn = replace ? setLoading : setLoadingMore;
    fn(true);
    fetch('/api/board/' + boardId + '/posts?page=' + pageNum)
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error) { setError(data.error); return; }
        setBoard(data.board);
        if (replace) {
          setPosts(data.posts);
        } else {
          setPosts(function(prev) { return prev.concat(data.posts); });
        }
        setHasMore(data.hasMore);
      })
      .catch(function() { setError('読み込みに失敗しました'); })
      .finally(function() { fn(false); });
  }

  React.useEffect(function() {
    if (!boardId) return;
    fetchPosts(1, true);
    // ニックネーム確認
    fetch('/api/board/profile')
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.profile && data.profile.display_name) {
          setDisplayName(data.profile.display_name);
        }
      })
      .catch(function() {});
  }, [boardId]);

  function loadMore() {
    var next = page + 1;
    setPage(next);
    fetchPosts(next, false);
  }

  function handlePostButtonClick() {
    if (!displayName) {
      setNickModal(true);
      return;
    }
    setShowForm(true);
  }

  function saveNickname() {
    var name = nickInput.trim();
    if (name.length < 2 || name.length > 12) {
      setNickError('2〜12文字で入力してください');
      return;
    }
    setNickSaving(true);
    setNickError('');
    fetch('/api/board/profile', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ displayName: name }),
    })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error) { setNickError(data.error); return; }
        setDisplayName(data.profile.display_name);
        setNickModal(false);
        setNickInput('');
        setShowForm(true);
      })
      .catch(function() { setNickError('保存に失敗しました'); })
      .finally(function() { setNickSaving(false); });
  }

  function handleImageChange(e) {
    var file = e.target.files && e.target.files[0];
    if (!file) return;
    setImageFile(file);
  }

  function uploadImage(file) {
    var fd = new FormData();
    fd.append('image', file);
    setUploading(true);
    return fetch('/api/board/upload-image', { method: 'POST', body: fd })
      .then(function(r) { return r.json(); })
      .then(function(data) {
        if (data.error) throw new Error(data.error);
        return data.url;
      })
      .finally(function() { setUploading(false); });
  }

  function submitPost() {
    if (!postTitle.trim()) { setFormError('タイトルを入力してください'); return; }
    if (!postBody.trim()) { setFormError('本文を入力してください'); return; }
    setFormError('');
    setSubmitting(true);

    var doSubmit = function(imageUrl) {
      fetch('/api/board/' + boardId + '/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: postTitle.trim(), body: postBody.trim(), imageUrl: imageUrl || null }),
      })
        .then(function(r) { return r.json(); })
        .then(function(data) {
          if (data.error) { setFormError(data.error); return; }
          setPostTitle('');
          setPostBody('');
          setPostImage('');
          setImageFile(null);
          setShowForm(false);
          fetchPosts(1, true);
          setPage(1);
        })
        .catch(function() { setFormError('投稿に失敗しました'); })
        .finally(function() { setSubmitting(false); });
    };

    if (imageFile) {
      uploadImage(imageFile)
        .then(function(url) { doSubmit(url); })
        .catch(function(e) { setFormError(e.message || '画像のアップロードに失敗しました'); setSubmitting(false); });
    } else {
      doSubmit(null);
    }
  }

  function formatDate(dateStr) {
    var d = new Date(dateStr);
    return d.getFullYear() + '/' + String(d.getMonth() + 1).padStart(2, '0') + '/' + String(d.getDate()).padStart(2, '0');
  }

  var cardStyle = {
    background: '#fff',
    border: '1px solid #e8e4dc',
    borderRadius: 12,
    padding: '14px 16px',
    marginBottom: 10,
  };

  return (
    <main className="main-content" style={{ maxWidth: 680, margin: '0 auto', padding: '24px 16px 80px' }}>
      {/* ニックネームモーダル */}
      {nickModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 16 }}>
          <div style={{ background: '#fff', borderRadius: 16, padding: 24, width: '100%', maxWidth: 360 }}>
            <h2 style={{ fontSize: 18, fontWeight: 700, color: '#13294B', marginBottom: 8 }}>ニックネームを設定</h2>
            <p style={{ fontSize: 13, color: '#666', marginBottom: 16, lineHeight: 1.6 }}>掲示板に表示される名前です。あとから変更できます。</p>
            <input
              type="text"
              placeholder="例: 株初心者たろう"
              value={nickInput}
              onChange={function(e) { setNickInput(e.target.value); }}
              maxLength={12}
              style={{ width: '100%', padding: '10px 12px', border: '1px solid #ddd', borderRadius: 8, fontSize: 15, boxSizing: 'border-box', marginBottom: 8 }}
            />
            <div style={{ fontSize: 11, color: '#999', marginBottom: 12 }}>{nickInput.length}/12文字</div>
            {nickError && <div style={{ color: '#c0392b', fontSize: 13, marginBottom: 10 }}>{nickError}</div>}
            <div style={{ display: 'flex', gap: 10 }}>
              <button
                onClick={function() { setNickModal(false); setNickInput(''); setNickError(''); }}
                style={{ flex: 1, padding: '10px 0', background: '#f5f2eb', border: 'none', borderRadius: 8, fontWeight: 600, cursor: 'pointer', fontSize: 14 }}
              >キャンセル</button>
              <button
                onClick={saveNickname}
                disabled={nickSaving}
                style={{ flex: 2, padding: '10px 0', background: '#13294B', color: '#fff', border: 'none', borderRadius: 8, fontWeight: 700, cursor: 'pointer', fontSize: 14, opacity: nickSaving ? 0.7 : 1 }}
              >{nickSaving ? '保存中...' : '決定して投稿へ'}</button>
            </div>
          </div>
        </div>
      )}

      {/* 戻るボタン + タイトル */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <button
          onClick={function() { nav.goCommunity(); }}
          style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 22, color: '#13294B', padding: 0, lineHeight: 1 }}
        >‹</button>
        <h1 style={{ fontSize: 20, fontWeight: 700, color: '#13294B', margin: 0 }}>
          {board ? board.emoji + ' ' + board.name : '...'}
        </h1>
      </div>

      {/* 投稿ボタン */}
      {!showForm && (
        <button
          onClick={handlePostButtonClick}
          style={{ width: '100%', padding: '12px 0', background: '#13294B', color: '#fff', border: 'none', borderRadius: 10, fontWeight: 700, fontSize: 15, cursor: 'pointer', marginBottom: 20 }}
        >+ 新しいスレッドを投稿する</button>
      )}

      {/* 投稿フォーム */}
      {showForm && (
        <div style={{ background: '#fff', border: '1px solid #e8e4dc', borderRadius: 12, padding: 20, marginBottom: 20 }}>
          <h3 style={{ fontSize: 15, fontWeight: 700, color: '#13294B', marginBottom: 12 }}>新規投稿</h3>
          <div style={{ marginBottom: 10 }}>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#555', display: 'block', marginBottom: 4 }}>タイトル（50文字以内）</label>
            <input
              type="text"
              placeholder="例: 移動平均線の使い方が分かりません"
              value={postTitle}
              onChange={function(e) { setPostTitle(e.target.value); }}
              maxLength={50}
              style={{ width: '100%', padding: '9px 12px', border: '1px solid #ddd', borderRadius: 8, fontSize: 14, boxSizing: 'border-box' }}
            />
          </div>
          <div style={{ marginBottom: 10 }}>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#555', display: 'block', marginBottom: 4 }}>本文（1000文字以内）</label>
            <textarea
              placeholder="質問・気づき・相談など自由に書いてください"
              value={postBody}
              onChange={function(e) { setPostBody(e.target.value); }}
              maxLength={1000}
              rows={5}
              style={{ width: '100%', padding: '9px 12px', border: '1px solid #ddd', borderRadius: 8, fontSize: 14, boxSizing: 'border-box', resize: 'vertical' }}
            />
            <div style={{ fontSize: 11, color: '#999', textAlign: 'right' }}>{postBody.length}/1000</div>
          </div>
          <div style={{ marginBottom: 12 }}>
            <label style={{ fontSize: 12, fontWeight: 600, color: '#555', display: 'block', marginBottom: 4 }}>画像（任意・5MB以内）</label>
            <input
              type="file"
              accept="image/jpeg,image/png,image/webp,image/gif"
              onChange={handleImageChange}
              style={{ fontSize: 13 }}
            />
            {uploading && <div style={{ fontSize: 12, color: '#999', marginTop: 4 }}>アップロード中...</div>}
          </div>
          {formError && <div style={{ color: '#c0392b', fontSize: 13, marginBottom: 10 }}>{formError}</div>}
          <div style={{ display: 'flex', gap: 10 }}>
            <button
              onClick={function() { setShowForm(false); setFormError(''); setPostTitle(''); setPostBody(''); setImageFile(null); }}
              style={{ flex: 1, padding: '10px 0', background: '#f5f2eb', border: 'none', borderRadius: 8, fontWeight: 600, cursor: 'pointer', fontSize: 14 }}
            >キャンセル</button>
            <button
              onClick={submitPost}
              disabled={submitting || uploading}
              style={{ flex: 2, padding: '10px 0', background: '#13294B', color: '#fff', border: 'none', borderRadius: 8, fontWeight: 700, fontSize: 14, cursor: 'pointer', opacity: (submitting || uploading) ? 0.7 : 1 }}
            >{submitting ? '投稿中...' : '投稿する'}</button>
          </div>
        </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>
      )}

      {!loading && posts.length === 0 && (
        <div style={{ textAlign: 'center', padding: '40px 0', color: '#999', fontSize: 14 }}>
          まだスレッドがありません。最初の投稿者になりましょう！
        </div>
      )}

      {posts.map(function(post) {
        return (
          <div
            key={post.id}
            style={{ ...cardStyle, cursor: 'pointer' }}
            onClick={function() { nav.goThread(post.id); }}
          >
            <div style={{ fontWeight: 700, fontSize: 15, color: '#13294B', marginBottom: 6, lineHeight: 1.4 }}>{post.title}</div>
            <div style={{ fontSize: 13, color: '#444', lineHeight: 1.6, marginBottom: 8, whiteSpace: 'pre-wrap', overflow: 'hidden', display: '-webkit-box', WebkitLineClamp: 3, WebkitBoxOrient: 'vertical' }}>{post.body}</div>
            {post.image_url && (
              <img src={post.image_url} alt="" style={{ maxWidth: '100%', borderRadius: 8, marginBottom: 8, display: 'block' }} />
            )}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, fontSize: 12, color: '#999' }}>
              <span>👤 {post.display_name}</span>
              <span>{formatDate(post.created_at)}</span>
              {post.reply_count > 0 && <span>💬 {post.reply_count}</span>}
              {post.like_count > 0 && <span>♥ {post.like_count}</span>}
            </div>
          </div>
        );
      })}

      {hasMore && (
        <button
          onClick={loadMore}
          disabled={loadingMore}
          style={{ width: '100%', padding: '12px 0', background: '#f5f2eb', border: '1px solid #ddd', borderRadius: 8, fontWeight: 600, fontSize: 14, cursor: 'pointer', opacity: loadingMore ? 0.7 : 1 }}
        >{loadingMore ? '読み込み中...' : 'もっと見る'}</button>
      )}
    </main>
  );
}

window.BoardPage = BoardPage;
