/* ============================================================
   ADMIN RSS — feed management + review queue
   window: AdminRSS
   ============================================================ */
(function () {
  const { useApp, H, Icon, useCurrentStaff } = window;
  const { AdminPageHead: PageHead } = window;

  function AddFeed({ onClose }) {
    const app = useApp();
    const [name, setName] = React.useState("");
    const [url, setUrl] = React.useState("");
    const [cat, setCat] = React.useState("world");
    const [mode, setMode] = React.useState("review");
    return (
      <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "oklch(0.2 0.02 250 / 0.45)", zIndex: 60, display: "grid", placeItems: "center", padding: 20 }}>
        <div onClick={e => e.stopPropagation()} className="fade-in" style={{ width: "min(460px,100%)", background: "var(--surface)", borderRadius: 10, boxShadow: "var(--shadow-2)", overflow: "hidden" }}>
          <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--line)", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
            <h3 className="serif" style={{ fontSize: 20, fontWeight: 700 }}>নতুন আরএসএস ফিড</h3>
            <button className="btn ghost sm" onClick={onClose}><Icon name="x" size={16} /></button>
          </div>
          <div style={{ padding: 22, display: "grid", gap: 16 }}>
            <label className="field"><span className="lbl">ফিডের নাম</span><input value={name} onChange={e => setName(e.target.value)} placeholder="যেমন: BBC বাংলা" /></label>
            <label className="field"><span className="lbl">ফিড URL</span><input value={url} onChange={e => setUrl(e.target.value)} placeholder="https://…/rss.xml" /></label>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <label className="field"><span className="lbl">ডিফল্ট বিভাগ</span>
                <select value={cat} onChange={e => setCat(e.target.value)}>{window.SEED.CATEGORIES.map(c => <option key={c.slug} value={c.slug}>{c.bn}</option>)}</select></label>
              <label className="field"><span className="lbl">প্রকাশ ধরন</span>
                <select value={mode} onChange={e => setMode(e.target.value)}><option value="review">রিভিউ কিউ</option><option value="auto">স্বয়ংক্রিয়</option></select></label>
            </div>
          </div>
          <div style={{ padding: "16px 22px", borderTop: "1px solid var(--line)", display: "flex", justifyContent: "flex-start", gap: 10 }}>
            <button className="btn primary" disabled={!name || !url} onClick={() => { app.addFeed({ name, url, cat, mode, interval: 15 }); onClose(); }}>ফিড যুক্ত করুন</button>
            <button className="btn" onClick={onClose}>বাতিল</button>
          </div>
        </div>
      </div>
    );
  }

  /* Publisher term → category mapping. Items whose RSS <category> matches an
     alias get that category; everything else falls back to the feed default. */
  function AliasTab() {
    const app = useApp();
    const me = useCurrentStaff();
    const [term, setTerm] = React.useState("");
    const [cat, setCat] = React.useState(window.SEED.CATEGORIES[0].slug);
    const aliases = app.state.aliases;
    const canEdit = me.perms.rss;
    const submit = () => { if (term.trim()) { app.addAlias({ term: term.trim(), cat }); setTerm(""); } };
    return (
      <div style={{ display: "grid", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--ink-3)", fontSize: 13 }}>
          <Icon name="rss" size={15} /> ফিডের আইটেমে থাকা ক্যাটাগরি শব্দ নিচের ম্যাপিং অনুযায়ী বিভাগ পায়; কোনো মিল না থাকলে ফিডের ডিফল্ট বিভাগ ব্যবহৃত হয়।
        </div>
        <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "16px 20px", display: "flex", gap: 10, alignItems: "flex-end", flexWrap: "wrap" }}>
          <label className="field" style={{ flex: "1 1 220px" }}><span className="lbl">ফিডের শব্দ</span>
            <input value={term} onChange={e => setTerm(e.target.value)} onKeyDown={e => { if (e.key === "Enter") submit(); }} placeholder="যেমন: ক্রিকেট, Sport" disabled={!canEdit} /></label>
          <label className="field" style={{ width: 180 }}><span className="lbl">বিভাগ</span>
            <select value={cat} onChange={e => setCat(e.target.value)} disabled={!canEdit}>{window.SEED.CATEGORIES.map(c => <option key={c.slug} value={c.slug}>{c.bn}</option>)}</select></label>
          <button className="btn primary" disabled={!canEdit || !term.trim()} onClick={submit}><Icon name="plus" size={15} /> যুক্ত করুন</button>
        </div>
        {window.SEED.CATEGORIES.map(c => {
          const list = aliases.filter(a => a.cat === c.slug);
          if (!list.length) return null;
          return (
            <div key={c.slug} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "14px 20px", display: "grid", gridTemplateColumns: "150px 1fr", gap: 14, alignItems: "baseline" }}>
              <span className="serif" style={{ fontSize: 16, fontWeight: 700 }}>{c.bn}</span>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {list.map(a => (
                  <span key={a.term} className="chip" style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "4px 10px" }}>
                    {a.term}
                    <button onClick={() => app.removeAlias(a.term)} disabled={!canEdit} style={{ border: 0, background: "none", cursor: canEdit ? "pointer" : "default", color: "var(--ink-3)", padding: 0, display: "inline-grid", placeItems: "center" }} aria-label={"মুছুন " + a.term}><Icon name="x" size={12} /></button>
                  </span>
                ))}
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  function AdminRSS() {
    const app = useApp();
    const me = useCurrentStaff();
    const [tab, setTab] = React.useState("queue");
    const [adding, setAdding] = React.useState(false);
    const [backfilling, setBackfilling] = React.useState(false);
    const pollRef = React.useRef(null);
    const queue = app.state.queue;
    const feeds = app.state.feeds;

    React.useEffect(() => () => clearInterval(pollRef.current), []);

    /* Re-fetches full article text for RSS items whose body is only the feed
       summary (backend backfill job); polls its status until it finishes. */
    const runBackfill = async () => {
      setBackfilling(true);
      try {
        const res = await window.API.admin.backfill.start({});
        if (!res.started && !res.candidates) { app.toast("আনার মতো কিছু নেই"); setBackfilling(false); return; }
        pollRef.current = setInterval(async () => {
          try {
            const s = await window.API.admin.backfill.status();
            if (!s.running) {
              clearInterval(pollRef.current);
              setBackfilling(false);
              app.toast(`সম্পূর্ণ টেক্সট আনা শেষ — ${H.toBn(s.updated)}টি হালনাগাদ, ${H.toBn(s.failed)}টি ব্যর্থ`);
            }
          } catch (e) { clearInterval(pollRef.current); setBackfilling(false); }
        }, 2000);
      } catch (e) {
        setBackfilling(false);
        app.toast(e && e.status === 409 ? "ইতিমধ্যে চলছে" : "সম্পূর্ণ টেক্সট আনা ব্যর্থ হয়েছে");
      }
    };

    return (
      <div className="fade-in">
        <PageHead title="আরএসএস ও রিভিউ" sub="ফিড থেকে আসা সংবাদ পর্যালোচনা ও প্রকাশ করুন">
          <button className="btn" disabled={!me.perms.rss || backfilling} onClick={runBackfill}>
            <Icon name="rss" size={15} /> {backfilling ? "আনা হচ্ছে…" : "সম্পূর্ণ টেক্সট আনুন"}
          </button>
          <button className="btn primary" onClick={() => setAdding(true)}><Icon name="plus" size={16} /> ফিড যুক্ত করুন</button>
        </PageHead>

        <div style={{ display: "flex", gap: 4, background: "var(--surface)", border: "1px solid var(--line)", borderRadius: 999, padding: 4, width: "fit-content", marginBottom: 20 }}>
          <button onClick={() => setTab("queue")} style={{ border: 0, padding: "8px 18px", borderRadius: 999, cursor: "pointer", fontSize: 13.5, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 7, background: tab === "queue" ? "var(--accent-wash)" : "transparent", color: tab === "queue" ? "var(--accent-ink)" : "var(--ink-3)" }}>
            রিভিউ কিউ {queue.length > 0 && <span style={{ background: "var(--accent)", color: "#fff", fontSize: 11, fontWeight: 700, minWidth: 18, height: 18, borderRadius: 999, display: "grid", placeItems: "center", padding: "0 5px" }}>{H.toBn(queue.length)}</span>}
          </button>
          <button onClick={() => setTab("feeds")} style={{ border: 0, padding: "8px 18px", borderRadius: 999, cursor: "pointer", fontSize: 13.5, fontWeight: 600, background: tab === "feeds" ? "var(--accent-wash)" : "transparent", color: tab === "feeds" ? "var(--accent-ink)" : "var(--ink-3)" }}>উৎস ফিড ({H.toBn(feeds.length)})</button>
          <button onClick={() => setTab("aliases")} style={{ border: 0, padding: "8px 18px", borderRadius: 999, cursor: "pointer", fontSize: 13.5, fontWeight: 600, background: tab === "aliases" ? "var(--accent-wash)" : "transparent", color: tab === "aliases" ? "var(--accent-ink)" : "var(--ink-3)" }}>বিভাগ ম্যাপিং</button>
        </div>

        {tab === "aliases" ? <AliasTab /> : tab === "queue" ? (
          <div>
            {!queue.length ? (
              <div style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "60px 20px", textAlign: "center" }}>
                <div style={{ display: "inline-grid", placeItems: "center", width: 60, height: 60, borderRadius: "50%", background: "color-mix(in oklch, var(--green), transparent 86%)", color: "var(--green)", marginBottom: 14 }}><Icon name="check" size={28} /></div>
                <p className="serif" style={{ fontSize: 20, marginBottom: 6 }}>কিউ পরিষ্কার</p>
                <p className="muted">সব ফিড আইটেম পর্যালোচনা করা হয়েছে।</p>
              </div>
            ) : (
              <div style={{ display: "grid", gap: 14 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--ink-3)", fontSize: 13, marginBottom: 2 }}>
                  <Icon name="clock" size={15} /> এই আইটেমগুলো রিভিউ-মোড ফিড থেকে এসেছে এবং প্রকাশের আগে অনুমোদন প্রয়োজন।
                </div>
                {queue.map(item => { const canAct = me.cats.includes("all") || me.cats.includes(item.cat); return (
                  <div key={item.id} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "18px 20px", display: "grid", gridTemplateColumns: "1fr auto", gap: 18, alignItems: "center" }} className="queue-card">
                    <div style={{ minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 8 }}>
                        <span className="badge gray" style={{ display: "inline-flex", alignItems: "center", gap: 4 }}><Icon name="rss" size={10} /> {item.feed}</span>
                        <span className="chip" style={{ padding: "2px 9px" }}>{H.catBy(item.cat).bn}</span>
                        <span className="muted" style={{ fontSize: 12 }}>{H.rel(item.ts)}</span>
                      </div>
                      <h3 className="serif" style={{ fontSize: 19, fontWeight: 700, lineHeight: 1.25, marginBottom: 6 }}>{item.bn}</h3>
                      <p className="ink2" style={{ fontSize: 14, lineHeight: 1.5 }}>{item.excerpt_bn}</p>
                    </div>
                    <div style={{ display: "flex", flexDirection: "column", gap: 8, minWidth: 140 }}>
                      <button className="btn primary sm" style={{ justifyContent: "center" }} disabled={!me.perms.publish || !canAct} onClick={() => app.approveQueue(item.id)}><Icon name="check" size={15} /> অনুমোদন</button>
                      <button className="btn sm" style={{ justifyContent: "center" }} disabled={!me.perms.edit || !canAct} onClick={() => { app.toast("সম্পাদকে খোলা হচ্ছে"); }}><Icon name="edit" size={14} /> সম্পাদনা</button>
                      <button className="btn danger sm" style={{ justifyContent: "center" }} disabled={!me.perms.publish || !canAct} onClick={() => app.rejectQueue(item.id)}><Icon name="x" size={14} /> বাতিল</button>
                    </div>
                  </div>
                ); })}
              </div>
            )}
          </div>
        ) : (
          <div style={{ display: "grid", gap: 14 }}>
            {feeds.map(f => (
              <div key={f.id} style={{ background: "var(--surface)", border: "1px solid var(--line)", borderRadius: "var(--radius)", padding: "18px 20px", display: "grid", gridTemplateColumns: "auto 1fr auto", gap: 16, alignItems: "center" }} className="feed-card">
                <span style={{ width: 42, height: 42, borderRadius: 10, background: f.status === "active" ? "var(--accent-wash)" : "var(--surface-2)", color: f.status === "active" ? "var(--accent-ink)" : "var(--ink-3)", display: "grid", placeItems: "center" }}><Icon name="rss" size={20} /></span>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 3 }}>
                    <span className="serif" style={{ fontSize: 17, fontWeight: 700 }}>{f.name}</span>
                    <span className={"badge " + (f.status === "active" ? "green" : "gray")}>{f.status === "active" ? "সক্রিয়" : "বিরতি"}</span>
                    <span className={"badge " + (f.mode === "auto" ? "amber" : "teal")}>{f.mode === "auto" ? "স্বয়ংক্রিয়" : "রিভিউ"}</span>
                  </div>
                  <div className="muted" style={{ fontSize: 12.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", direction: "ltr", textAlign: "right" }}><Icon name="link" size={11} style={{ display: "inline", verticalAlign: "-1px", marginLeft: 4 }} />{f.url}</div>
                  <div className="meta" style={{ fontSize: 12, marginTop: 5 }}>{H.catBy(f.cat).bn}<span className="dot" />সিংক: {f.lastSync}<span className="dot" />{H.bnNum(f.items)} আইটেম<span className="dot" />প্রতি {H.toBn(f.interval)} মিনিট</div>
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <select value={f.mode} onChange={e => app.setFeedMode(f.id, e.target.value)} disabled={!me.perms.rss} style={{ width: "auto", padding: "7px 10px", fontSize: 13 }}>
                    <option value="review">রিভিউ</option><option value="auto">স্বয়ংক্রিয়</option>
                  </select>
                  <button className="btn sm" disabled={!me.perms.rss} onClick={() => app.toggleFeed(f.id)}>{f.status === "active" ? "বিরতি" : "চালু"}</button>
                  <button className="btn ghost sm" disabled={!me.perms.rss} onClick={() => app.removeFeed(f.id)} style={{ color: "var(--red)", padding: 7 }}><Icon name="trash" size={15} /></button>
                </div>
              </div>
            ))}
          </div>
        )}

        {adding && <AddFeed onClose={() => setAdding(false)} />}
      </div>
    );
  }

  window.AdminRSS = AdminRSS;
})();
