/* educator-authors.jsx — Authors folder (Educator + Delivery portals).
   Manage the authors who build individual products: see each author and the
   products they build, assign an author to a product (by email), remove them,
   and spot products that still need an author. Server roster via /api/authors. */
function AuthorsScreen({ toast }) {
  const [data, setData] = useState(null);          // { authors, unassigned, products } | null
  const [busy, setBusy] = useState(false);
  const [selProd, setSelProd] = useState("");
  const [email, setEmail] = useState("");
  const [q, setQ] = useState("");
  const tell = (m, i) => { if (toast) toast(m, i); else if (window.eduToast) window.eduToast(m, i); };

  async function load() {
    try { if (window.VHProducts) setData(await window.VHProducts.authors()); }
    catch (e) { setData({ authors: [], unassigned: [], products: [] }); }
  }
  useEffect(() => { load(); }, []);

  async function assign(pid, mail) {
    const p = pid || selProd, e = (mail || email).trim();
    if (!p) { tell("Pick a product first", "x"); return; }
    if (!e) { tell("Enter the author's email", "x"); return; }
    setBusy(true);
    try { const a = await window.VHProducts.assign(p, e); tell("Assigned " + (a && a.name ? a.name : e), "check"); setEmail(""); setSelProd(""); await load(); }
    catch (err) { tell(err.message || "Could not assign author", "x"); }
    setBusy(false);
  }
  async function unassign(pid, mail) {
    if (!window.confirm("Remove " + mail + " from this product?")) return;
    try { await window.VHProducts.unassign(pid, mail); tell("Author removed", "check"); await load(); }
    catch (err) { tell(err.message || "Could not remove author", "x"); }
  }

  const authors = (data && data.authors) || [];
  const unassigned = (data && data.unassigned) || [];
  const products = (data && data.products) || [];
  const shown = authors.filter((a) => !q || (a.name || "").toLowerCase().includes(q.toLowerCase()) || (a.email || "").toLowerCase().includes(q.toLowerCase()));
  const builders = authors.filter((a) => a.assigned.length || a.role === "author").length;

  return (
    <div>
      <div className="between" style={{ marginBottom: 22 }}>
        <div className="page-head" style={{ marginBottom: 0 }}>
          <h1>Authors</h1>
          <p>{authors.length} author{authors.length === 1 ? "" : "s"} · {builders} building products · {unassigned.length} product{unassigned.length === 1 ? "" : "s"} without an author</p>
        </div>
      </div>

      {/* Assign an author to a product */}
      <div className="card" style={{ padding: 20, marginBottom: 20 }}>
        <div className="eyebrow" style={{ marginBottom: 12 }}>Assign an author to a product</div>
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center" }}>
          <select value={selProd} onChange={(e) => setSelProd(e.target.value)} style={{ ...VH_FIELD, flex: "1 1 220px", background: "#fff" }}>
            <option value="">— Select product —</option>
            {products.map((p) => <option key={p.id} value={p.id}>{p.name}</option>)}
          </select>
          <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="author@vanharen.net"
            onKeyDown={(e) => { if (e.key === "Enter") assign(); }} style={{ ...VH_FIELD, flex: "1 1 220px" }} />
          <button className="btn btn-acc" disabled={busy} style={{ opacity: busy ? .6 : 1, flex: "none" }} onClick={() => assign()}><Icon name="plus" size={15} />Assign author</button>
        </div>
        <div className="dim" style={{ fontSize: 12, marginTop: 9 }}><Icon name="clock" size={12} style={{ verticalAlign: "-2px", marginRight: 4 }} />The author must already have an account (Author portal). Assigning lets them build that product's content.</div>
      </div>

      {/* Products still needing an author */}
      {unassigned.length > 0 && (
        <div className="card" style={{ padding: 20, marginBottom: 20, borderLeft: "3px solid #f59e0b" }}>
          <div className="eyebrow" style={{ marginBottom: 12 }}><Icon name="clock" size={13} style={{ verticalAlign: "-2px", marginRight: 5, color: "#b45309" }} />Products without an author <span style={{ color: "var(--ink-3)", fontWeight: 600, textTransform: "none", letterSpacing: 0 }}>· {unassigned.length}</span></div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {unassigned.map((p) => (
              <button key={p.id} className="btn btn-outline btn-sm" onClick={() => { setSelProd(p.id); const el = document.querySelector("input[type=email]"); if (el) el.focus(); }}
                title={"Assign an author to " + p.name} style={{ fontWeight: 600 }}>
                <Icon name="layers" size={12} />{p.name}<Icon name="plus" size={12} />
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Author directory */}
      <div className="between" style={{ marginBottom: 14 }}>
        <div className="eyebrow">Author directory</div>
        <label className="search" style={{ maxWidth: 280 }}><Icon name="search" size={15} /><input placeholder="Search authors…" value={q} onChange={(e) => setQ(e.target.value)} /></label>
      </div>

      {data === null ? <div className="dim" style={{ fontSize: 13.5, padding: "10px 2px" }}>Loading…</div>
        : shown.length === 0 ? <div className="card" style={{ padding: 24, textAlign: "center" }}>
            <div className="dim" style={{ fontSize: 13.5 }}>{authors.length === 0 ? "No authors yet. Assign one to a product above — they build that product's content." : "No authors match your search."}</div>
          </div>
        : <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 14 }}>
            {shown.map((a) => (
              <div key={a.email} className="card" style={{ padding: 18 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 11, marginBottom: 12 }}>
                  <div style={{ width: 40, height: 40, borderRadius: "50%", flex: "none", background: "var(--vh-blue-500)", color: "#fff", fontSize: 14, fontWeight: 800, display: "grid", placeItems: "center" }}>
                    {(a.name || a.email || "?").split(/[ @.]/).filter(Boolean).slice(0, 2).map((s) => s[0].toUpperCase()).join("")}
                  </div>
                  <div style={{ minWidth: 0, flex: 1 }}>
                    <div style={{ fontWeight: 700, fontSize: 14.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.name || a.email}</div>
                    <div className="dim" style={{ fontSize: 12, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{a.email}</div>
                  </div>
                  <span style={{ fontSize: 10, fontWeight: 800, letterSpacing: ".04em", padding: "2px 8px", borderRadius: 999, flex: "none",
                    background: a.role === "author" ? "#ede7f6" : a.role ? "var(--surface-3)" : "#fff3e0",
                    color: a.role === "author" ? "#5e35b1" : a.role ? "var(--ink-2)" : "#b45309" }}>
                    {a.role ? a.role.toUpperCase() : "NO ACCOUNT"}
                  </span>
                </div>

                <div style={{ display: "flex", gap: 14, marginBottom: 10, fontSize: 12 }}>
                  <span className="dim"><b style={{ color: "var(--ink)" }}>{a.assigned.length}</b> building</span>
                  <span className="dim"><b style={{ color: "var(--ink)" }}>{a.owned.length}</b> owned</span>
                  {a.last_seen && <span className="dim" title="Last in the environment"><Icon name="checkCircle" size={11} style={{ verticalAlign: "-1px", marginRight: 3, color: "#1565c0" }} />{cohFmtDate(a.last_seen)}</span>}
                </div>

                {a.assigned.length > 0 && <div style={{ marginBottom: a.owned.length ? 8 : 0 }}>
                  <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".05em", color: "var(--ink-3)", textTransform: "uppercase", marginBottom: 5 }}>Builds</div>
                  <div style={{ display: "flex", flexDirection: "column", gap: 5 }}>
                    {a.assigned.map((p) => (
                      <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 8, background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 8, padding: "6px 10px" }}>
                        <Icon name="layers" size={13} style={{ color: "var(--vh-blue-500)", flex: "none" }} />
                        <span style={{ flex: 1, fontSize: 12.5, fontWeight: 600, minWidth: 0, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{p.name}</span>
                        <button className="btn btn-ghost btn-sm" style={{ flex: "none", color: "#c62828", padding: "2px 6px" }} title="Remove from this product" onClick={() => unassign(p.id, a.email)}><Icon name="x" size={13} /></button>
                      </div>
                    ))}
                  </div>
                </div>}

                {a.owned.length > 0 && <div>
                  <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".05em", color: "var(--ink-3)", textTransform: "uppercase", marginBottom: 5 }}>Owns</div>
                  <div style={{ display: "flex", flexWrap: "wrap", gap: 5 }}>
                    {a.owned.map((p) => <span key={p.id} className="dim" style={{ fontSize: 11.5, background: "var(--surface-2)", border: "1px solid var(--line)", borderRadius: 7, padding: "3px 8px" }}>{p.name}</span>)}
                  </div>
                </div>}

                {a.assigned.length === 0 && a.owned.length === 0 && <div className="dim" style={{ fontSize: 12 }}>Not assigned to any product yet.</div>}
              </div>
            ))}
          </div>}
    </div>
  );
}
window.AuthorsScreen = AuthorsScreen;
