// Teacher views (re-uses class views) + Analytics page (admin/teacher)
const UT = window.UI;
const AT = UT.A;
const MT = window.MOCK;
const { PageHeader: PHT } = window.Shell;

const TeacherOverview = ({ onNav, onOpenClass, onOpenStudent }) => {
  const myClasses = MT.CLASSES.filter((c) => c.teacher === MT.TEACHER_USER.id);
  const teacherFirstName = (MT.TEACHER_USER.name || "professor").split(" ")[0];
  return (
    <>
      <PHT
        title={`Olá, ${teacherFirstName}.`}
        subtitle="Suas turmas, alunos e o desempenho geral em treinamentos."
      />

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 14,
          marginBottom: 18,
        }}
        className="metric-grid"
      >
        <UT.Glass>
          <UT.Metric
            label="Minhas turmas"
            value={myClasses.length}
            sub={`${myClasses.filter((c) => c.status !== "closed").length} ativas`}
            icon="classes"
          />
        </UT.Glass>
        <UT.Glass>
          <UT.Metric
            label="Alunos sob acompanhamento"
            value="22"
            sub="únicos em todas as turmas"
            icon="users"
          />
        </UT.Glass>
        <UT.Glass>
          <UT.Metric
            label="Sessões nesta semana"
            value="148"
            delta={6}
            icon="session"
            accent={AT.green}
          />
        </UT.Glass>
        <UT.Glass>
          <UT.Metric
            label="Média geral"
            value="87%"
            delta={3}
            sub="suas turmas"
            icon="chart"
            accent={AT.gold}
          />
        </UT.Glass>
      </div>

      <div
        style={{
          display: "grid",
          gridTemplateColumns: "2fr 1fr",
          gap: 16,
          marginBottom: 18,
        }}
        className="two-col"
      >
        <UT.Glass>
          <h3
            style={{
              margin: "0 0 14px",
              fontSize: 15,
              fontWeight: 600,
              color: AT.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Atividade — última semana
          </h3>
          <UT.LineChart
            data={[
              { value: 18 },
              { value: 24 },
              { value: 22 },
              { value: 31 },
              { value: 28 },
              { value: 25 },
              { value: 32 },
            ]}
            height={160}
          />
          <div
            style={{
              display: "flex",
              justifyContent: "space-between",
              marginTop: 8,
              fontSize: 11,
              color: AT.inkMute,
            }}
          >
            {["Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"].map((d) => (
              <span key={d}>{d}</span>
            ))}
          </div>
        </UT.Glass>
        <UT.Glass>
          <h3
            style={{
              margin: "0 0 14px",
              fontSize: 15,
              fontWeight: 600,
              color: AT.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Alunos a observar
          </h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {MT.STUDENTS.filter((s) => s.avgScore < 75)
              .slice(0, 4)
              .map((s) => (
                <div
                  key={s.id}
                  onClick={() => onOpenStudent && onOpenStudent(s.id)}
                  style={{
                    display: "flex",
                    gap: 10,
                    alignItems: "center",
                    padding: "8px 10px",
                    background: "rgba(184,51,31,0.06)",
                    borderLeft: `3px solid ${AT.warn}`,
                    borderRadius: 6,
                    cursor: "pointer",
                  }}
                >
                  <UT.Avatar name={s.name} role="student" size={28} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div
                      style={{
                        fontSize: 13,
                        fontWeight: 500,
                        color: AT.ink,
                        whiteSpace: "nowrap",
                        overflow: "hidden",
                        textOverflow: "ellipsis",
                      }}
                    >
                      {s.name}
                    </div>
                    <div style={{ fontSize: 11, color: AT.inkSoft }}>
                      {s.id} · {s.sessions} sessões · média {s.avgScore}%
                    </div>
                  </div>
                </div>
              ))}
          </div>
        </UT.Glass>
      </div>

      <UT.Glass>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            marginBottom: 14,
          }}
        >
          <h3
            style={{
              margin: 0,
              fontSize: 15,
              fontWeight: 600,
              color: AT.ink,
              fontFamily: '"Plus Jakarta Sans", sans-serif',
            }}
          >
            Minhas turmas ativas
          </h3>
          <UT.Button
            variant="ghost"
            size="sm"
            iconRight="arrow"
            onClick={() => onNav("classes")}
          >
            Ver todas
          </UT.Button>
        </div>
        <div
          style={{
            display: "grid",
            gridTemplateColumns: "repeat(2, 1fr)",
            gap: 14,
          }}
        >
          {myClasses
            .filter((c) => c.status !== "closed")
            .map((c) => (
              <div
                key={c.id}
                onClick={() => onOpenClass(c.id)}
                style={{
                  padding: 14,
                  background: "#f5f7f5",
                  border: "1px solid rgba(0,0,0,0.06)",
                  borderRadius: 10,
                  cursor: "pointer",
                }}
              >
                <div
                  style={{
                    display: "flex",
                    justifyContent: "space-between",
                    marginBottom: 8,
                  }}
                >
                  <UT.Badge tone="primary" size="sm">
                    {c.id}
                  </UT.Badge>
                  {c.status === "closing" && (
                    <UT.Badge tone="gold" size="sm">
                      Encerrando
                    </UT.Badge>
                  )}
                </div>
                <div
                  style={{
                    fontSize: 14,
                    fontWeight: 600,
                    color: AT.ink,
                    marginBottom: 8,
                    fontFamily: '"Plus Jakarta Sans", sans-serif',
                  }}
                >
                  {c.name}
                </div>
                <div
                  style={{
                    display: "flex",
                    gap: 14,
                    fontSize: 12,
                    color: AT.inkSoft,
                  }}
                >
                  <span>{c.students} alunos</span>
                  <span style={{ color: AT.ok, fontWeight: 600 }}>
                    {c.avgScore}% média
                  </span>
                  <span
                    style={{
                      marginLeft: "auto",
                      fontWeight: 600,
                      color: AT.ink,
                    }}
                  >
                    {c.completion}%
                  </span>
                </div>
                <div
                  style={{
                    marginTop: 8,
                    height: 4,
                    background: "rgba(0,0,0,0.06)",
                    borderRadius: 2,
                    overflow: "hidden",
                  }}
                >
                  <div
                    style={{
                      width: `${c.completion}%`,
                      height: "100%",
                      background: AT.green,
                    }}
                  />
                </div>
              </div>
            ))}
        </div>
      </UT.Glass>
    </>
  );
};

