/* 各角色畫面 — screens.jsx */
const { useState, useMemo } = React;
const {
  Icon, Card, StatCard, TypeBadge, ScoreChip, RiskLight, Button,
  SectionTitle, FilterChip, Avatar, DistBar, TrendLine
} = window;

const D = window.APPDATA;
const fmtDate = (s) => s.slice(5).replace("-", "/");
const TODAY = "2026-05-31";

/* 把成績依日期排序 */
function byDate(a, b) { return a.date < b.date ? -1 : a.date > b.date ? 1 : 0; }

/* ============================================================
   我的成績（學生 / 小老師）
   ============================================================ */
function MyGradesScreen({ studentId, grades }) {
  const [typeFilter, setTypeFilter] = useState("全部");
  const student = D.students.find(s => s.id === studentId);
  const myGrades = useMemo(
    () => grades.filter(g => g.studentId === studentId).slice().sort(byDate),
    [grades, studentId]
  );
  const stats = useMemo(() => {
    const sc = myGrades.map(g => g.score);
    return {
      count: sc.length,
      average: sc.length ? +(sc.reduce((a, b) => a + b, 0) / sc.length).toFixed(1) : 0,
      highest: sc.length ? Math.max(...sc) : 0,
      passRate: sc.length ? Math.round(sc.filter(s => s >= 60).length / sc.length * 100) : 0
    };
  }, [myGrades]);
  const risk = useMemo(() => D.riskFor(studentId, grades), [grades, studentId]);

  const types = ["全部", ...D.assessmentTypes];
  const shown = typeFilter === "全部" ? myGrades : myGrades.filter(g => g.type === typeFilter);

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="hello">嗨，{student.name} 👋</div>
          <div className="page-sub">這是你目前的數學科平時成績，只有你看得到。</div>
        </div>
      </div>

      <div className="grid-4">
        <StatCard label="平均分數" value={stats.average} icon="chart" tone="accent"
          hint={"班級平均 " + D.classStats(grades).average} />
        <StatCard label="最高分" value={stats.highest} icon="award" tone="good" />
        <StatCard label="評量次數" value={stats.count} icon="calendar" suffix=" 次" />
        <StatCard label="及格率" value={stats.passRate} suffix="%" icon="check"
          tone={stats.passRate >= 80 ? "good" : stats.passRate >= 60 ? "warn" : "fail"} />
      </div>

      {/* AI 風險卡 */}
      {risk && (
        <Card className={"risk-card risk-bg-" + risk.level}>
          <div className="risk-head">
            <span className="risk-chip"><Icon name="spark" size={15} /> AI 期末預測</span>
            <span className={"risk-status risk-" + risk.level}>
              <RiskLight level={risk.level} /> {risk.headline}
            </span>
          </div>
          <div className="risk-body">
            <div className="risk-pred">
              <div className="risk-pred-num">{risk.predicted}<span>分</span></div>
              <div className="risk-pred-lbl">預估期末平均</div>
            </div>
            <p className="risk-advice">{risk.advice}</p>
          </div>
        </Card>
      )}

      {/* 明細 */}
      <Card>
        <SectionTitle icon="chart" right={
          <div className="chip-row">
            {types.map(t => (
              <FilterChip key={t} active={typeFilter === t} onClick={() => setTypeFilter(t)}>{t}</FilterChip>
            ))}
          </div>
        }>成績明細</SectionTitle>

        <div className="table">
          <div className="tr th">
            <div className="td col-date">日期</div>
            <div className="td col-type">類型</div>
            <div className="td col-title">評量項目</div>
            <div className="td col-score">得分</div>
          </div>
          {shown.slice().reverse().map(g => (
            <div className="tr" key={g.id}>
              <div className="td col-date mono">{fmtDate(g.date)}</div>
              <div className="td col-type"><TypeBadge type={g.type} /></div>
              <div className="td col-title">{g.title}</div>
              <div className="td col-score"><ScoreChip score={g.score} /></div>
            </div>
          ))}
          {!shown.length && <div className="empty">此類型尚無成績。</div>}
        </div>
      </Card>
    </div>
  );
}

