/* ==================================================================
   Assessment → Overview
   ------------------------------------------------------------------
   The online-test platform from the office's point of view: what is live,
   what has been attempted, how the marks are landing, and a genuine
   recent-activity column.

   Reads the backend cockpit assessment summary. The "Live Activity" panel is real attempt
   rows ordered by time — deliberately NOT a synthetic ticker. A quiet
   school shows a quiet panel.
   ================================================================== */

const AssessmentOverviewScreen = ({ setScreen }) => {
  const CX = window.CX;
  const state = CX.useCockpitData("/admin/cockpit/assessments", { pollMs: 45000 });
  const d = state.data;

  const AsBadge = window.AppUI.StatusBadge;
  const statusPill = (s) =>
    s === "live"      ? <AsBadge tone="green" variant="solid">Live</AsBadge>
  : s === "grading"   ? <AsBadge tone="blue">Grading</AsBadge>
  : s === "published" ? <AsBadge tone="blue">Published</AsBadge>
  : s === "draft"     ? <AsBadge tone="grey">Draft</AsBadge>
  :                     <AsBadge tone="grey">{CX.title(s)}</AsBadge>;

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Online tests"
        title="Assessment"
        actions={
          <button type="button" className="btn primary" onClick={() => setScreen("library")}>
            <CX.Icon name="plus" size={15}/> New test
          </button>
        }
      />

      <CX.Screen state={state}>
        {d && (
          <>
            <div className="cx-grid cols-3" style={{ gridTemplateColumns: "repeat(3,1fr)", marginBottom: 20 }}>
              <CX.StatCard
                icon="bolt" color="var(--green-solid)" label="Tests live now"
                value={CX.num(d.tests.live)}
                delta={d.attempts.inProgress ? `● ${d.attempts.inProgress} in progress` : null}
                deltaTone="up"
                onAction={() => setScreen("library")}
                actionLabel="Open test library"
                footNote={`${CX.num(d.tests.total)} in library · ${d.tests.draft} draft · ${d.tests.today} scheduled today`}
                action={<CX.Tag>Library</CX.Tag>}
              />
              <CX.StatCard
                icon="pulse" color="var(--blue-solid)" label="Attempts recorded"
                value={CX.num(d.attempts.total)}
                delta={d.attempts.today ? `${d.attempts.today} submitted today` : null}
                deltaTone="flat"
                onAction={() => setScreen("online-tests")}
                actionLabel="Open online tests"
                footNote={`${CX.num(d.attempts.submitted)} submitted · ${d.attempts.inProgress} in progress · ${CX.num(d.attempts.distinctStudents)} students`}
                action={<CX.Tag>Online</CX.Tag>}
              />
              <CX.StatCard
                icon="smile" color="var(--pink-solid)" label="Average score"
                value={d.scores.avgPct != null ? `${d.scores.avgPct}%` : "—"}
                delta={d.scores.avgPct7d != null ? `${d.scores.avgPct7d}% last 7 days` : null}
                deltaTone={
                  d.scores.avgPct7d != null && d.scores.avgPct != null
                    ? (d.scores.avgPct7d >= d.scores.avgPct ? "up" : "down") : "flat"
                }
                onAction={() => setScreen("doubts")}
                actionLabel="Open doubts"
                footNote={
                  d.scores.graded
                    ? `across ${CX.num(d.scores.graded)} graded attempts · ${d.doubts.open} doubt(s) open`
                    : "no graded attempts yet"
                }
                action={<CX.Tag>Doubts</CX.Tag>}
              />
            </div>

            <div className="cx-grid split" style={{ gridTemplateColumns: "1.35fr 1fr" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 20, minWidth: 0 }}>
                <CX.Card>
                  <CX.CardHead title="Test library" right={<CX.Tag>{CX.num(d.tests.total)} tests</CX.Tag>}/>
                  <div className="ui-list">
                    {d.tests.list.length === 0 ? (
                      <CX.Empty icon="file" title="No tests yet" hint="Create one from the Test Library."/>
                    ) : d.tests.list.map((t) => (
                      <window.AppUI.ListRow
                        key={t.display_id}
                        leading={<span className="ui-id" style={{ width: 56, flexShrink: 0 }}>{t.display_id}</span>}
                        title={t.title}
                        sub={[t.subject, t.class_level && `${t.class_level}${t.section || ""}`,
                          t.scheduled_date && CX.date(t.scheduled_date)].filter(Boolean).join(" · ")}
                        status={statusPill(t.status)}
                        trailing={
                          <div style={{ width: 110, flexShrink: 0 }}>
                            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, color: "var(--ink-3)", marginBottom: 4, fontVariantNumeric: "tabular-nums" }}>
                              <span>{t.submitted}/{t.enrolled || t.attempts || 0}</span>
                              <span>{t.progressPct}%</span>
                            </div>
                            <CX.Meter className="xthin" pct={t.progressPct}
                                      color={t.status === "live" ? "var(--green-solid)" : "var(--blue-solid)"}/>
                          </div>
                        }
                      />
                    ))}
                  </div>
                  <CX.CardFoot
                    note={`${d.tests.published} published · ${d.tests.draft} still in draft`}
                    action="Open library" onAction={() => setScreen("library")}
                  />
                </CX.Card>
              </div>

              <CX.Card style={{ display: "flex", flexDirection: "column" }}>
                <CX.CardHead
                  title="Recent activity"
                  style={{ marginBottom: 6 }}
                  right={state.refreshing
                    ? <AsBadge tone="blue" variant="outline">Refreshing…</AsBadge>
                    : <AsBadge tone="green" variant="outline">Live</AsBadge>}
                />
                <div className="ui-list" style={{ flex: 1 }}>
                  {d.feed.length === 0 && (
                    <CX.Empty icon="pulse" title="No attempts recorded"
                              hint="Student activity on live tests shows up here."/>
                  )}
                  {d.feed.map((f, i) => {
                    const done = !!f.submitted_at;
                    const color = done ? "var(--blue-solid)" : "var(--green-solid)";
                    const score = done && f.max_marks
                      ? ` · ${Math.round((Number(f.auto_score) / Number(f.max_marks)) * 100)}%`
                      : "";
                    return (
                      <div key={i} className="ui-row" style={{ alignItems: "flex-start" }}>
                        <span className="cx-dot" style={{ background: color, boxShadow: `0 0 0 3px color-mix(in srgb, ${color} 15%, transparent)` }}/>
                        <div className="ui-row-main">
                          <div style={{ fontSize: 13.5, color: "var(--ink-0)", lineHeight: 1.4 }}>
                            <span style={{ fontWeight: 500 }}>{f.student_name}</span>{" "}
                            <span style={{ color: "var(--ink-3)" }}>{done ? "submitted" : "started"}</span>{" "}
                            <span style={{ color: "var(--ink-1)" }}>{f.test_title}</span>
                          </div>
                          <div className="ui-row-sub">
                            {[f.class_level && `${f.class_level}${f.section || ""}`, f.display_id]
                              .filter(Boolean).join(" · ")}{score}
                          </div>
                        </div>
                        <span style={{ fontSize: 12, color: "var(--ink-3)", whiteSpace: "nowrap", fontVariantNumeric: "tabular-nums" }}>
                          {CX.relTime(f.submitted_at || f.started_at)}
                        </span>
                      </div>
                    );
                  })}
                </div>
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitAssessment = AssessmentOverviewScreen;
