/* ============================================================
   comments.jsx — right panel with comments + suggestions
   ============================================================ */

function CommentsPanel() {
  const { doc, rightTab, setRightTab, activeCommentId, setActiveCommentId,
          updateComment, removeComment, acceptSuggestion, rejectSuggestion, removeSuggestion,
          tweaks } = useApp();

  const role = ROLES[tweaks.role] || ROLES.instromer;

  // build unified feed
  let items = [];
  doc.comments.forEach(c => items.push({ kind: 'comment', id: c.id, ...c }));
  doc.suggestions.forEach(s => items.push({ kind: 'suggestion', id: s.id, ...s }));
  items.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));

  if (rightTab === 'comments') items = items.filter(x => x.kind === 'comment' && !x.resolved);
  else if (rightTab === 'suggestions') items = items.filter(x => x.kind === 'suggestion' && x.status === 'pending');
  else if (rightTab === 'resolved') items = items.filter(x => (x.kind === 'comment' && x.resolved) || (x.kind === 'suggestion' && x.status !== 'pending'));
  else items = items.filter(x => (x.kind === 'comment' && !x.resolved) || (x.kind === 'suggestion' && x.status === 'pending'));

  return (
    <aside className="right-panel">
      <div className="panel-head">
        <h3>Feedback</h3>
        <span style={{fontSize: 11, color: 'var(--ink-4)'}}>
          {doc.comments.filter(c=>!c.resolved).length} comments · {doc.suggestions.filter(s=>s.status==='pending').length} voorstellen
        </span>
      </div>

      <div className="tab-row">
        <button className={'tab-btn' + (rightTab==='all' ? ' active':'')} onClick={()=>setRightTab('all')}>Actief</button>
        <button className={'tab-btn' + (rightTab==='comments' ? ' active':'')} onClick={()=>setRightTab('comments')}>Comments</button>
        <button className={'tab-btn' + (rightTab==='suggestions' ? ' active':'')} onClick={()=>setRightTab('suggestions')}>Voorstellen</button>
        <button className={'tab-btn' + (rightTab==='resolved' ? ' active':'')} onClick={()=>setRightTab('resolved')}>Afgerond</button>
      </div>

      {items.length === 0 && (
        <div className="comment-empty">
          <div style={{marginBottom: 10, fontSize: 22, fontFamily:'var(--f-serif)', fontStyle:'italic', color:'var(--ink-3)'}}>
            Nog geen feedback
          </div>
          Selecteer tekst in het document<br/>om een <span className="kbd">comment</span> of <span className="kbd">voorstel</span> te plaatsen.
        </div>
      )}

      <div className="comment-list">
        {items.map(it => (
          <CommentCard
            key={it.kind + '-' + it.id}
            item={it}
            isActive={activeCommentId === it.id}
            onActivate={() => setActiveCommentId(it.id)}
            onResolve={() => it.kind === 'comment' ? updateComment(it.id, { resolved: !it.resolved }) : null}
            onDelete={() => it.kind === 'comment' ? removeComment(it.id) : removeSuggestion(it.id)}
            onAccept={() => acceptSuggestion(it.id)}
            onReject={() => rejectSuggestion(it.id)}
            currentRole={role}
          />
        ))}
      </div>
    </aside>
  );
}

function CommentCard({ item, isActive, onActivate, onResolve, onDelete, onAccept, onReject, currentRole }) {
  const { doc } = useApp();
  const block = doc.blocks.find(b => b.id === item.blockId);
  let snippet = '';
  if (block) {
    const field = item.range?.field || 'text';
    const source = field.startsWith('item-')
      ? (block.items?.[Number(field.slice(5))] || '')
      : (block[field] || '');
    snippet = source.slice(item.range.start, item.range.end);
  }

  const resolved = item.kind === 'comment' ? item.resolved : (item.status !== 'pending');
  const initials = (item.author || '?').split(' ').map(s=>s[0]).slice(0,2).join('').toUpperCase();

  return (
    <div className={'comment-card ' + item.kind + (isActive ? ' active':'') + (resolved ? ' resolved':'')} onClick={onActivate}>
      <div className="comment-head">
        <div className="avatar" style={{background: item.color || 'var(--accent)'}}>{initials}</div>
        <div>
          <div className="comment-author">{item.author}</div>
          <div style={{fontSize: 10.5, color: 'var(--ink-4)'}}>
            {item.kind === 'comment' ? 'Opmerking' : 'Tekstvoorstel'}
            {item.kind === 'suggestion' && item.status !== 'pending' && ` · ${item.status === 'accepted' ? 'geaccepteerd':'afgewezen'}`}
          </div>
        </div>
        <span className="comment-time">{timeAgo(item.createdAt)}</span>
      </div>

      {item.kind === 'comment' && (
        <>
          {snippet && <div className="comment-snippet">"{snippet}"</div>}
          <p className="comment-body">{item.text}</p>
          <div className="comment-actions">
            {!item.resolved && <button className="btn-mini primary" onClick={(e)=>{e.stopPropagation(); onResolve();}}><I.check/> Oplossen</button>}
            {item.resolved  && <button className="btn-mini" onClick={(e)=>{e.stopPropagation(); onResolve();}}>Heropenen</button>}
            <button className="btn-mini" onClick={(e)=>{e.stopPropagation(); onDelete();}}>Verwijderen</button>
          </div>
        </>
      )}

      {item.kind === 'suggestion' && (
        <>
          <div className="suggestion-pair">
            <span className="del">{item.original}</span>{' → '}<span className="ins">{item.proposed}</span>
          </div>
          {item.status === 'pending' ? (
            <div className="comment-actions">
              <button className="btn-mini accept" onClick={(e)=>{e.stopPropagation(); onAccept();}}><I.check/> Accepteren</button>
              <button className="btn-mini reject" onClick={(e)=>{e.stopPropagation(); onReject();}}><I.x/> Afwijzen</button>
            </div>
          ) : (
            <div className="comment-actions">
              <button className="btn-mini" onClick={(e)=>{e.stopPropagation(); onDelete();}}>Verwijderen</button>
            </div>
          )}
        </>
      )}
    </div>
  );
}

function timeAgo(ts) {
  if (!ts) return '';
  const d = (Date.now() - ts) / 1000;
  if (d < 60) return 'nu';
  if (d < 3600) return Math.floor(d/60) + 'm';
  if (d < 86400) return Math.floor(d/3600) + 'u';
  return Math.floor(d/86400) + 'd';
}

Object.assign(window, { CommentsPanel });
