/* ============================================================
   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}{post.city ? (", " + post.city) : ""}</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 [loc, setLoc] = useState(() => { try { return localStorage.getItem("ipanjab_city") || "Everywhere"; } catch (e) { return "Everywhere"; } });
  const baseCities = Array.from(new Set(((typeof window !== "undefined" && window.__DATA__ && window.__DATA__.cities) || []).filter(Boolean)));
  if (loc && loc !== "Everywhere" && loc !== "Worldwide" && baseCities.indexOf(loc) < 0) baseCities.push(loc);
  const cities = ["Everywhere", ...baseCities];
  const sorts = ["Hot", "New", "Top"];
  let posts = [...(allPosts || POSTS)];
  if (active !== "all") posts = posts.filter(p => p.sub === active);
  if (loc !== "Everywhere" && loc !== "Worldwide") posts = posts.filter(p => p.city === loc);
  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">
            <select className="loc-select" value={cities.indexOf(loc) >= 0 ? loc : "Everywhere"} onChange={e => { const v = e.target.value; setLoc(v); try { v === "Everywhere" ? localStorage.removeItem("ipanjab_city") : localStorage.setItem("ipanjab_city", v); } catch (x) {} }}>{cities.map(c => <option key={c} value={c}>{c}</option>)}</select>
            <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" onClick={() => go("c/" + 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" onClick={() => setActive("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" onClick={() => go("compose")}>Create one</button>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ---------- Community landing page ---------- */
function CommunityPage({ name, go, posts: allPosts }) {
  const comm = COMMUNITIES.find(c => c.name === name);
  const me = (typeof window !== "undefined" && window.__USER__) || null;
  const people = (typeof window !== "undefined" && window.__DATA__ && window.__DATA__.people) || [];
  const [tab, setTab] = useState("posts");
  const [joined, setJoined] = useState(() => { try { return (JSON.parse(localStorage.getItem("ipanjab_joined") || "[]")).indexOf(name) >= 0; } catch (e) { return false; } });

  if (!comm) {
    return (
      <div className="view community-page">
        <div className="shell">
          <div className="pf-empty" style={{ marginTop: 80 }}>
            <Icon name="users" size={28} />
            <b className="serif">Community not found</b>
            <p>This community may have been renamed or removed.</p>
            <button className="btn btn-primary" onClick={() => go("community")}>Back to community</button>
          </div>
        </div>
      </div>
    );
  }

  const posts = (allPosts || POSTS).filter(p => p.sub === name);
  const authorNames = Array.from(new Set(posts.map(p => p.author).filter(Boolean)));
  const members = authorNames.map(n => people.find(p => p.name === n) || { id: null, name: n, handle: "" });
  const baseCount = parseInt(String(comm.members).replace(/[^\d]/g, "")) || members.length;
  const memberCount = baseCount + (joined ? 1 : 0);

  const toggleJoin = () => {
    if (!me) { document.dispatchEvent(new CustomEvent("ipanjab:auth")); return; }
    setJoined(j => {
      const nj = !j;
      try {
        let arr = JSON.parse(localStorage.getItem("ipanjab_joined") || "[]");
        if (nj) { if (arr.indexOf(name) < 0) arr.push(name); } else { arr = arr.filter(x => x !== name); }
        localStorage.setItem("ipanjab_joined", JSON.stringify(arr));
      } catch (e) {}
      return nj;
    });
  };

  return (
    <div className="view community-page">
      <section className="cpage-banner" style={{ "--cc": comm.color }}>
        <div className="shell">
          <button className="back back-light" onClick={() => go("community")}><Icon name="arrowLeft" size={16} /> All communities</button>
          <div className="cpage-head">
            <span className="cpage-badge" style={{ background: comm.color }}>{comm.name[0]}</span>
            <div className="cpage-id">
              <h1 className="serif">{comm.name}</h1>
              <p>{comm.desc}</p>
              <span className="cpage-meta">{memberCount} {memberCount === 1 ? "member" : "members"} · {posts.length} {posts.length === 1 ? "post" : "posts"}</span>
            </div>
            <div className="cpage-actions">
              <button className={"btn " + (joined ? "btn-soft" : "btn-primary")} onClick={toggleJoin}>{joined ? "Joined" : "Join"}</button>
              <button className="btn btn-soft" onClick={() => go("compose")}><Icon name="plus" size={16} /> New post</button>
            </div>
          </div>
        </div>
      </section>

      <div className="shell cpage-body">
        <div className="cpage-tabs">
          {["posts", "members", "about"].map(tb => (
            <button key={tb} className="pf-tab" data-on={tab === tb} onClick={() => setTab(tb)}>
              {tb[0].toUpperCase() + tb.slice(1)}
              {tb === "posts" && <span className="pf-tab-n">{posts.length}</span>}
              {tb === "members" && <span className="pf-tab-n">{members.length}</span>}
            </button>
          ))}
        </div>

        {tab === "posts" && (
          posts.length ? (
            <div className="post-list">
              {posts.map((p, i) => <PostRow key={p.id} post={p} i={i} onOpen={(id) => go("community/" + id)} />)}
            </div>
          ) : (
            <div className="pf-empty">
              <Icon name="chat" size={28} />
              <b className="serif">No posts yet</b>
              <p>Be the first to start a thread in {comm.name}.</p>
              <button className="btn btn-primary" onClick={() => go("compose")}>New post</button>
            </div>
          )
        )}

        {tab === "members" && (
          members.length ? (
            <div className="people-grid">
              {members.map((p, i) => (
                <button key={p.id || i} className="person-card" onClick={() => p.id ? go("profile/u" + p.id) : null}>
                  <Avatar seed={p.handle || p.name} label={p.name} size={46} />
                  <div className="person-main">
                    <b>{p.name}{vTick(p.name)}</b>
                    {p.handle && <span className="person-handle">{p.handle}</span>}
                  </div>
                  {p.id && <Icon name="arrowRight" size={16} className="person-go" />}
                </button>
              ))}
            </div>
          ) : (
            <div className="empty">No active members yet — join and post to be the first.</div>
          )
        )}

        {tab === "about" && (
          <div className="cpage-about surface">
            <h3 className="serif">About {comm.name}</h3>
            <p>{comm.desc}</p>
            <div className="hr" style={{ margin: "16px 0" }} />
            <div className="cpage-about-row"><span className="kicker">Members</span><b>{memberCount}</b></div>
            <div className="cpage-about-row"><span className="kicker">Posts</span><b>{posts.length}</b></div>
            <div className="cpage-about-row"><span className="kicker">Guidelines</span><span>Be kind, keep it Punjabi, no spam. Posts here are public to the diaspora worldwide.</span></div>
          </div>
        )}
      </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("c/" + post.sub)}><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 }} onClick={() => go("c/" + post.sub)}><span className="sub-dot" /> {post.sub}</span>
            <span className="post-by">· {post.author} · {post.time}{post.city ? (", " + post.city) : ""}</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, CommunityPage, PostThread, PostRow });
