// screen-idea.jsx
const { useState: useIdeaState, useEffect: useIdeaEffect } = React;

function IdeaDetail({ idea, vote, onVote, goBack, openUser, currentUser }) {
  const Icon = window.Icon;
  const [bookmarked, setBookmarked] = useIdeaState(true);
  const [draft, setDraft] = useIdeaState('');
  // idea.comments from the home list is a count number, not an array — always start empty and load from API
  const [comments, setComments] = useIdeaState(Array.isArray(idea?.comments) ? idea.comments : []);
  const [expanded, setExpanded] = useIdeaState(null);
  const [posting, setPosting] = useIdeaState(false);
  const [replyTo, setReplyTo] = useIdeaState(null);      // comment id being replied to
  const [replyDraft, setReplyDraft] = useIdeaState('');
  const [replyPosting, setReplyPosting] = useIdeaState(false);
  const [replies, setReplies] = useIdeaState({});         // { [commentId]: [...] }
  const [loadingReplies, setLoadingReplies] = useIdeaState({});

  // Reload comments when idea changes
  useIdeaEffect(() => {
    if (!idea?.id) return;
    window.API.getIdea(idea.id)
      .then(d => setComments(d.comments || []))
      .catch(() => setComments(window.COMMENTS));
  }, [idea?.id]);

  const ideaUp = Number(idea?.up_votes ?? idea?.up ?? 0);
  const ideaDown = Number(idea?.down_votes ?? idea?.down ?? 0);
  const up = ideaUp + (vote === 'up' ? 1 : 0);
  const down = ideaDown + (vote === 'down' ? 1 : 0);

  const post = async () => {
    if (!draft.trim() || posting) return;
    setPosting(true);
    try {
      await window.API.addComment(idea.id, draft.trim());
      const d = await window.API.getIdea(idea.id);
      setComments(d.comments || []);
      setDraft('');
    } catch {
      // optimistic fallback
      const me = currentUser || {};
      setComments(cs => [{ id: Date.now(), author: me.name || 'You', avatar: me.avatar, ago: 'just now', up_votes: 0, down_votes: 0, replies: 0, body: draft.trim() }, ...cs]);
      setDraft('');
    } finally {
      setPosting(false);
    }
  };

  const toggleReplies = async (commentId, currentCount) => {
    if (expanded === commentId) { setExpanded(null); return; }
    setExpanded(commentId);
    if (replies[commentId]) return; // already loaded
    setLoadingReplies(l => ({ ...l, [commentId]: true }));
    try {
      const data = await window.API.getReplies(idea.id, commentId);
      setReplies(r => ({ ...r, [commentId]: data }));
    } catch {
      setReplies(r => ({ ...r, [commentId]: [] }));
    } finally {
      setLoadingReplies(l => ({ ...l, [commentId]: false }));
    }
  };

  const postReply = async (parentId) => {
    if (!replyDraft.trim() || replyPosting) return;
    setReplyPosting(true);
    try {
      await window.API.addComment(idea.id, replyDraft.trim(), parentId);
      // Reload replies for this comment
      const data = await window.API.getReplies(idea.id, parentId);
      setReplies(r => ({ ...r, [parentId]: data }));
      // Update reply count on parent comment
      setComments(cs => cs.map(c => c.id === parentId ? { ...c, replies: (Number(c.replies) || 0) + 1 } : c));
      setReplyDraft('');
      setReplyTo(null);
    } catch {
      // optimistic fallback
      const me = currentUser || {};
      const newReply = { id: Date.now(), author: me.name || 'You', avatar: me.avatar, ago: 'just now', up_votes: 0, down_votes: 0, body: replyDraft.trim() };
      setReplies(r => ({ ...r, [parentId]: [...(r[parentId] || []), newReply] }));
      setComments(cs => cs.map(c => c.id === parentId ? { ...c, replies: (Number(c.replies) || 0) + 1 } : c));
      setReplyDraft('');
      setReplyTo(null);
    } finally {
      setReplyPosting(false);
    }
  };

  const [cVotes, setCVotes] = useIdeaState({});
  const voteComment = async (id, dir) => {
    const prev = cVotes[id];
    setCVotes(v => ({ ...v, [id]: v[id] === dir ? undefined : dir }));
    try {
      const res = await window.API.voteComment(idea.id, id, dir);
      setCVotes(v => ({ ...v, [id]: res.vote || undefined }));
    } catch {
      setCVotes(v => ({ ...v, [id]: prev }));
    }
  };

  return (
    <div className="page fade-in" style={{ maxWidth: 1320 }}>
      <button className="btn btn-ghost btn-sm" onClick={goBack} style={{ marginBottom: 18 }}><Icon name="chevLeft" size={16} />Back to ideas</button>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 360px', gap: 24, alignItems: 'start' }}>
        {/* main */}
        <div>
          <div className="muted" style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.04em', marginBottom: 10 }}>IDEA #{idea.id.toString().padStart(3, '0')}</div>
          <div className="card" style={{ padding: 28 }}>
            <div className="spread" style={{ alignItems: 'flex-start' }}>
              <div>
                <h1 style={{ margin: 0, fontSize: 27, fontWeight: 800, color: 'var(--coral-500)', letterSpacing: '-.02em' }}>{idea.title}</h1>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 9 }}>
                  <window.CatChip name={idea.category} />
                  <window.StatusBadge status={idea.status} />
                  <span className="muted" style={{ fontSize: 13 }}>· {idea.date}</span>
                </div>
              </div>
              <div style={{ display: 'flex', gap: 8 }}>
                <button className="icon-btn" onClick={() => setBookmarked(b => !b)} style={{ color: bookmarked ? 'var(--coral-500)' : 'var(--ink-400)', background: bookmarked ? 'var(--coral-50)' : 'transparent' }}><Icon name="bookmark" size={20} /></button>
                <button className="icon-btn"><Icon name="share" size={20} /></button>
              </div>
            </div>

            <p style={{ color: 'var(--ink-600)', fontSize: 15, lineHeight: 1.7, marginTop: 18 }}>
              {idea.desc} The proposal outlines a phased rollout, success metrics tied to engagement and turnaround time, and a clear owner for each milestone so progress stays visible to leadership.
            </p>

            <div style={{ display: 'flex', gap: 8, marginTop: 4, marginBottom: 20 }}>
              {[idea.category, 'Business', 'Idea'].map(t => (
                <span key={t} style={{ fontSize: 12.5, fontWeight: 700, color: 'var(--coral-600)', background: 'var(--coral-50)', padding: '6px 12px', borderRadius: 99 }}>{t}</span>
              ))}
            </div>

            <div style={{ height: 320, borderRadius: 'var(--r)', background: `url(${window.HERO}) center/cover`, border: '1px solid var(--line)' }} />

            {/* vote bar */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '18px 0 4px', marginTop: 8, borderTop: '1px solid var(--line)', marginTop: 18 }}>
              <button className="btn btn-sm" onClick={() => onVote(idea.id, 'up')} style={{ background: vote === 'up' ? 'var(--accent-600)' : 'var(--ink-50)', color: vote === 'up' ? '#fff' : 'var(--ink-700)' }}><Icon name="thumbUp" size={17} />Upvote · {window.fmt(up)}</button>
              <button className="btn btn-sm" onClick={() => onVote(idea.id, 'down')} style={{ background: vote === 'down' ? 'var(--danger)' : 'var(--ink-50)', color: vote === 'down' ? '#fff' : 'var(--ink-700)' }}><Icon name="thumbDown" size={17} />Downvote · {window.fmt(down)}</button>
              <span className="schip comment" style={{ marginLeft: 'auto' }}><Icon name="comment" size={16} />{comments.length} comments</span>
              <span className="schip"><Icon name="eye" size={16} />{window.fmt(idea.views)} views</span>
            </div>
          </div>

          {/* comment composer */}
          <div className="card" style={{ padding: 18, marginTop: 18 }}>
            <div style={{ display: 'flex', gap: 12 }}>
              <window.Avatar src={window.AV.heba} size={40} />
              <div style={{ flex: 1 }}>
                <textarea value={draft} onChange={e => setDraft(e.target.value)} placeholder="Share your thoughts on this idea…" rows={2}
                  style={{ width: '100%', resize: 'none', border: '1.5px solid var(--line)', borderRadius: 'var(--r-sm)', padding: '11px 13px', fontSize: 14, color: 'var(--ink-700)', outline: 'none' }} />
                <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 9, marginTop: 9 }}>
                  <button className="btn btn-ghost btn-sm" onClick={() => setDraft('')}>Cancel</button>
                  <button className="btn btn-primary btn-sm" onClick={post} disabled={posting}>{posting ? '…' : 'Comment'}</button>
                </div>
              </div>
            </div>
          </div>

          {/* comments */}
          <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 6 }}>
            {comments.map(c => {
              // normalise: API returns body/author/avatar/up_votes/down_votes; mock uses text/name/av/up/down
              const cName = c.author || c.name || 'Unknown';
              const cAv = c.avatar || c.av;
              const cText = c.body || c.text || '';
              const cUp = Number(c.up_votes ?? c.up ?? 0);
              const cDown = Number(c.down_votes ?? c.down ?? 0);
              const cReplies = Number(c.replies ?? 0);
              const cAgo = c.ago || (c.created_at ? new Date(c.created_at).toLocaleDateString() : '');
              return (
              <div key={c.id} style={{ padding: '18px 4px', borderBottom: '1px solid var(--line)' }}>
                <div style={{ display: 'flex', gap: 12 }}>
                  <window.Avatar src={cAv} size={40} />
                  <div style={{ flex: 1 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                      <b style={{ fontSize: 14.5, color: 'var(--ink-900)' }}>{cName}</b>
                      <span className="muted" style={{ fontSize: 12.5 }}>{cAgo}</span>
                    </div>
                    <p style={{ margin: '7px 0 0', color: 'var(--ink-600)', fontSize: 14, lineHeight: 1.6 }}>{cText}</p>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginTop: 11 }}>
                      <button className={`schip up ${cVotes[c.id] === 'up' ? 'on' : ''}`} onClick={() => voteComment(c.id, 'up')}><Icon name="thumbUp" size={15} />{cUp + (cVotes[c.id] === 'up' ? 1 : 0)}</button>
                      <button className={`schip down ${cVotes[c.id] === 'down' ? 'on' : ''}`} onClick={() => voteComment(c.id, 'down')}><Icon name="thumbDown" size={15} />{cDown + (cVotes[c.id] === 'down' ? 1 : 0)}</button>
                      <button onClick={() => { setReplyTo(replyTo === c.id ? null : c.id); setReplyDraft(''); }} style={{ fontSize: 13, fontWeight: 700, color: replyTo === c.id ? 'var(--coral-500)' : 'var(--ink-500)' }}>
                        {replyTo === c.id ? 'Cancel' : 'Reply'}
                      </button>
                      {cReplies > 0 && (
                        <button onClick={() => toggleReplies(c.id, cReplies)} style={{ fontSize: 13, fontWeight: 700, color: 'var(--coral-500)', display: 'flex', alignItems: 'center', gap: 4 }}>
                          {loadingReplies[c.id] ? 'Loading…' : expanded === c.id ? 'Hide replies' : `View ${cReplies} ${cReplies === 1 ? 'reply' : 'replies'}`}
                          <Icon name="chevDown" size={14} style={{ transform: expanded === c.id ? 'rotate(180deg)' : 'none', transition: 'transform .15s' }} />
                        </button>
                      )}
                    </div>

                    {/* Inline reply composer */}
                    {replyTo === c.id && (
                      <div style={{ marginTop: 12, paddingLeft: 16, borderLeft: '2px solid var(--coral-200)', display: 'flex', gap: 10 }}>
                        <window.Avatar src={currentUser?.avatar} size={32} />
                        <div style={{ flex: 1 }}>
                          <textarea
                            value={replyDraft}
                            onChange={e => setReplyDraft(e.target.value)}
                            placeholder={`Reply to ${cName}…`}
                            rows={2}
                            autoFocus
                            style={{ width: '100%', resize: 'none', border: '1.5px solid var(--line)', borderRadius: 'var(--r-sm)', padding: '9px 12px', fontSize: 13.5, color: 'var(--ink-700)', outline: 'none' }}
                          />
                          <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 8 }}>
                            <button className="btn btn-ghost btn-sm" onClick={() => { setReplyTo(null); setReplyDraft(''); }}>Cancel</button>
                            <button className="btn btn-primary btn-sm" onClick={() => postReply(c.id)} disabled={replyPosting || !replyDraft.trim()}>
                              {replyPosting ? '…' : 'Post reply'}
                            </button>
                          </div>
                        </div>
                      </div>
                    )}

                    {/* Expanded replies list */}
                    {expanded === c.id && (
                      <div style={{ marginTop: 12, paddingLeft: 16, borderLeft: '2px solid var(--line)', display: 'flex', flexDirection: 'column', gap: 12 }}>
                        {(replies[c.id] || []).length === 0 && !loadingReplies[c.id] && (
                          <span className="muted" style={{ fontSize: 13 }}>No replies yet.</span>
                        )}
                        {(replies[c.id] || []).map(r => (
                          <div key={r.id} style={{ display: 'flex', gap: 10 }}>
                            <window.Avatar src={r.avatar} size={32} />
                            <div>
                              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                                <b style={{ fontSize: 13.5, color: 'var(--ink-900)' }}>{r.author || r.name}</b>
                                <span className="muted" style={{ fontSize: 12 }}>{r.ago || (r.created_at ? new Date(r.created_at).toLocaleDateString() : '')}</span>
                              </div>
                              <p style={{ margin: '4px 0 0', fontSize: 13.5, color: 'var(--ink-600)', lineHeight: 1.55 }}>{r.body || r.text}</p>
                            </div>
                          </div>
                        ))}
                      </div>
                    )}
                  </div>
                </div>
              </div>
              );
            })}
          </div>
        </div>

        {/* right rail */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 18, position: 'sticky', top: 0 }}>
          <div className="muted" style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.04em' }}>THE OWNER</div>
          <div className="card" style={{ padding: 24, textAlign: 'center', marginTop: -8 }}>
            <window.Avatar src={idea.avatar} size={92} />
            <div style={{ fontSize: 18, fontWeight: 800, color: 'var(--ink-900)', marginTop: 14 }}>{idea.author}</div>
            <div className="muted" style={{ fontSize: 13.5, fontWeight: 600 }}>{idea.role}</div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginTop: 18 }}>
              <div style={{ background: 'var(--ink-50)', borderRadius: 'var(--r-sm)', padding: '12px 8px' }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--ink-900)' }} className="tnum">20</div>
                <div className="muted" style={{ fontSize: 12, fontWeight: 600 }}>Published</div>
              </div>
              <div style={{ background: 'var(--ink-50)', borderRadius: 'var(--r-sm)', padding: '12px 8px' }}>
                <div style={{ fontSize: 20, fontWeight: 800, color: 'var(--ink-900)' }} className="tnum">1.2k</div>
                <div className="muted" style={{ fontSize: 12, fontWeight: 600 }}>Views</div>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'center', gap: 10, marginTop: 18 }}>
              {['#e8930c', '#0a66ff', '#e23b56'].map(c => (
                <div key={c} style={{ color: c }}><Icon name="award" size={34} /></div>
              ))}
            </div>
            <button className="btn btn-outline btn-sm" style={{ width: '100%', marginTop: 18 }} onClick={() => openUser && openUser({ name: idea.author, role: idea.role, av: idea.avatar })}>View profile</button>
          </div>

          <div className="muted" style={{ fontSize: 13, fontWeight: 700, letterSpacing: '.04em', marginTop: 4 }}>SIMILAR IDEAS</div>
          {window.SIMILAR.map((s, idx) => (
            <div key={idx} className="card" style={{ padding: 16, cursor: 'pointer', marginTop: idx === 0 ? -8 : 0 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <window.Avatar src={s.av} size={32} />
                <b style={{ fontSize: 13.5, color: 'var(--ink-900)', whiteSpace: 'nowrap' }}>{s.name}</b>
                <span className="muted" style={{ fontSize: 12, marginLeft: 'auto', whiteSpace: 'nowrap', flex: 'none' }}>{s.ago}</span>
              </div>
              <p style={{ margin: '10px 0 12px', fontSize: 13, color: 'var(--ink-600)', lineHeight: 1.55 }}>{s.text}</p>
              <div style={{ display: 'flex', gap: 6 }}>
                {s.tags.map(t => <span key={t} style={{ fontSize: 11.5, fontWeight: 700, color: 'var(--coral-600)', background: 'var(--coral-50)', padding: '4px 10px', borderRadius: 99 }}>{t}</span>)}
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
window.IdeaDetail = IdeaDetail;
