/* ==================================================================
   Admin Cockpit → Parents
   ------------------------------------------------------------------
   The parent portal seen from the office: account state, how much of the
   student roll is actually covered by a linked parent, the teacher-chat
   backlog, and how far announcements are reaching.

   Reads /admin/cockpit/parents. "Announcement reach" is delivered vs read
   from parent_notifications — if nothing was ever delivered the card says
   so rather than reporting 0%, which would read as "nobody opened it".
   ================================================================== */

const ParentsOverviewScreen = ({ setScreen }) => {
  const CX = window.CX;
  const state = CX.useCockpitData("/admin/cockpit/parents", { pollMs: 120000 });
  const d = state.data;

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Parent portal · connect"
        title="Parents"
        actions={
          <button className="cx-btn-dark" onClick={() => setScreen("announcements")}>
            <CX.Icon name="plus" size={17}/> Broadcast announcement
          </button>
        }
      />

      <CX.Screen state={state}>
        {d && (
          <>
            <div className="cx-grid cols-3" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 20 }}>
              <CX.StatCard
                icon="users" color="var(--green-solid)" label="Registered Parents"
                value={CX.num(d.parents.total)}
                delta={d.parents.new30d ? `↑ ${d.parents.new30d} in 30 days` : null}
                deltaTone="up"
                onAction={() => setScreen("parents")}
                actionLabel="Open parent accounts"
                footNote={
                  `${d.coverage.studentsCovered} of ${CX.num(d.coverage.studentsTotal)} students linked · ` +
                  `${d.coverage.coveragePct}%`
                }
                action={<span className="cx-pill">Accounts</span>}
              />
              <CX.StatCard
                icon="alert" color="var(--amber-solid)" label="Pending Approvals"
                value={CX.num(d.parents.pending)}
                delta={d.parents.oldestPending ? `oldest ${CX.relTime(d.parents.oldestPending)}` : null}
                deltaTone="warn"
                onAction={() => setScreen("parents")}
                actionLabel="Review sign-ups"
                footNote={d.parents.pending ? "Sign-ups awaiting activation" : "Nothing waiting for review"}
                action={d.parents.pending
                  ? <button className="cx-pill dark" onClick={() => setScreen("parents")}>Approve</button>
                  : <span className="cx-pill tint green">Clear</span>}
              />
              <CX.StatCard
                icon="chat" color="var(--blue-solid)" label="Chat Threads"
                value={CX.num(d.chats.threads)}
                delta={d.chats.unanswered ? `${d.chats.unanswered} awaiting a reply` : null}
                deltaTone="down"
                footNote={`${d.chats.active7d} active in the last 7 days`}
                action={<span className="cx-pill">Threads</span>}
              />
            </div>

            <div className="cx-grid split" style={{ gridTemplateColumns: "1.2fr 1fr" }}>
              <CX.Card>
                <div className="cx-card-head">
                  <div className="cx-card-title">Teacher ↔ Parent Threads</div>
                  <span className="cx-pill">Most recent</span>
                </div>
                {d.chats.list.length === 0 ? (
                  <CX.Empty icon="chat" title="No conversations yet"
                            hint="Threads started in the parent app appear here."/>
                ) : d.chats.list.map((c) => (
                  <div key={c.id} className="cx-row" style={{ alignItems: "flex-start" }}>
                    <span className="cx-dot" style={{
                      background: c.unread_from_parent ? "var(--amber-solid)" : "var(--green-solid)",
                      boxShadow: `0 0 0 4px ${c.unread_from_parent ? "rgba(255,159,10,0.18)" : "rgba(47,190,95,0.18)"}`,
                    }}/>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, color: "var(--ink-0)" }}>
                        <strong>{c.parent_name || "Parent"}</strong>
                        {c.teacher_name ? <> ↔ {c.teacher_name}</> : null}
                        {c.student_name ? <span style={{ color: "var(--ink-3)" }}> · about {c.student_name}</span> : null}
                      </div>
                      <div className="cx-row-sub" style={{ marginTop: 2, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {c.last_body ? `${c.last_sender === "parent" ? "Parent" : "Teacher"}: ${c.last_body}` : "No messages yet"}
                      </div>
                    </div>
                    <div style={{ textAlign: "right", flexShrink: 0 }}>
                      {c.unread_from_parent > 0 && (
                        <span className="cx-pill tint amber">{c.unread_from_parent} unread</span>
                      )}
                      <div style={{ fontSize: 12, color: "var(--ink-3)", marginTop: 4 }}>
                        {c.last_message_at ? CX.relTime(c.last_message_at) : "—"}
                      </div>
                    </div>
                  </div>
                ))}
                <div className="cx-card-foot">
                  <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    {d.parents.active7d} parent{d.parents.active7d === 1 ? "" : "s"} signed in this week ·{" "}
                    {d.parents.pushEnabled} with push enabled
                  </span>
                </div>
              </CX.Card>

              <CX.Card>
                <div className="cx-card-head">
                  <div className="cx-card-title">Announcement Reach</div>
                  <span className="cx-pill">Read rate</span>
                </div>

                {d.announcements.length === 0 ? (
                  <CX.Empty icon="bell" title="No announcements published"
                            hint="Broadcast one to reach every linked parent."/>
                ) : (
                  <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                    {d.announcements.map((a, i) => {
                      const colors = ["var(--green-solid)", "var(--blue-solid)", "var(--pink-solid)",
                                      "var(--amber-solid)", "var(--violet-solid)"];
                      return (
                        <div key={a.id}>
                          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, marginBottom: 7, gap: 12 }}>
                            <span style={{ fontWeight: 600, color: "var(--ink-0)", minWidth: 0,
                                           whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                              {a.title}
                            </span>
                            <span style={{ color: "var(--ink-3)", whiteSpace: "nowrap" }}>
                              {a.delivered === 0
                                ? "not delivered"
                                : <><strong style={{ color: "var(--ink-0)" }}>{a.readPct}%</strong> · {a.read}/{a.delivered} read</>}
                            </span>
                          </div>
                          {/* An undelivered notice gets an empty track, not a
                              0% bar — the distinction is the whole point. */}
                          <CX.Meter pct={a.delivered === 0 ? 0 : a.readPct} color={colors[i % colors.length]}/>
                        </div>
                      );
                    })}
                  </div>
                )}

                {d.announcements.some((a) => a.delivered === 0) && (
                  <div className="cx-note" style={{ marginTop: 18 }}>
                    <div className="cx-note-mark"><CX.Icon name="bell" size={18}/></div>
                    <div>
                      Some notices have no delivery records. A notice only reaches a parent
                      once their account is approved and linked to a student — currently{" "}
                      {d.coverage.coveragePct}% of the roll.
                    </div>
                  </div>
                )}

                <div className="cx-card-foot">
                  <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                    {d.coverage.verified} of {d.coverage.links} parent–student links verified
                  </span>
                  <button className="cx-pill" onClick={() => setScreen("announcements")}>All notices</button>
                </div>
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitParents = ParentsOverviewScreen;
