/* ============================================================
   VLF 2026 · OPS COMMENTS — phối hợp theo từng nhiệm vụ
   Comment + trả lời + @nhắc tên (người/đội). Feed gộp toàn bộ
   comment kèm bộ lọc "Nhắc tôi · Đội tôi · Tất cả".
   Xuất: TaskComments, CommentsFeed
   ============================================================ */

function meName(store) { return window.VLF.staffRoleById(store.meRole).me; }

/* hàng chip @nhắc tên */
function MentionChips({ to, lang }) {
  if (!to || !to.length) return null;
  return (
    <span className="ops-mentions">
      {to.map((n, i) => <span className="ops-mention" key={i}>@{n}</span>)}
    </span>);
}

/* 1 comment (hoặc reply) */
function CommentNode({ c, lang, me, onReply }) {
  const mine = c.by === me;
  return (
    <div className={'ops-cmt' + (c.isReplyNode ? ' reply' : '') + (mine ? ' mine' : '')}>
      <OpsAva name={c.by} size={c.isReplyNode ? 24 : 30} />
      <div className="ops-cmt-b">
        <div className="ops-cmt-head">
          <b>{c.by}</b>
          {c.team && <TeamChip id={c.team} lang={lang} small />}
          <span className="at">{c.at}</span>
        </div>
        <MentionChips to={c.to} lang={lang} />
        <div className="ops-cmt-tx">{trL(lang, c.msg)}</div>
        {onReply && <button className="ops-cmt-reply" onClick={() => onReply(c)}>{trL(lang, { vi: 'Trả lời', en: 'Reply' })}</button>}
      </div>
    </div>);
}

/* khối comment cho TaskDetail */
function TaskComments({ taskId, store, team }) {
  const lang = useLang();
  const O = window.VLF.ops;
  const me = meName(store);
  const seed = (O.taskComments[taskId] || []).map((c) => ({ ...c, replies: [...(c.replies || [])] }));
  const [list, setList] = useState(seed);
  const [text, setText] = useState('');
  const [to, setTo] = useState([]);
  const [replyTo, setReplyTo] = useState(null);

  const base = O.tasks.find((t) => t.id === taskId);
  // ứng viên @nhắc tên: người làm + đội trưởng chủ trì + đội trưởng các đội phối hợp
  const cands = Array.from(new Set([
    ...(base.assignees || []),
    O.teamById(base.team).lead,
    ...(base.collab || []).map((cid) => O.teamById(cid).lead),
  ])).filter((n) => n && n !== me);

  const count = list.reduce((a, c) => a + 1 + (c.replies ? c.replies.length : 0), 0);

  function toggleMention(n) { setTo((s) => (s.includes(n) ? s.filter((x) => x !== n) : [...s, n])); }
  function send() {
    if (!text.trim() && to.length === 0) return;
    const node = { id: 'u' + Date.now(), by: me, team: team.id, at: window.OPS_NOW, to: [...to], msg: text.trim() || (lang === 'en' ? '(mention)' : '(nhắc tên)'), mine: true };
    if (replyTo) {
      setList((s) => s.map((c) => (c.id === replyTo.id ? { ...c, replies: [...(c.replies || []), node] } : c)));
    } else {
      setList((s) => [...s, { ...node, replies: [] }]);
    }
    setText(''); setTo([]); setReplyTo(null);
  }

  return (
    <>
      <SectionHead title={trL(lang, { vi: 'Trao đổi theo nhiệm vụ', en: 'Task discussion' })} right={<span className="v-muted" style={{ fontSize: 12 }}>{count} {trL(lang, { vi: 'bình luận', en: 'comments' })}</span>} />
      <div className="v-card ops-cmts">
        {list.length === 0 && <div className="v-muted" style={{ fontSize: 12.5, padding: '6px 2px' }}>{trL(lang, { vi: 'Chưa có trao đổi. Bình luận & @nhắc tên người liên quan để phối hợp.', en: 'No comments. Post & @mention people to coordinate.' })}</div>}
        {list.map((c) => (
          <div className="ops-cmt-thread" key={c.id}>
            <CommentNode c={c} lang={lang} me={me} onReply={setReplyTo} />
            {(c.replies || []).map((r) => <CommentNode key={r.id} c={{ ...r, isReplyNode: true }} lang={lang} me={me} onReply={() => setReplyTo(c)} />)}
          </div>
        ))}
      </div>

      {/* compose */}
      <div className="ops-cmt-compose">
        {replyTo && <div className="ops-cmt-replybar">{trL(lang, { vi: 'Đang trả lời', en: 'Replying to' })} <b>@{replyTo.by}</b><button onClick={() => setReplyTo(null)}>✕</button></div>}
        <div className="ops-cmt-mrow">
          <span className="lbl">{trL(lang, { vi: 'Nhắc:', en: 'Mention:' })}</span>
          {cands.map((n) => <button key={n} className={'ops-mchip' + (to.includes(n) ? ' on' : '')} onClick={() => toggleMention(n)}>@{n}</button>)}
        </div>
        <div className="ops-cmt-inrow">
          <input className="ops-input" value={text} onChange={(e) => setText(e.target.value)} placeholder={trL(lang, { vi: 'Viết bình luận phối hợp…', en: 'Write a coordination comment…' })} onKeyDown={(e) => { if (e.key === 'Enter') send(); }} />
          <button className="ops-cmt-send" onClick={send}><Icon name="arrowR" size={18} sw={2.2} /></button>
        </div>
      </div>
    </>);
}

