/* ============================================================
   COMMONS — Community (Reddit-like) view
   ============================================================ */

function PostRow({ post, i, onOpen }) {
  const comm = COMMUNITIES.find(c => c.name === post.sub);
  return (
    <article className="post" style={{ "--i": i }} onClick={() => onOpen(post.id)}>
      <VoteCluster initial={post.votes} type={post._type} id={post._id} liked={post.liked} />
      <div className="post-main">
        <div className="post-top">
          <span className="post-sub" style={{ "--c": comm?.color }}>
            <span className="sub-dot" /> {post.sub}
          </span>
          <span className="post-by">· {post.author} · {post.time}</span>
          <span className="tag post-tag">{post.tag}</span>
        </div>
        <h3 className="post-title">{post.title}</h3>
        <p className="post-body">{post.body}</p>
        {post.img && (
          <Cover seed={post.id} aspect="16 / 7" radius="10px" className="post-img" />
        )}
        <div className="post-foot">
          <span><Icon name="comment" size={16} />{post.comments} comments</span>
          <span><Icon name="share" size={16} />Share</span>
          <span><Icon name="bookmark" size={16} />Save</span>
        </div>
      </div>
    </article>
  );
}

function Community({ go, posts: allPosts }) {
  const [sort, setSort] = useState("Hot");
  const [active, setActive] = useState("all");
  const sorts = ["Hot", "New", "Top"];
  let posts = [...(allPosts || POSTS)];
  if (active !== "all") posts = posts.filter(p => p.sub === active);
  if (sort === "Top") posts = [...posts].sort((a, b) => b.votes - a.votes);
  if (sort === "New") posts = [...posts].sort((a, b) => (a.fresh ? -1 : 0) - (b.fresh ? -1 : 0) || parseInt(a.time) - parseInt(b.time));

  return (
    <div className="view community">
      <section className="comm-banner">
        <div className="shell comm-banner-inner">
          <div>
            <span className="kicker" style={{ "--i": 0 }}>iPanjab · Community</span>
            <h1 className="comm-title serif" style={{ "--i": 1 }}>What the diaspora is talking about.</h1>
          </div>
          <button className="btn btn-primary comm-new" style={{ "--i": 2 }} onClick={() => go("compose")}><Icon name="plus" size={16} /> New post</button>
        </div>
      </section>

      <div className="shell comm-layout">
        <main className="comm-feed">
          <div className="comm-toolbar">
            <div className="comm-sorts">
              {sorts.map(s => (
                <button key={s} className="sortbtn" data-on={sort === s} onClick={() => setSort(s)}>
                  <Icon name={s === "Hot" ? "flame" : s === "New" ? "bolt" : "arrowUp"} size={15} />{s}
                </button>
              ))}
            </div>
            {active !== "all" && (
              <button className="chip" data-on="true" onClick={() => setActive("all")}>
                {active} <Icon name="x" size={13} />
              </button>
            )}
          </div>
          <div className="post-list">
            {posts.map((p, i) => <PostRow key={p.id} post={p} i={i} onOpen={(id) => go("community/" + id)} />)}
          </div>
        </main>

        <aside className="comm-side">
          <div className="surface side-card">
            <span className="kicker">Your communities</span>
            <ul className="comm-list">
              {COMMUNITIES.map(c => (
                <li key={c.id}>
                  <button className="comm-item" data-on={active === c.name} onClick={() => setActive(active === c.name ? "all" : c.name)}>
                    <span className="comm-badge" style={{ background: c.color }}>{c.name[0]}</span>
                    <span className="comm-item-txt">
                      <b>{c.name}</b>
                      <span>{c.members} members</span>
                    </span>
                    <Icon name="arrowRight" size={15} className="comm-item-go" />
                  </button>
                </li>
              ))}
            </ul>
            <button className="side-all">Browse all communities <Icon name="arrowRight" size={14} /></button>
          </div>
          <div className="surface side-card side-cta">
            <Icon name="users" size={22} />
            <b className="serif">Start a community</b>
            <p>Got a niche? Gather the people who care about it.</p>
            <button className="btn btn-soft">Create one</button>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ---------- Post thread (live comments) ---------- */
function relTime(ts) {
  const d = new Date(String(ts).replace(" ", "T"));
  const s = (Date.now() - d.getTime()) / 1000;
  if (isNaN(s)) return "now";
  if (s < 60) return "now";
  if (s < 3600) return Math.round(s / 60) + "m";
  if (s < 86400) return Math.round(s / 3600) + "h";
  return Math.round(s / 86400) + "d";
}

function PostThread({ id, go, posts }) {
  const post = (posts || POSTS).find(p => p.id === id) || (posts || POSTS)[0];
  const comm = COMMUNITIES.find(c => c.name === post.sub);
  const [draft, setDraft] = useState("");
  const [comments, setComments] = useState([]);
  const [busy, setBusy] = useState(false);
  const user = (typeof window !== "undefined" && window.__USER__) || null;
  const tid = post && post._id;
  useEffect(() => {
    if (!tid) return;
    fetch("/api/comments?type=thread&id=" + tid).then(r => r.json()).then(j => setComments(j.comments || [])).catch(() => {});
  }, [tid]);
  const send = async () => {
    if (!draft.trim() || busy) return;
    if (!user) { document.dispatchEvent(new CustomEvent("ipanjab:auth")); return; }
    setBusy(true);
    try {
      const r = await fetch("/api/comment", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ type: "thread", id: tid, body: draft.trim() }) });
      const j = await r.json();
      if (r.ok && j.comment) { setComments(c => [...c, j.comment]); setDraft(""); }
    } catch (_) {}
    setBusy(false);
  };
  const list = [...comments].reverse();
  return (
    <div className="view thread">
      <div className="shell thread-shell">
        <button className="back" onClick={() => go("community")}><Icon name="arrowLeft" size={16} /> {post.sub}</button>
        <article className="thread-post surface">
          <div className="post-top">
            <span className="post-sub" style={{ "--c": comm?.color }}><span className="sub-dot" /> {post.sub}</span>
            <span className="post-by">· {post.author} · {post.time}</span>
            <span className="tag post-tag">{post.tag}</span>
          </div>
          <h1 className="thread-title serif">{post.title}</h1>
          <p className="thread-body">{post.body}</p>
          {post.img && <Cover seed={post.id} aspect="16 / 8" radius="12px" className="thread-img" />}
          <div className="thread-bar">
            <VoteCluster initial={post.votes} type={post._type} id={post._id} liked={post.liked} />
            <span><Icon name="comment" size={17} />{comments.length || post.comments}</span>
            <span><Icon name="share" size={17} />Share</span>
            <span><Icon name="bookmark" size={17} />Save</span>
          </div>
        </article>

        <div className="reply-box surface">
          <Avatar seed={user ? user.email : "you"} label={user ? user.name : "You"} size={36} />
          <input placeholder={user ? "Add your two cents…" : "Log in to join the conversation…"} value={draft} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === "Enter") send(); }} />
          <button className="btn btn-primary" data-dim={!draft.trim() || busy} onClick={send}>{busy ? "…" : "Reply"}</button>
        </div>

        <div className="comments">
          <span className="kicker">{comments.length} comments · newest first</span>
          {list.map((c, i) => (
            <div key={c.id || i} className="comment" style={{ "--i": i }}>
              <Avatar seed={c.author || "x"} label={c.author} size={34} />
              <div className="comment-main">
                <div className="comment-head"><b>{c.author || "someone"}</b><span>· {relTime(c.created_at)}</span></div>
                <p>{c.body}</p>
                <div className="comment-foot"><button>Reply</button><button>Share</button></div>
              </div>
            </div>
          ))}
          {comments.length === 0 && <p style={{ color: "var(--ink-faint)", padding: "10px 0", fontSize: 14 }}>Be the first to comment.</p>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Community, PostThread, PostRow });
