/* ============================================================
   ADMIN DASHBOARD + POSTS LIST
   window: AdminDashboard, AdminPosts
   ============================================================ */
(function () {
  const { useApp, H, Icon, useCurrentStaff, RoleBadge } = window;

  function Stat({ label, value, sub, accent }) {
    return (
      <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "18px 20px" }}>
        <div className="muted" style={{ fontSize: 12.5, fontWeight: 600, marginBottom: 8 }}>{label}</div>
        <div className="serif" style={{ fontSize: 34, fontWeight: 700, color: accent ? "var(--accent-ink)" : "var(--ink)", lineHeight: 1 }}>{value}</div>
        {sub && <div style={{ fontSize: 12, color: "var(--green)", marginTop: 7, fontWeight: 600 }}>{sub}</div>}
      </div>
    );
  }

  function PageHead({ title, sub, children }) {
    return (
      <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 14, marginBottom: 24 }}>
        <div>
          <h1 className="serif nowrap" style={{ fontSize: 28, fontWeight: 700 }}>{title}</h1>
          {sub && <p className="muted" style={{ fontSize: 14, marginTop: 4 }}>{sub}</p>}
        </div>
        {children}
      </div>
    );
  }
  window.AdminPageHead = PageHead;

  function AdminDashboard() {
    const app = useApp();
    const me = useCurrentStaff();
    const posts = app.state.posts;
    const published = posts.filter(p => p.status === "published");
    const totalViews = app.state.articles.reduce((s, a) => s + ((app.state.articleState[a.id] || {}).views || 0), 0);
    const recent = [...posts].sort((a, b) => b.ts - a.ts).slice(0, 6);
    const queueCount = app.state.queue.length;

    // simple bar data — articles per category
    const byCat = window.SEED.CATEGORIES.map(c => ({ c, n: posts.filter(p => p.cat === c.slug).length })).filter(x => x.n).sort((a, b) => b.n - a.n);
    const maxN = Math.max(...byCat.map(x => x.n), 1);

    return (
      <div className="fade-in">
        <PageHead title={`স্বাগতম, ${me.name.split(" ")[0]}`} sub="আজকের নিউজরুমের সারসংক্ষেপ" >
          <div style={{ display: "flex", gap: 8 }}>
            {me.perms.create && <button className="btn primary" onClick={() => app.nav("admin-editor")}><Icon name="plus" size={16} /> নতুন পোস্ট</button>}
            {me.perms.rss && queueCount > 0 && <button className="btn" onClick={() => app.nav("admin-rss")}><Icon name="rss" size={15} /> রিভিউ ({H.toBn(queueCount)})</button>}
          </div>
        </PageHead>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 16, marginBottom: 24 }} className="stat-grid">
          <Stat label="প্রকাশিত পোস্ট" value={H.toBn(published.length)} sub="↑ ৩ আজ" accent />
          <Stat label="রিভিউ অপেক্ষমাণ" value={H.toBn(queueCount)} sub={queueCount ? "মনোযোগ প্রয়োজন" : "সব পরিষ্কার"} />
          <Stat label="মোট পাঠ" value={H.bnNum(totalViews)} sub="↑ ১২% সপ্তাহে" />
          <Stat label="সক্রিয় মডারেটর" value={H.toBn(app.state.staff.filter(s => s.status === "active").length)} />
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1.5fr 1fr", gap: 20 }} className="dash-grid">
          {/* recent posts */}
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden" }}>
            <div style={{ padding: "16px 20px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <h3 className="serif nowrap" style={{ fontSize: 18, fontWeight: 700 }}>সাম্প্রতিক পোস্ট</h3>
              <button className="btn ghost sm" onClick={() => app.nav("admin-posts")}>সব দেখুন <Icon name="chevR" size={14} /></button>
            </div>
            <div>
              {recent.map(p => (
                <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 14, padding: "13px 20px", borderBottom: "1px solid var(--line-2)" }}>
                  <span style={{ width: 8, height: 8, borderRadius: "50%", background: p.status === "published" ? "var(--green)" : "var(--amber)", flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="serif" style={{ fontSize: 15, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.bn}</div>
                    <div className="meta" style={{ fontSize: 11.5, marginTop: 3 }}>
                      {H.catBy(p.cat).bn}<span className="dot" />{H.rel(p.ts)}
                      {p.source === "rss" && <><span className="dot" /><span style={{ display: "inline-flex", alignItems: "center", gap: 3, color: "var(--accent-ink)" }}><Icon name="rss" size={10} /> {p.feed}</span></>}
                    </div>
                  </div>
                  <span className={"badge " + (p.source === "rss" ? "gray" : "teal")} style={{ flexShrink: 0 }}>{p.source === "rss" ? "RSS" : "নিজস্ব"}</span>
                </div>
              ))}
            </div>
          </div>

          {/* category distribution */}
          <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "16px 20px" }}>
            <h3 className="serif nowrap" style={{ fontSize: 18, fontWeight: 700, marginBottom: 18 }}>বিভাগভিত্তিক পোস্ট</h3>
            <div style={{ display: "grid", gap: 14 }}>
              {byCat.map(({ c, n }) => (
                <div key={c.slug}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13, marginBottom: 5 }}>
                    <span style={{ fontWeight: 600 }}>{c.bn}</span><span className="muted" style={{ fontVariantNumeric: "tabular-nums" }}>{H.toBn(n)}</span>
                  </div>
                  <div style={{ height: 7, background: "var(--surface-2)", borderRadius: 999, overflow: "hidden" }}>
                    <div style={{ width: (n / maxN * 100) + "%", height: "100%", background: "var(--accent)", borderRadius: 999 }} />
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }

  function AdminPosts() {
    const app = useApp();
    const me = useCurrentStaff();
    const [filter, setFilter] = React.useState("all");
    const [q, setQ] = React.useState("");
    let posts = [...app.state.posts].sort((a, b) => b.ts - a.ts);
    if (filter === "rss") posts = posts.filter(p => p.source === "rss");
    if (filter === "manual") posts = posts.filter(p => p.source === "manual");
    if (filter === "draft") posts = posts.filter(p => p.status === "draft");
    if (q.trim()) posts = posts.filter(p => (p.bn + p.en).toLowerCase().includes(q.toLowerCase()));

    const inCat = (cat) => me.cats.includes("all") || me.cats.includes(cat);
    const canEditCat = (cat) => me.perms.edit && inCat(cat);
    const canToggle = (cat) => me.perms.publish && inCat(cat);

    return (
      <div className="fade-in">
        <PageHead title="সব পোস্ট" sub={`মোট ${H.toBn(app.state.posts.length)}টি পোস্ট`}>
          {me.perms.create && <button className="btn primary" onClick={() => app.nav("admin-editor")}><Icon name="plus" size={16} /> নতুন পোস্ট</button>}
        </PageHead>

        <div style={{ display: "flex", gap: 10, marginBottom: 16, flexWrap: "wrap" }}>
          <div style={{ display: "flex", gap: 4, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 999, padding: 4 }}>
            {[["all", "সব"], ["manual", "নিজস্ব"], ["rss", "RSS"], ["draft", "খসড়া"]].map(([k, l]) => (
              <button key={k} onClick={() => setFilter(k)} style={{ border: 0, padding: "7px 15px", borderRadius: 999, cursor: "pointer", fontSize: 13, fontWeight: 600, background: filter === k ? "var(--accent-wash)" : "transparent", color: filter === k ? "var(--accent-ink)" : "var(--ink-3)" }}>{l}</button>
            ))}
          </div>
          <div style={{ position: "relative", flex: 1, minWidth: 200 }}>
            <Icon name="search" size={16} style={{ position: "absolute", right: 12, top: 11, color: "var(--ink-3)" }} />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="পোস্ট খুঁজুন…" style={{ paddingRight: 38 }} />
          </div>
        </div>

        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", overflow: "hidden" }}>
          {/* header row */}
          <div className="post-row post-head" style={{ display: "grid", gridTemplateColumns: "1fr 130px 110px 100px 124px", gap: 14, padding: "12px 20px", borderBottom: "1px solid var(--line)", fontSize: 11.5, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase", color: "var(--ink-3)" }}>
            <span>শিরোনাম</span><span>বিভাগ</span><span>উৎস</span><span>অবস্থা</span><span style={{ textAlign: "left" }}>ক্রিয়া</span>
          </div>
          {posts.map(p => {
            const editable = canEditCat(p.cat);
            return (
              <div key={p.id} className="post-row" style={{ display: "grid", gridTemplateColumns: "1fr 130px 110px 100px 124px", gap: 14, padding: "13px 20px", borderBottom: "1px solid var(--line-2)", alignItems: "center" }}>
                <div style={{ minWidth: 0 }}>
                  <div className="serif" style={{ fontSize: 15, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.bn}</div>
                  <div className="muted" style={{ fontSize: 11.5, marginTop: 2 }}>{H.rel(p.ts)} · {p.author}</div>
                </div>
                <span style={{ fontSize: 13 }}>{H.catBy(p.cat).bn}</span>
                <span className={"badge " + (p.source === "rss" ? "gray" : "teal")} style={{ width: "fit-content" }}>{p.source === "rss" ? "RSS" : "নিজস্ব"}</span>
                <span className={"badge " + (p.status === "published" ? "green" : "amber")} style={{ width: "fit-content" }}>{p.status === "published" ? "প্রকাশিত" : "খসড়া"}</span>
                <div style={{ display: "flex", gap: 4, justifyContent: "flex-start" }}>
                  <button className="btn ghost sm" disabled={!editable} title={editable ? "সম্পাদনা" : "অনুমতি নেই"} onClick={() => app.nav("admin-editor", { id: p.id })} style={{ padding: 7 }}><Icon name="edit" size={15} /></button>
                  <button className="btn ghost sm" disabled={!canToggle(p.cat)}
                    title={!canToggle(p.cat) ? "অনুমতি নেই" : (p.status === "published" ? "খসড়ায় নিন" : "প্রকাশ করুন")}
                    onClick={() => app.setPostStatus(p.id, p.status === "published" ? "draft" : "published")}
                    style={{ padding: 7 }}><Icon name={p.status === "published" ? "file" : "up"} size={15} /></button>
                  <button className="btn ghost sm" disabled={!me.perms.delete || !inCat(p.cat)} title={(me.perms.delete && inCat(p.cat)) ? "মুছুন" : "অনুমতি নেই"} onClick={() => app.deletePost(p.id)} style={{ padding: 7, color: (me.perms.delete && inCat(p.cat)) ? "var(--red)" : undefined }}><Icon name="trash" size={15} /></button>
                </div>
              </div>
            );
          })}
          {!posts.length && <div className="muted" style={{ padding: 40, textAlign: "center" }}>কোনো পোস্ট পাওয়া যায়নি।</div>}
        </div>
      </div>
    );
  }

  Object.assign(window, { AdminDashboard, AdminPosts });
})();
