// comments.jsx — reusable discussion thread (project + task)

const { useState: useStateC, useRef: useRefC, useEffect: useEffectC } = React;
const getME_C = () => window.SEED.ME;

function CommentThread({ comments = [], onAdd, placeholder = 'Write a comment\u2026', empty = 'No comments yet \u2014 start the discussion.', autoScroll = false }) {
  const ME_C = getME_C();
  const [text, setText] = useStateC('');
  const listRef = useRefC(null);
  const send = () => {
    const v = text.trim();
    if (!v) return;
    onAdd(v);
    setText('');
  };
  useEffectC(() => {
    if (autoScroll && listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [comments.length]);

  return (
    <div className="cmt-thread">
      <div className="cmt-list" ref={listRef}>
        {comments.length === 0 && <p className="cmt-empty">{empty}</p>}
        {comments.map((c) => {
          const u = window.userById(c.author);
          const mine = c.author === ME_C;
          return (
            <div key={c.id} className={'cmt' + (mine ? ' mine' : '')}>
              <window.Avatar id={c.author} size={30} />
              <div className="cmt-main">
                <div className="cmt-head">
                  <span className="cmt-author">{u.name}{mine && <span className="cmt-you">You</span>}</span>
                  <span className="cmt-time">{c.time}</span>
                </div>
                <div className="cmt-bubble">{c.text}</div>
              </div>
            </div>
          );
        })}
      </div>
      <div className="cmt-composer">
        <window.Avatar id={ME_C} size={30} />
        <div className="cmt-input-wrap">
          <textarea value={text} placeholder={placeholder} rows={1}
            onChange={(e) => setText(e.target.value)}
            onInput={(e) => { e.target.style.height = 'auto'; e.target.style.height = Math.min(e.target.scrollHeight, 120) + 'px'; }}
            onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }} />
          <button className="cmt-send" onClick={send} disabled={!text.trim()} title="Comment (Enter)">
            <window.Icon name="send" size={16} />
          </button>
        </div>
      </div>
    </div>
  );
}

window.CommentThread = CommentThread;
