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

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

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

  const statusPill = (s) =>
    s === "live"      ? <span className="cx-pill tint green">● Live</span>
  : s === "grading"   ? <span className="cx-pill tint blue">Grading</span>
  : s === "published" ? <span className="cx-pill tint blue">Published</span>
  : s === "draft"     ? <span className="cx-pill tint grey">Draft</span>
  :                     <span className="cx-pill tint grey">{CX.title(s)}</span>;

  const ACCESS_DOT = { full: "var(--green-solid)", partial: "var(--amber-solid)", locked: "var(--grey-solid)" };

  return (
    <div className="cx-page">
      <CX.PageHead
        eyebrow="Online tests"
        title="KinetiX Portal"
        actions={
          <button className="cx-btn-dark" onClick={() => setScreen("library")}>
            <CX.Icon name="plus" size={17}/> 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={<span className="cx-pill">Library</span>}
              />
              <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("kinetix-activity")}
                actionLabel="Open activity log"
                footNote={`${CX.num(d.attempts.submitted)} submitted · ${d.attempts.inProgress} in progress · ${CX.num(d.attempts.distinctStudents)} students`}
                action={<span className="cx-pill">Activity</span>}
              />
              <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={<span className="cx-pill">Doubts</span>}
              />
            </div>

            <div className="cx-grid split" style={{ gridTemplateColumns: "1.35fr 1fr" }}>
              <div style={{ display: "flex", flexDirection: "column", gap: 20, minWidth: 0 }}>
                <CX.Card>
                  <div className="cx-card-head">
                    <div className="cx-card-title">Test Library</div>
                    <span className="cx-pill">{CX.num(d.tests.total)} tests</span>
                  </div>
                  {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) => (
                    <div key={t.display_id} className="cx-row">
                      <span style={{
                        fontSize: 12.5, fontWeight: 700, color: "var(--ink-3)", width: 56,
                        fontVariantNumeric: "tabular-nums", flexShrink: 0,
                      }}>{t.display_id}</span>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div className="cx-row-title" style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                          {t.title}
                        </div>
                        <div className="cx-row-sub">
                          {[t.subject, t.class_level && `${t.class_level}${t.section || ""}`,
                            t.scheduled_date && CX.date(t.scheduled_date)].filter(Boolean).join(" · ")}
                        </div>
                      </div>
                      {statusPill(t.status)}
                      <div style={{ width: 110, flexShrink: 0 }}>
                        <div style={{ display: "flex", justifyContent: "space-between", fontSize: 11.5, color: "var(--ink-3)", marginBottom: 4 }}>
                          <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>
                  ))}
                  <div className="cx-card-foot">
                    <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                      {d.tests.published} published · {d.tests.draft} still in draft
                    </span>
                    <button className="cx-pill" onClick={() => setScreen("library")}>Open library</button>
                  </div>
                </CX.Card>

                <CX.Card>
                  <div className="cx-card-head">
                    <div className="cx-card-title">KinetiX Access</div>
                    <span className="cx-pill tint blue">
                      {CX.num(d.access.granted)} of {CX.num(d.access.studentsTotal)} students · {d.access.pct}%
                    </span>
                  </div>
                  {d.access.byClass.length === 0 ? (
                    <CX.Empty icon="shield" title="No classes registered"/>
                  ) : (
                    <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 10 }}>
                      {d.access.byClass.map((c) => (
                        <div key={c.label} className="cx-tile" style={{ display: "flex", flexDirection: "column", gap: 4 }}>
                          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                            <span style={{ fontSize: 15, fontWeight: 700, color: "var(--ink-0)" }}>{c.label}</span>
                            <span style={{ width: 8, height: 8, borderRadius: "50%", background: ACCESS_DOT[c.state] }}/>
                          </div>
                          <div style={{ fontSize: 12, color: "var(--ink-3)" }}>
                            {c.granted}/{c.students} ·{" "}
                            {c.state === "full" ? "full access" : c.state === "partial" ? "partial" : "locked"}
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                  <div className="cx-card-foot">
                    <span style={{ fontSize: 13, color: "var(--ink-3)" }}>
                      Access is granted per student and gates the learning portal
                    </span>
                    <button className="cx-pill" onClick={() => setScreen("kinetix-access")}>Manage access</button>
                  </div>
                </CX.Card>
              </div>

              <CX.Card style={{ display: "flex", flexDirection: "column" }}>
                <div className="cx-card-head" style={{ marginBottom: 6 }}>
                  <div className="cx-card-title">Recent Activity</div>
                  {state.refreshing
                    ? <span className="cx-pill tint blue">Refreshing…</span>
                    : <span className="cx-pill tint green">● Live</span>}
                </div>
                <div style={{ display: "flex", flexDirection: "column", 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} style={{
                        display: "flex", gap: 12, padding: "12px 0",
                        borderBottom: "1px solid var(--line-soft)", alignItems: "flex-start",
                      }}>
                        <span className="cx-dot" style={{ background: color, boxShadow: `0 0 0 4px ${color}22` }}/>
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{ fontSize: 14, color: "var(--ink-0)" }}>
                            <strong>{f.student_name}</strong> {done ? "submitted" : "started"}{" "}
                            <span style={{ color: "var(--ink-2)" }}>{f.test_title}</span>
                          </div>
                          <div className="cx-row-sub" style={{ marginTop: 2 }}>
                            {[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" }}>
                          {CX.relTime(f.submitted_at || f.started_at)}
                        </span>
                      </div>
                    );
                  })}
                </div>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", paddingTop: 14, gap: 10 }}>
                  <span style={{ fontSize: 13, color: "var(--ink-3)" }}>Auditable session log</span>
                  <button className="cx-pill" onClick={() => setScreen("kinetix-activity")}>Full log</button>
                </div>
              </CX.Card>
            </div>
          </>
        )}
      </CX.Screen>
    </div>
  );
};

window.CockpitKinetix = KinetixOverviewScreen;
