/* ===================================================================
   KabelFlux v5 — Review tab panel (views-review.jsx)
   Exposes window.ReviewTab — rendered inside LayoutView's right panel.
   =================================================================== */

const StatusBadge = ({ status }) => {
  const map = {
    draft:     { label:'Draft',     color:'var(--info)',    bg:'rgba(74,158,255,.12)' },
    in_review: { label:'In Review', color:'var(--warning)', bg:'rgba(245,166,35,.12)' },
    approved:  { label:'Approved',  color:'var(--success)', bg:'rgba(76,175,80,.12)'  },
  };
  const s = map[status] || map.draft;
  return (
    <span style={{ padding:'2px 8px', background:s.bg, color:s.color, borderRadius:'var(--r-pill)', fontSize:10, fontWeight:700, letterSpacing:'.5px' }}>
      {s.label}
    </span>
  );
};

const CommentCard = ({ cmt, idx, canResolve, onResolve, onDelete, replyTo, replyText, setReplyTo, setReplyText, onReply, currentUser, isOwner }) => {
  const pinColor = cmt.resolved ? 'var(--success)' : ['#ef4e4e','#f5a623','#4a9eff','#9c6cd1','#4caf50'][idx % 5];
  return (
    <div style={{ marginBottom:6, opacity: cmt.resolved ? 0.5 : 1 }}>
      <div style={{ padding:8, background:'var(--bg-2)', borderRadius:'var(--r-2)', borderLeft:`2px solid ${cmt.resolved ? 'var(--success)' : pinColor}` }}>
        <div style={{ display:'flex', alignItems:'center', gap:5, marginBottom:4 }}>
          {cmt.x != null && (
            <div style={{ width:16, height:16, borderRadius:'50%', background:pinColor, color:'#fff', fontSize:8, fontWeight:800, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
              {cmt.resolved ? '✓' : idx + 1}
            </div>
          )}
          <span style={{ fontSize:9, color:'var(--t-3)', flex:1 }}>{cmt.author} · {new Date(cmt.created_at).toLocaleDateString()}</span>
          {(isOwner || cmt.user_id === currentUser?.id) && !cmt.resolved && (
            <button onClick={onDelete} style={{ fontSize:9, color:'var(--t-4)', background:'none', border:'none', cursor:'pointer', padding:'0 2px' }}>✕</button>
          )}
        </div>
        <p style={{ fontSize:11, color:'var(--t-1)', margin:'0 0 5px', lineHeight:1.4 }}>{cmt.text}</p>
        {/* Replies */}
        {(cmt.replies || []).map(r => (
          <div key={r.id} style={{ marginLeft:12, marginTop:4, paddingLeft:8, borderLeft:'1px solid var(--line)', fontSize:10, color:'var(--t-2)' }}>
            <span style={{ fontWeight:600, marginRight:4 }}>{r.author}:</span>{r.text}
          </div>
        ))}
        {/* Actions */}
        {!cmt.resolved && (
          <div style={{ display:'flex', gap:4, marginTop:5 }}>
            <button onClick={() => setReplyTo(replyTo === cmt.id ? null : cmt.id)} style={{ fontSize:9, color:'var(--t-3)', background:'none', border:'none', cursor:'pointer', padding:'1px 4px' }}>Reply</button>
            {canResolve && (
              <button onClick={onResolve} style={{ fontSize:9, color:'var(--success)', background:'none', border:'none', cursor:'pointer', padding:'1px 4px' }}>Resolve</button>
            )}
          </div>
        )}
        {/* Reply input */}
        {replyTo === cmt.id && (
          <div style={{ marginTop:6, display:'flex', gap:4 }}>
            <input className="kf-input" value={replyText} onChange={e => setReplyText(e.target.value)}
                   placeholder="Reply…" style={{ flex:1, fontSize:11 }}
                   onKeyDown={e => e.key === 'Enter' && onReply(cmt.id)}/>
            <Btn size="sm" kind="primary" onClick={() => onReply(cmt.id)}>Post</Btn>
          </div>
        )}
      </div>
    </div>
  );
};

const ReviewTab = ({ project, currentUser, reviewData, loadReview }) => {
  const toast = useToast();
  const [replyTo, setReplyTo] = useState(null);
  const [replyText, setReplyText] = useState('');
  const [commentText, setCommentText] = useState('');
  const [addingComment, setAddingComment] = useState(false);

  const myApproval = reviewData?.approvals?.find(a => a.user_id === currentUser?.id);
  const isOwner = project?.owner_id === currentUser?.id || project?.ownerId === currentUser?.id;
  const canVote = myApproval !== undefined;
  const canComment = isOwner || canVote;
  const status = reviewData?.status || 'draft';

  const handleSubmit = async () => {
    try {
      await kfxFetch('/projects/' + project.realId + '/review/submit', { method: 'POST', body: {} });
      toast.ok('Submitted for review');
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  const handleClose = async () => {
    if (!window.confirm('Close review and revert to Draft?')) return;
    try {
      await kfxFetch('/projects/' + project.realId + '/review/close', { method: 'POST', body: {} });
      toast.warn('Review closed — back to Draft');
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  const handleVote = async (verdict) => {
    try {
      await kfxFetch('/projects/' + project.realId + '/review/vote', { method: 'POST', body: { verdict } });
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  const handleAddComment = async () => {
    if (!commentText.trim()) return;
    try {
      await kfxFetch('/projects/' + project.realId + '/review/comments', { method: 'POST', body: { text: commentText } });
      setCommentText(''); setAddingComment(false);
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  const handleResolve = async (cmt) => {
    try {
      await kfxFetch('/review/comments/' + cmt.id, { method: 'PUT', body: { resolved: !cmt.resolved } });
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  const handleDeleteComment = async (cid) => {
    if (!window.confirm('Delete this comment?')) return;
    try {
      await kfxFetch('/review/comments/' + cid, { method: 'DELETE' });
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  const handleReply = async (parentId) => {
    if (!replyText.trim()) return;
    try {
      await kfxFetch('/review/comments/' + parentId + '/replies', { method: 'POST', body: { text: replyText } });
      setReplyText(''); setReplyTo(null);
      await loadReview();
    } catch(e) { toast.err('Failed: ' + (e?.message || e)); }
  };

  return (
    <div style={{ display:'flex', flexDirection:'column', height:'100%', overflow:'hidden' }}>
      {/* Status banner */}
      <div style={{ padding:'8px 12px', background:'#0d0d0d', borderBottom:'1px solid var(--line)', flexShrink:0 }}>
        <div style={{ display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:9, color:'var(--t-3)', textTransform:'uppercase', letterSpacing:'.8px' }}>Status</span>
          <StatusBadge status={status}/>
          {/* spacer */}
          <div style={{ flex:1 }}/>
          {/* Owner: submit or close */}
          {isOwner && status === 'draft' && (
            <Btn size="sm" kind="primary" onClick={handleSubmit}>Submit for review</Btn>
          )}
          {isOwner && status === 'in_review' && (
            <Btn size="sm" kind="ghost" onClick={handleClose}>Close review</Btn>
          )}
        </div>
      </div>

      {/* Scrollable body */}
      <div style={{ flex:1, overflowY:'auto', display:'flex', flexDirection:'column' }}>

        {/* Draft state for non-owners */}
        {status === 'draft' && !isOwner && (
          <div style={{ padding:16, textAlign:'center', color:'var(--t-3)', fontSize:12 }}>
            Waiting for the project owner to submit for review.
          </div>
        )}

        {/* Sign-off section (shown when in_review or approved) */}
        {(status === 'in_review' || status === 'approved') && reviewData?.approvals?.length > 0 && (
          <div style={{ padding:'10px 12px', borderBottom:'1px solid var(--line)', background:'var(--bg-2)' }}>
            <div style={{ fontSize:9, color:'var(--t-3)', textTransform:'uppercase', letterSpacing:'.8px', marginBottom:8 }}>Sign-off</div>
            {reviewData.approvals.map(a => (
              <div key={a.user_id} style={{ display:'flex', alignItems:'center', gap:6, marginBottom:4 }}>
                <div style={{ width:7, height:7, borderRadius:'50%', background: a.verdict === 'approved' ? 'var(--success)' : a.verdict === 'changes_requested' ? 'var(--danger)' : 'var(--t-4)', flexShrink:0 }}/>
                <span style={{ fontSize:11, color:'var(--t-1)', flex:1 }}>{a.name}</span>
                <span style={{ fontSize:9, fontWeight:700, color: a.verdict === 'approved' ? 'var(--success)' : a.verdict === 'changes_requested' ? 'var(--danger)' : 'var(--t-4)' }}>
                  {a.verdict === 'approved' ? 'Approved' : a.verdict === 'changes_requested' ? 'Changes requested' : 'Pending'}
                </span>
              </div>
            ))}
            {/* My vote buttons */}
            {canVote && status === 'in_review' && (
              <div style={{ display:'flex', gap:5, marginTop:8 }}>
                <Btn size="sm" kind={myApproval?.verdict === 'approved' ? 'primary' : 'outline'} onClick={() => handleVote('approved')} style={{ flex:1 }}>✓ Approve</Btn>
                <Btn size="sm" kind={myApproval?.verdict === 'changes_requested' ? 'danger' : 'ghost'} onClick={() => handleVote('changes_requested')} style={{ flex:1 }}>✗ Request changes</Btn>
              </div>
            )}
          </div>
        )}

        {/* Approved banner */}
        {status === 'approved' && (
          <div style={{ margin:'10px 12px', padding:'8px 12px', background:'rgba(76,175,80,.1)', border:'1px solid rgba(76,175,80,.25)', borderRadius:'var(--r-2)', fontSize:12, color:'var(--success)', fontWeight:600 }}>
            ✓ All reviewers approved
          </div>
        )}

        {/* Comment thread */}
        {(status === 'in_review' || status === 'approved') && (
          <div style={{ padding:'10px 12px', flex:1 }}>
            <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom:8 }}>
              <div style={{ fontSize:9, color:'var(--t-3)', textTransform:'uppercase', letterSpacing:'.8px' }}>
                Comments · {(reviewData?.comments || []).filter(c => !c.resolved).length} open
              </div>
              {canComment && status === 'in_review' && (
                <Btn size="sm" kind="ghost" onClick={() => setAddingComment(true)}>+ General</Btn>
              )}
            </div>

            {/* Add general comment form */}
            {addingComment && (
              <div style={{ marginBottom:8, padding:8, background:'var(--bg-3)', borderRadius:'var(--r-2)', border:'1px solid var(--line)' }}>
                <textarea className="kf-input" rows="2" placeholder="Add a comment…"
                          value={commentText} onChange={e => setCommentText(e.target.value)}
                          style={{ width:'100%', marginBottom:6, resize:'vertical' }}/>
                <div style={{ display:'flex', gap:5 }}>
                  <Btn size="sm" kind="primary" onClick={handleAddComment}>Post</Btn>
                  <Btn size="sm" kind="ghost" onClick={() => { setAddingComment(false); setCommentText(''); }}>Cancel</Btn>
                </div>
              </div>
            )}

            {/* Comment list */}
            {(reviewData?.comments || []).length === 0 && (
              <div style={{ fontSize:11, color:'var(--t-4)', textAlign:'center', padding:'16px 0' }}>No comments yet</div>
            )}
            {(reviewData?.comments || []).map((cmt, idx) => (
              <CommentCard key={cmt.id} cmt={cmt} idx={idx}
                           canResolve={canComment || isOwner}
                           onResolve={() => handleResolve(cmt)}
                           onDelete={() => handleDeleteComment(cmt.id)}
                           replyTo={replyTo} replyText={replyText}
                           setReplyTo={setReplyTo} setReplyText={setReplyText}
                           onReply={handleReply}
                           currentUser={currentUser}
                           isOwner={isOwner}/>
            ))}
          </div>
        )}

      </div>
    </div>
  );
};

window.ReviewTab = ReviewTab;