const Analytics = ({ role }) => {
  const sessions = MT.SESSIONS || [];
  const byType = MT._byType || [];
  const myClasses = role === "teacher"
    ? MT.CLASSES.filter((c) => c.teacher === MT.TEACHER_USER.id)
    : MT.CLASSES;

  // Aggregate metrics across the sessions in scope (admin: all sessions; teacher: own students')
  const totalFound = sessions.reduce((s, x) => s + (x.found || 0), 0);
  const totalMissed = sessions.reduce((s, x) => s + ((x.missed || 0)), 0);
  const totalMisId = sessions.reduce((s, x) => s + (x.misidentified || 0), 0);
  const totalDefects = totalFound + totalMissed + totalMisId;
  const hitRate = totalDefects > 0 ? Math.round(((totalFound - totalMisId) / totalDefects) * 100) : null;
  const missRate = totalDefects > 0 ? Math.round((totalMissed / totalDefects) * 100) : null;
  const avgCoverage = sessions.length > 0
    ? Math.round(sessions.reduce((s, x) => s + (x.coverage || 0), 0) / sessions.length)
    : null;

  // Score trajectory: average score per "bucket" of recent sessions, oldest first.
  // For ≤ 12 sessions, plot each one. For more, bucket into 12 groups.
  let scoreTrajectory = [];
  if (sessions.length > 0) {
    const ordered = [...sessions].reverse(); // oldest first
    if (ordered.length <= 12) {
      scoreTrajectory = ordered.map((s) => ({ value: s.score }));
    } else {
      const bucketSize = Math.ceil(ordered.length / 12);
      for (let i = 0; i < ordered.length; i += bucketSize) {
        const bucket = ordered.slice(i, i + bucketSize);
        const avg = Math.round(bucket.reduce((s, x) => s + x.score, 0) / bucket.length);
        scoreTrajectory.push({ value: avg });
      }
    }
  }

  const hasData = sessions.length > 0;

  return (
  <>
    <PHT
      title={role === "admin" ? "Analytics Geral" : "Analytics"}
      subtitle={role === "admin"
        ? "Visão consolidada de toda a plataforma — defeitos, cobertura e progressão."
        : "Suas turmas — desempenho consolidado dos seus alunos."}
    />

    {!hasData && (
      <div style={{
        marginBottom: 18, padding: "14px 16px",
        background: "rgba(221,160,3,0.08)",
        border: "1px solid rgba(221,160,3,0.3)",
        borderRadius: 8, fontSize: 13, color: "#7a5a00",
        display: "flex", gap: 10, alignItems: "center",
      }}>
        <UT.Icon name="info" size={18} />
        <div>
          {role === "admin"
            ? "Nenhuma sessão de simulação foi registrada ainda."
            : "Suas turmas ainda não têm sessões registradas. Quando seus alunos começarem a usar o simulador, os dados aparecerão aqui."}
        </div>
      </div>
    )}

    <div
      style={{
        display: "grid",
        gridTemplateColumns: "repeat(4, 1fr)",
        gap: 14,
        marginBottom: 18,
      }}
      className="metric-grid"
    >
      <UT.Glass>
        <UT.Metric
          label="Sessões totais"
          value={String(sessions.length)}
          icon="session"
        />
      </UT.Glass>
      <UT.Glass>
        <UT.Metric
          label="Taxa de acerto"
          value={hitRate !== null ? `${hitRate}%` : "—"}
          icon="check"
          accent={AT.ok}
        />
      </UT.Glass>
      <UT.Glass>
        <UT.Metric
          label="Defeitos perdidos"
          value={missRate !== null ? `${missRate}%` : "—"}
          icon="alert"
          accent={AT.danger}
        />
      </UT.Glass>
      <UT.Glass>
        <UT.Metric label="Cobertura média" value={avgCoverage !== null ? `${avgCoverage}%` : "—"} icon="layers" />
      </UT.Glass>
    </div>

    <div
      style={{
        display: "grid",
        gridTemplateColumns: "2fr 1fr",
        gap: 16,
        marginBottom: 18,
      }}
      className="two-col"
    >
      <UT.Glass>
        <h3
          style={{
            margin: "0 0 14px",
            fontSize: 15,
            fontWeight: 600,
            color: AT.ink,
            fontFamily: '"Plus Jakarta Sans", sans-serif',
          }}
        >
          {role === "admin" ? "Pontuação média — todas as turmas" : "Pontuação média — minhas turmas"}
        </h3>
        {scoreTrajectory.length >= 2 ? (
          <UT.LineChart data={scoreTrajectory} height={200} />
        ) : (
          <div style={{ padding: "60px 8px", textAlign: "center", fontSize: 13, color: AT.inkMute }}>
            {scoreTrajectory.length === 1 ? "Apenas uma sessão registrada — sem trajetória ainda." : "Sem dados para exibir."}
          </div>
        )}
      </UT.Glass>
      <UT.Glass>
        <h3
          style={{
            margin: "0 0 14px",
            fontSize: 15,
            fontWeight: 600,
            color: AT.ink,
            fontFamily: '"Plus Jakarta Sans", sans-serif',
          }}
        >
          Comparação de turmas
        </h3>
        {myClasses.filter((c) => c.status !== "closed").length === 0 ? (
          <div style={{ padding: "20px 8px", textAlign: "center", fontSize: 13, color: AT.inkMute }}>
            Nenhuma turma ativa.
          </div>
        ) : (
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          {myClasses.filter((c) => c.status !== "closed").map((c) => (
            <div key={c.id}>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  fontSize: 12,
                  marginBottom: 5,
                }}
              >
                <span style={{ color: AT.ink, fontWeight: 500 }}>{c.id}</span>
                <span
                  style={{
                    color: AT.ok,
                    fontWeight: 600,
                    fontVariantNumeric: "tabular-nums",
                  }}
                >
                  {c.avgScore || 0}%
                </span>
              </div>
              <div
                style={{
                  height: 6,
                  background: "rgba(0,0,0,0.06)",
                  borderRadius: 4,
                  overflow: "hidden",
                }}
              >
                <div
                  style={{
                    width: `${c.avgScore || 0}%`,
                    height: "100%",
                    background: `linear-gradient(90deg, ${AT.green}, ${AT.greenSoft})`,
                  }}
                />
              </div>
            </div>
          ))}
        </div>
        )}
      </UT.Glass>
    </div>

    <div
      style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}
      className="two-col"
    >
      <UT.Glass>
        <h3
          style={{
            margin: "0 0 14px",
            fontSize: 15,
            fontWeight: 600,
            color: AT.ink,
            fontFamily: '"Plus Jakarta Sans", sans-serif',
          }}
        >
          {role === "admin" ? "Defeitos por tipo (todas as turmas)" : "Defeitos por tipo (minhas turmas)"}
        </h3>
        {byType.length > 0 ? (
          <UT.StackedBar rows={byType} />
        ) : (
          <div style={{ padding: "24px 8px", textAlign: "center", fontSize: 13, color: AT.inkMute }}>
            Sem dados de defeitos ainda.
          </div>
        )}
      </UT.Glass>
      <UT.Glass>
        <h3
          style={{
            margin: "0 0 14px",
            fontSize: 15,
            fontWeight: 600,
            color: AT.ink,
            fontFamily: '"Plus Jakarta Sans", sans-serif',
          }}
        >
          Cobertura por zona — média
        </h3>
        {((MT.SESSION_DETAIL && MT.SESSION_DETAIL.zones) || []).length > 0 ? (
          <UT.StackedBar
            rows={MT.SESSION_DETAIL.zones.map((z) => ({
              type: z.zone,
              found: z.covered,
              misId: 0,
              missed: z.missed,
              total: 100,
            }))}
            showLegend={false}
          />
        ) : (
          <div style={{ padding: "24px 8px", textAlign: "center", fontSize: 13, color: AT.inkMute }}>
            Abra uma sessão de aluno para ver a cobertura por zona.
          </div>
        )}
      </UT.Glass>
    </div>
  </>
  );
};

window.OtherViews = { TeacherOverview, Analytics };