/* ---------- FEED TRAO ĐỔI & NHẮC TÊN (L2) ---------- */
function CommentsFeed({ nav, store, team, isBtc }) {
  const lang = useLang();
  const O = window.VLF.ops;
  const me = meName(store);
  const teamMembers = team ? team.members : [];
  const all = O.allComments();
  const [tab, setTab] = useState('me');

  const mentionsMe = (c) => (c.to || []).includes(me);
  const fromOrToTeam = (c) => c.by === me || teamMembers.includes(c.by) || (c.to || []).some((n) => teamMembers.includes(n)) || c.taskTeam === team.id;

  let list = all;
  if (tab === 'me') list = all.filter(mentionsMe);
  else if (tab === 'team') list = all.filter(fromOrToTeam);

  const tabs = [
    ['me', { vi: 'Nhắc tôi', en: 'Mentions me' }, all.filter(mentionsMe).length],
    ['team', { vi: 'Đội tôi', en: 'My team' }, all.filter(fromOrToTeam).length],
    ['all', { vi: 'Tất cả', en: 'All' }, all.length],
  ];

  return (
    <>
      <div className="ops-scopebar">
        {tabs.map(([id, lbl, n]) => <button key={id} className={'ops-scope' + (tab === id ? ' on' : '')} onClick={() => setTab(id)}>{trL(lang, lbl)} <b>{n}</b></button>)}
      </div>

      <div className="v-card" style={{ marginTop: 4 }}>
        {list.map((c, i) => {
          const t = O.tasks.find((x) => x.id === c.taskId);
          return (
            <div className="v-row ops-feed-row" key={c.id + i} onClick={() => nav('task', { id: c.taskId, tab: 'cmt' })}>
              <OpsAva name={c.by} size={32} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="ops-feed-top">
                  <b>{c.by}</b>
                  {c.isReply && <span className="ops-feed-reply">↳ {trL(lang, { vi: 'trả lời', en: 'reply' })} {c.parent}</span>}
                  <span className="ops-feed-at">{c.at}</span>
                </div>
                <MentionChips to={c.to} lang={lang} />
                <div className="ops-feed-tx">{trL(lang, c.msg)}</div>
                <div className="ops-feed-task"><PrioChip p={t ? t.prio : 'P2'} /><span>{trL(lang, c.taskTitle)}</span></div>
              </div>
              <Icon name="chev" size={18} className="chev" />
            </div>);
        })}
        {list.length === 0 && <div className="v-row" style={{ cursor: 'default' }}><div className="v-muted" style={{ fontSize: 13 }}>{tab === 'me' ? trL(lang, { vi: 'Chưa ai nhắc tên bạn.', en: 'No mentions yet.' }) : trL(lang, { vi: 'Chưa có trao đổi.', en: 'No comments yet.' })}</div></div>}
      </div>
      <p className="v-muted" style={{ fontSize: 11.5, lineHeight: 1.5, padding: '10px 2px 0' }}>{trL(lang, { vi: 'Mỗi bình luận gắn với một nhiệm vụ. Chạm để mở đúng nhiệm vụ và trả lời ngay tại đó.', en: 'Each comment is tied to a task. Tap to open the task and reply in context.' })}</p>
    </>);
}

Object.assign(window, { TaskComments, CommentsFeed, MentionChips });