/* ============================================================
   輸入成績（老師 / 小老師）
   ============================================================ */
function InputGradesScreen({ grades, addGrade, deleteGrade, types, addType, currentUser }) {
  const [form, setForm] = useState({
    studentId: D.students[0].id, type: D.assessmentTypes[0],
    title: "", score: "", date: TODAY
  });
  const [adding, setAdding] = useState(false);
  const [newType, setNewType] = useState("");
  const [toast, setToast] = useState(null);

  const sessionRecords = useMemo(
    () => grades.filter(g => g.addedThisSession).slice().reverse(),
    [grades]
  );

  function set(k, v) { setForm(f => ({ ...f, [k]: v })); }

  function submit() {
    const sc = parseInt(form.score, 10);
    if (!form.title.trim()) return flash("請輸入評量項目名稱", "warn");
    if (isNaN(sc) || sc < 0 || sc > 100) return flash("得分需介於 0–100", "warn");
    const st = D.students.find(s => s.id === form.studentId);
    addGrade({
      id: "n" + Date.now(),
      studentId: form.studentId, type: form.type,
      title: form.title.trim(), score: sc, date: form.date,
      addedThisSession: true, by: currentUser.name
    });
    flash(st.name + "・" + form.title.trim() + " " + sc + " 分 已新增", "good");
    setForm(f => ({ ...f, title: "", score: "" }));
  }
  function flash(msg, tone) { setToast({ msg, tone }); setTimeout(() => setToast(null), 2400); }

  function confirmType() {
    const t = newType.trim();
    if (t && !types.includes(t)) { addType(t); set("type", t); }
    setNewType(""); setAdding(false);
  }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="hello">輸入成績</div>
          <div className="page-sub">
            {currentUser.role === "assistant"
              ? "小老師：可為班上任何同學登記成績。"
              : "選擇學生與評量項目，登記平時成績。"}
          </div>
        </div>
      </div>

      <div className="input-layout">
        {/* 表單 */}
        <Card>
          <SectionTitle icon="pencil">登記新成績</SectionTitle>
          <div className="form">
            <label className="field">
              <span className="field-label">學生</span>
              <div className="select-wrap">
                <select value={form.studentId} onChange={e => set("studentId", e.target.value)}>
                  {D.students.map(s => (
                    <option key={s.id} value={s.id}>{String(s.seat).padStart(2, "0")}・{s.name}</option>
                  ))}
                </select>
                <Icon name="chevron" size={16} />
              </div>
            </label>

            <div className="field">
              <span className="field-label">評量類型</span>
              <div className="chip-row wrap">
                {types.map(t => (
                  <FilterChip key={t} active={form.type === t} onClick={() => set("type", t)}>{t}</FilterChip>
                ))}
                {adding ? (
                  <span className="newtype">
                    <input autoFocus value={newType} placeholder="自訂類型"
                      onChange={e => setNewType(e.target.value)}
                      onKeyDown={e => e.key === "Enter" && confirmType()} />
                    <button className="newtype-ok" onClick={confirmType}><Icon name="check" size={14} /></button>
                  </span>
                ) : (
                  <button className="filter-chip ghost" onClick={() => setAdding(true)}>
                    <Icon name="plus" size={14} /> 自訂
                  </button>
                )}
              </div>
            </div>

            <label className="field">
              <span className="field-label">評量項目名稱</span>
              <input className="text-input" value={form.title} placeholder="例：第 5 次小考・統計圖表"
                onChange={e => set("title", e.target.value)} />
            </label>

            <div className="field-row">
              <label className="field">
                <span className="field-label">得分（0–100）</span>
                <input className="text-input" type="number" min="0" max="100" value={form.score}
                  placeholder="0–100" onChange={e => set("score", e.target.value)} />
              </label>
              <label className="field">
                <span className="field-label">日期</span>
                <input className="text-input" type="date" value={form.date}
                  onChange={e => set("date", e.target.value)} />
              </label>
            </div>

            <Button full icon="plus" onClick={submit}>新增成績</Button>
          </div>
        </Card>

        {/* 本次新增 */}
        <Card>
          <SectionTitle icon="calendar" right={
            <span className="count-pill">{sessionRecords.length} 筆</span>
          }>本次登入新增的紀錄</SectionTitle>
          {sessionRecords.length ? (
            <div className="table">
              <div className="tr th">
                <div className="td col-name">學生</div>
                <div className="td col-type">類型</div>
                <div className="td col-score">得分</div>
                <div className="td col-act"></div>
              </div>
              {sessionRecords.map(g => {
                const st = D.students.find(s => s.id === g.studentId);
                return (
                  <div className="tr" key={g.id}>
                    <div className="td col-name">
                      <div className="cell-stack">
                        <span>{st ? st.name : "—"}</span>
                        <span className="cell-sub">{g.title}</span>
                      </div>
                    </div>
                    <div className="td col-type"><TypeBadge type={g.type} /></div>
                    <div className="td col-score"><ScoreChip score={g.score} size="sm" /></div>
                    <div className="td col-act">
                      <button className="icon-btn danger" title="刪除" onClick={() => deleteGrade(g.id)}>
                        <Icon name="trash" size={15} />
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          ) : (
            <div className="empty-state">
              <Icon name="pencil" size={26} />
              <p>本次登入還沒有新增任何成績。</p>
              <span>新增的紀錄會列在這裡，可隨時刪除。</span>
            </div>
          )}
        </Card>
      </div>

      {toast && <div className={"toast toast-" + toast.tone}><Icon name={toast.tone === "good" ? "check" : "info"} size={16} />{toast.msg}</div>}
    </div>
  );
}

/* ============================================================
   全班成績（老師）
   ============================================================ */
function ClassGradesScreen({ grades, types }) {
  const [typeFilter, setTypeFilter] = useState("全部");
  const [studentFilter, setStudentFilter] = useState("all");

  const filtered = useMemo(() => {
    return grades.filter(g =>
      (typeFilter === "全部" || g.type === typeFilter) &&
      (studentFilter === "all" || g.studentId === studentFilter)
    );
  }, [grades, typeFilter, studentFilter]);

  const cs = useMemo(() => {
    const sc = filtered.map(g => g.score);
    return {
      average: sc.length ? +(sc.reduce((a, b) => a + b, 0) / sc.length).toFixed(1) : 0,
      passRate: sc.length ? Math.round(sc.filter(s => s >= 60).length / sc.length * 100) : 0,
      count: sc.length,
      students: D.students.length
    };
  }, [filtered]);

  const buckets = useMemo(() => {
    const sc = filtered.map(g => g.score);
    return [
      { key: "fail", label: "不及格", count: sc.filter(s => s < 60).length },
      { key: "warn", label: "待加強", count: sc.filter(s => s >= 60 && s < 80).length },
      { key: "good", label: "良好", count: sc.filter(s => s >= 80).length }
    ];
  }, [filtered]);

  // 每位學生平均（依目前類型篩選）
  const roster = useMemo(() => {
    return D.students.map(s => {
      const gs = grades.filter(g => g.studentId === s.id && (typeFilter === "全部" || g.type === typeFilter));
      const sc = gs.map(g => g.score);
      const avg = sc.length ? +(sc.reduce((a, b) => a + b, 0) / sc.length).toFixed(1) : 0;
      return { ...s, avg, count: sc.length };
    });
  }, [grades, typeFilter]);

  const selStudent = studentFilter === "all" ? null : D.students.find(s => s.id === studentFilter);
  const selGrades = selStudent
    ? grades.filter(g => g.studentId === selStudent.id && (typeFilter === "全部" || g.type === typeFilter)).slice().sort(byDate)
    : [];

  const typeOpts = ["全部", ...types];

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="hello">全班成績</div>
          <div className="page-sub">七年三班・數學科｜共 {D.students.length} 位學生</div>
        </div>
        <div className="head-filters">
          <div className="select-wrap sm">
            <select value={studentFilter} onChange={e => setStudentFilter(e.target.value)}>
              <option value="all">全班學生</option>
              {D.students.map(s => <option key={s.id} value={s.id}>{String(s.seat).padStart(2, "0")}・{s.name}</option>)}
            </select>
            <Icon name="chevron" size={15} />
          </div>
        </div>
      </div>

      <div className="chip-row" style={{ marginBottom: 4 }}>
        {typeOpts.map(t => (
          <FilterChip key={t} active={typeFilter === t} onClick={() => setTypeFilter(t)}>{t}</FilterChip>
        ))}
      </div>

      <div className="grid-4">
        <StatCard label={selStudent ? selStudent.name + " 平均" : "班級平均"} value={cs.average} icon="chart" tone="accent" />
        <StatCard label="及格率" value={cs.passRate} suffix="%" icon="check"
          tone={cs.passRate >= 80 ? "good" : cs.passRate >= 60 ? "warn" : "fail"} />
        <StatCard label="評量筆數" value={cs.count} suffix=" 筆" icon="calendar" />
        <StatCard label="學生人數" value={cs.students} suffix=" 人" icon="users" />
      </div>

      {selStudent ? (
        /* 單一學生明細 */
        <Card>
          <SectionTitle icon="user" right={
            <button className="link-btn" onClick={() => setStudentFilter("all")}>← 回全班</button>
          }>{selStudent.name}・成績明細</SectionTitle>
          <div className="table">
            <div className="tr th">
              <div className="td col-date">日期</div>
              <div className="td col-type">類型</div>
              <div className="td col-title">評量項目</div>
              <div className="td col-score">得分</div>
            </div>
            {selGrades.slice().reverse().map(g => (
              <div className="tr" key={g.id}>
                <div className="td col-date mono">{fmtDate(g.date)}</div>
                <div className="td col-type"><TypeBadge type={g.type} /></div>
                <div className="td col-title">{g.title}</div>
                <div className="td col-score"><ScoreChip score={g.score} /></div>
              </div>
            ))}
          </div>
        </Card>
      ) : (
        <div className="class-layout">
          <Card>
            <SectionTitle icon="users">學生平均一覽</SectionTitle>
            <div className="roster">
              {roster.map(s => (
                <button className="roster-row" key={s.id} onClick={() => setStudentFilter(s.id)}>
                  <span className="roster-seat mono">{String(s.seat).padStart(2, "0")}</span>
                  <span className="roster-name">{s.name}</span>
                  <span className="roster-bar">
                    <span className={"roster-fill lvl-" + D.gradeLevel(s.avg).key} style={{ width: s.avg + "%" }} />
                  </span>
                  <ScoreChip score={Math.round(s.avg)} size="sm" />
                </button>
              ))}
            </div>
          </Card>
          <Card>
            <SectionTitle icon="chart">成績分佈</SectionTitle>
            <DistBar buckets={buckets} />
            <div className="legend">
              <span><i className="lg lvl-good" />良好 ≥80</span>
              <span><i className="lg lvl-warn" />待加強 60–79</span>
              <span><i className="lg lvl-fail" />不及格 &lt;60</span>
            </div>
          </Card>
        </div>
      )}
    </div>
  );
}

window.MyGradesScreen = MyGradesScreen;
window.InputGradesScreen = InputGradesScreen;
window.ClassGradesScreen = ClassGradesScreen;
window.fmtDate = fmtDate;
window.TODAY = TODAY;
