/* ==================================================================
   Admin → Announcements
   ------------------------------------------------------------------
   Authoring surface for school-wide announcements that flow to the
   parent app (Adarshabani Parent). Class-specific announcements can
   be authored here too, or by teachers from their mobile app.

   Composer + history list. Soft-delete on the trash button (sets
   deleted_at; the row stays for audit).
   ================================================================== */

const { Icon: AnnIcon } = window.KXUI;

const AdminAnnouncementsScreen = () => {
  const [rows, setRows]               = React.useState([]);
  const [classSections, setSections]  = React.useState([]);
  const [loading, setLoading]         = React.useState(true);
  const [err, setErr]                 = React.useState(null);

  const [scope, setScope]             = React.useState("school");
  const [classSectionId, setCsId]     = React.useState("");
  const [title, setTitle]             = React.useState("");
  const [body, setBody]               = React.useState("");
  const [pinned, setPinned]           = React.useState(false);
  const [busy, setBusy]               = React.useState(false);
  const [flash, setFlash]             = React.useState(null);

  const load = React.useCallback(async () => {
    setLoading(true); setErr(null);
    try {
      setRows(await window.KXApi.get("/admin/announcements"));
    } catch (e) {
      setErr(String(e.message || e));
    } finally {
      setLoading(false);
    }
  }, []);
  React.useEffect(() => { load(); }, [load]);
  React.useEffect(() => {
    window.KXApi.get("/admin/class-sections").then(setSections).catch(() => {});
  }, []);

  const reset = () => { setTitle(""); setBody(""); setPinned(false); };

  const publish = async (e) => {
    e.preventDefault();
    if (!title.trim() || !body.trim()) { window.alert("Title and body are required."); return; }
    if (scope !== "school" && !classSectionId) { window.alert("Pick a class."); return; }
    setBusy(true); setFlash(null);
    try {
      // pinned_until = +7 days when toggled on
      const pinned_until = pinned ? new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString() : null;
      await window.KXApi.post("/admin/announcements", {
        scope, title: title.trim(), body: body.trim(),
        class_section_id: scope === "school" ? null : classSectionId,
        pinned_until,
      });
      setFlash("Published.");
      reset();
      await load();
    } catch (e) {
      window.alert("Could not publish: " + (e.message || e));
    } finally {
      setBusy(false);
    }
  };

  const remove = async (id, t) => {
    if (!window.confirm(`Delete announcement "${t}"? Parents will stop seeing it.`)) return;
    try {
      await window.KXApi.del(`/admin/announcements/${id}`);
      await load();
    } catch (e) {
      window.alert("Could not delete: " + (e.message || e));
    }
  };

  const sectionLabel = (cs) => `${cs.label}${cs.academic_year ? ` · ${cs.academic_year}` : ""}`;
  const fmt = (iso) => new Date(iso).toLocaleString(undefined, {
    month: "short", day: "numeric", hour: "2-digit", minute: "2-digit",
  });

  return (
    <div style={{ overflow: "auto", padding: "24px 28px", height: "100%" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 4 }}>
        <span style={{ color: "var(--accent)" }}><AnnIcon name="inbox" size={18}/></span>
        <div className="muted" style={{ fontSize: 11, letterSpacing: ".08em", textTransform: "uppercase" }}>Admin · Announcements</div>
      </div>
      <h1 style={{ margin: "4px 0 6px", color: "var(--ink-0)", fontFamily: "'Instrument Serif', serif", fontWeight: 400, fontSize: 32, letterSpacing: "-0.01em" }}>
        Announcements
      </h1>
      <p className="muted" style={{ margin: 0, fontSize: 13.5, maxWidth: 720 }}>
        Author school-wide announcements that reach every approved parent. For class-specific
        notices, teachers can also write from the teacher app — both flow to the same parent feed.
      </p>

      {err && (
        <div style={{ marginTop: 16, padding: "10px 14px", background: "rgba(225, 80, 80, 0.08)",
                     border: "1px solid var(--red)", borderRadius: 8, color: "var(--ink-0)", fontSize: 13 }}>
          {err}
        </div>
      )}

      {/* Composer */}
      <form onSubmit={publish} className="card" style={{ marginTop: 18 }}>
        <div className="card-head"><span className="card-title">New announcement</span></div>
        <div className="card-body" style={{ padding: 16 }}>
          <div style={{ display: "flex", gap: 12, alignItems: "center", marginBottom: 12 }}>
            <label style={{ fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: ".06em" }}>Scope</label>
            <select className="input" value={scope}
              onChange={e => setScope(e.target.value)}
              style={{ padding: "5px 8px", fontSize: 12.5 }}>
              <option value="school">School-wide</option>
              <option value="class">Class-specific</option>
            </select>
            {scope !== "school" && (
              <select className="input" value={classSectionId}
                onChange={e => setCsId(e.target.value)}
                style={{ padding: "5px 8px", fontSize: 12.5, minWidth: 220 }}>
                <option value="">Pick a class…</option>
                {classSections.map(cs => (
                  <option key={cs.id} value={cs.id}>{sectionLabel(cs)}</option>
                ))}
              </select>
            )}
            <label style={{ marginLeft: "auto", display: "flex", gap: 6, alignItems: "center", fontSize: 12.5, color: "var(--ink-1)" }}>
              <input type="checkbox" checked={pinned} onChange={e => setPinned(e.target.checked)} />
              Pin for 7 days
            </label>
          </div>

          <input className="input" value={title}
            onChange={e => setTitle(e.target.value)}
            placeholder="Title — e.g. Annual Day Registration Deadline"
            style={{ width: "100%", padding: "8px 10px", fontSize: 14, marginBottom: 10 }} />

          <textarea className="input" value={body}
            onChange={e => setBody(e.target.value)}
            placeholder="Body — include dates, contact, sign-up links…"
            rows={5}
            style={{ width: "100%", padding: "8px 10px", fontSize: 13, lineHeight: 1.5 }} />

          <div style={{ display: "flex", gap: 10, marginTop: 12, alignItems: "center" }}>
            <button type="submit" className="btn sm primary" disabled={busy}>
              <AnnIcon name="sparkle" size={11}/> {busy ? "Publishing…" : "Publish"}
            </button>
            {flash && <span className="muted" style={{ fontSize: 12, color: "var(--green)" }}>{flash}</span>}
          </div>
        </div>
      </form>

      {/* History */}
      <div className="card" style={{ marginTop: 18 }}>
        <div className="card-head" style={{ gap: 10 }}>
          <span className="card-title">Published</span>
          <button className="btn ghost sm" onClick={load} disabled={loading} style={{ marginLeft: "auto" }}>
            Refresh
          </button>
        </div>
        <div className="card-body" style={{ padding: 0 }}>
          {loading && <div style={{ padding: 20, color: "var(--ink-3)", fontSize: 12 }}>Loading…</div>}
          {!loading && rows.length === 0 && (
            <div style={{ padding: 28, textAlign: "center", color: "var(--ink-3)", fontSize: 13 }}>
              No announcements published yet.
            </div>
          )}
          {rows.map(r => (
            <div key={r.id} style={{
              padding: "12px 16px", borderBottom: "1px solid var(--line-soft)",
              display: "grid", gridTemplateColumns: "1fr 100px auto", gap: 12, alignItems: "start",
            }}>
              <div>
                <div style={{ color: "var(--ink-0)", fontSize: 13.5, fontWeight: 500 }}>{r.title}</div>
                <div className="muted" style={{ fontSize: 11.5, marginTop: 2, lineHeight: 1.5 }}>
                  {r.body.length > 200 ? r.body.slice(0, 200) + "…" : r.body}
                </div>
                <div className="muted" style={{ fontSize: 11, marginTop: 6 }}>
                  by {r.author_name} ({r.author_role}) · {fmt(r.published_at)}
                  {r.pinned_until && new Date(r.pinned_until) > new Date() && (
                    <> · <span style={{ color: "var(--accent)" }}>📌 pinned</span></>
                  )}
                </div>
              </div>
              <div style={{
                fontSize: 10, color: "var(--ink-2)",
                border: "1px solid var(--line)", borderRadius: 4, padding: "1px 6px",
                textAlign: "center", textTransform: "uppercase", letterSpacing: ".06em",
              }}>
                {r.scope === "school" ? "school-wide" : `${r.audience_count} class${r.audience_count === 1 ? "" : "es"}`}
              </div>
              <button className="btn ghost sm" onClick={() => remove(r.id, r.title)}
                title="Soft-delete this announcement">
                <AnnIcon name="trash" size={11}/>
              </button>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

window.AdminAnnouncementsScreen = AdminAnnouncementsScreen;
