/* ==================================================================
   Overview → 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;

  const PaBadge = window.AppUI.StatusBadge;

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Parent portal · connect"
        title="Parents"
        actions={
          <button type="button" className="btn primary" onClick={() => setScreen("announcements")}>
            <CX.Icon name="plus" size={15}/> 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={<CX.Tag>Accounts</CX.Tag>}
              />
              <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 type="button" className="btn primary sm" onClick={() => setScreen("parents")}>Approve</button>
                  : <PaBadge tone="green">Clear</PaBadge>}
              />
              <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={<CX.Tag>Threads</CX.Tag>}
              />
            </div>

            <div className="cx-grid split" style={{ gridTemplateColumns: "1.2fr 1fr" }}>
              <CX.Card>
                <CX.CardHead title="Teacher ↔ parent threads" right={<CX.Tag>Most recent</CX.Tag>}/>
                <div className="ui-list">
                  {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="ui-row" style={{ alignItems: "flex-start" }}>
                      <span style={{ position: "relative", flexShrink: 0 }}>
                        <window.AppUI.Avatar name={c.parent_name || "Parent"}/>
                        <span title={c.unread_from_parent ? "Unread from parent" : "Up to date"} style={{
                          position: "absolute", right: -1, bottom: -1, width: 10, height: 10, borderRadius: "50%",
                          border: "2px solid var(--surface)",
                          background: c.unread_from_parent ? "var(--amber-solid)" : "var(--green-solid)",
                        }}/>
                      </span>
                      <div className="ui-row-main">
                        <div className="ui-row-title">
                          {c.parent_name || "Parent"}
                          {c.teacher_name ? <span style={{ color: "var(--ink-2)", fontWeight: 400 }}> ↔ {c.teacher_name}</span> : null}
                          {c.student_name ? <span style={{ color: "var(--ink-3)", fontWeight: 400 }}> · about {c.student_name}</span> : null}
                        </div>
                        <div className="ui-row-sub">
                          {c.last_body ? `${c.last_sender === "parent" ? "Parent" : "Teacher"}: ${c.last_body}` : "No messages yet"}
                        </div>
                      </div>
                      <div style={{ textAlign: "right", flexShrink: 0, display: "flex", flexDirection: "column", alignItems: "flex-end", gap: 4 }}>
                        {c.unread_from_parent > 0 && (
                          <PaBadge tone="amber" variant="solid">{c.unread_from_parent} unread</PaBadge>
                        )}
                        <div style={{ fontSize: 12, color: "var(--ink-3)", fontVariantNumeric: "tabular-nums" }}>
                          {c.last_message_at ? CX.relTime(c.last_message_at) : "—"}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                <CX.CardFoot note={
                  `${d.parents.active7d} parent${d.parents.active7d === 1 ? "" : "s"} signed in this week · `
                  + `${d.parents.pushEnabled} with push enabled`
                }/>
              </CX.Card>

              <CX.Card>
                <CX.CardHead title="Announcement reach" right={<CX.Tag>Read rate</CX.Tag>}/>

                {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: 500, color: "var(--ink-0)", minWidth: 0,
                                           whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                              {a.title}
                            </span>
                            <span style={{ color: "var(--ink-3)", whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>
                              {a.delivered === 0
                                ? "not delivered"
                                : <><strong style={{ color: "var(--ink-0)", fontWeight: 600 }}>{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={16}/></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>
                )}

                <CX.CardFoot
                  note={`${d.coverage.verified} of ${d.coverage.links} parent–student links verified`}
                  action="All notices" onAction={() => setScreen("announcements")}
                />
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitParents = ParentsOverviewScreen;
