/* 匯入 & AI 學習分析畫面 — screens2.jsx */
const { useState: useState2, useMemo: useMemo2 } = React;
const {
  Icon: Icon2, Card: Card2, StatCard: StatCard2, TypeBadge: TypeBadge2,
  ScoreChip: ScoreChip2, RiskLight: RiskLight2, Button: Button2,
  SectionTitle: SectionTitle2, TrendLine: TrendLine2
} = window;
const D2 = window.APPDATA;
const fmt2 = window.fmtDate;

/* ============================================================
   匯入成績（老師）— 三步驟流程
   ============================================================ */
function ImportScreen({ commitImport }) {
  const [step, setStep] = useState2(1);
  const [source, setSource] = useState2(null); // "excel" | "sheet"
  const [done, setDone] = useState2(false);
  const rows = D2.importSampleRows;
  const okRows = rows.filter(r => r.status !== "error");
  const errRows = rows.filter(r => r.status === "error");

  const steps = ["上傳來源", "預覽與對應", "確認匯入"];

  function reset() { setStep(1); setSource(null); setDone(false); }

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="hello">匯入成績</div>
          <div className="page-sub">支援 Excel 檔上傳，或連結 Google 試算表批次匯入。</div>
        </div>
      </div>

      {/* 步驟列 */}
      <div className="stepper">
        {steps.map((s, i) => {
          const n = i + 1;
          const state = done ? "done" : n < step ? "done" : n === step ? "active" : "idle";
          return (
            <React.Fragment key={s}>
              <div className={"step " + state}>
                <span className="step-dot">{state === "done" ? <Icon2 name="check" size={15} /> : n}</span>
                <span className="step-label">{s}</span>
              </div>
              {i < steps.length - 1 && <div className={"step-line " + ((n < step || done) ? "done" : "")} />}
            </React.Fragment>
          );
        })}
      </div>

      {done ? (
        <Card2 className="import-done">
          <div className="done-badge"><Icon2 name="check" size={34} /></div>
          <h2>匯入完成</h2>
          <p>已成功匯入 <b>{okRows.length}</b> 筆成績{errRows.length ? <>，略過 <b>{errRows.length}</b> 筆有問題的資料。</> : "。"}</p>
          <div className="done-actions">
            <Button2 variant="ghost" icon="upload" onClick={reset}>再匯入一批</Button2>
            <Button2 onClick={reset}>完成</Button2>
          </div>
        </Card2>
      ) : (
        <>
          {/* Step 1 — 上傳來源 */}
          {step === 1 && (
            <Card2>
              <SectionTitle2 icon="upload">選擇匯入來源</SectionTitle2>
              <div className="source-grid">
                <button className={"source-card" + (source === "excel" ? " sel" : "")} onClick={() => setSource("excel")}>
                  <span className="source-ic file"><Icon2 name="file" size={26} /></span>
                  <span className="source-name">上傳 Excel 檔</span>
                  <span className="source-desc">.xlsx / .csv，依範本欄位排列</span>
                </button>
                <button className={"source-card" + (source === "sheet" ? " sel" : "")} onClick={() => setSource("sheet")}>
                  <span className="source-ic sheet"><Icon2 name="sheet" size={26} /></span>
                  <span className="source-name">連結 Google 試算表</span>
                  <span className="source-desc">貼上分享連結，自動同步</span>
                </button>
              </div>

              {source === "excel" && (
                <div className="dropzone">
                  <Icon2 name="upload" size={28} />
                  <div className="dz-title">將 Excel 檔拖曳到這裡，或點擊選擇</div>
                  <div className="dz-sub">已選擇範例檔：<b>七年三班_第5次小考.xlsx</b>（8 列）</div>
                </div>
              )}
              {source === "sheet" && (
                <div className="sheet-input">
                  <div className="select-wrap" style={{ flex: 1 }}>
                    <input className="text-input" defaultValue="https://docs.google.com/spreadsheets/d/1aB...（範例）" />
                  </div>
                  <span className="sheet-ok"><Icon2 name="check" size={14} /> 連結有效</span>
                </div>
              )}

              <div className="step-actions">
                <Button2 disabled={!source} icon="chevron" onClick={() => setStep(2)}>下一步：預覽</Button2>
              </div>
            </Card2>
          )}

          {/* Step 2 — 預覽與對應 */}
          {step === 2 && (
            <Card2>
              <SectionTitle2 icon="sheet" right={
                <span className="preview-summary">
                  <span className="ok-pill"><Icon2 name="check" size={13} /> {okRows.length} 筆可匯入</span>
                  {errRows.length > 0 && <span className="err-pill"><Icon2 name="info" size={13} /> {errRows.length} 筆需檢查</span>}
                </span>
              }>預覽資料・欄位對應</SectionTitle2>

              <div className="mapping">
                {[["座號", "seat"], ["姓名", "name"], ["評量類型", "type"], ["評量項目", "title"], ["日期", "date"], ["得分", "score"]].map(([cn]) => (
                  <span className="map-tag" key={cn}>{cn} <Icon2 name="check" size={12} /></span>
                ))}
              </div>

              <div className="table preview-table">
                <div className="tr th">
                  <div className="td col-seat">座號</div>
                  <div className="td col-name">姓名</div>
                  <div className="td col-type">類型</div>
                  <div className="td col-title">評量項目</div>
                  <div className="td col-date">日期</div>
                  <div className="td col-score">得分</div>
                </div>
                {rows.map((r, i) => (
                  <div className={"tr" + (r.status === "error" ? " row-error" : "")} key={i}>
                    <div className="td col-seat mono">{String(r.seat).padStart(2, "0")}</div>
                    <div className="td col-name">{r.name}</div>
                    <div className="td col-type"><TypeBadge2 type={r.type} /></div>
                    <div className="td col-title">{r.title}</div>
                    <div className="td col-date mono">{fmt2(r.date)}</div>
                    <div className="td col-score">
                      {r.score == null
                        ? <span className="cell-error"><Icon2 name="info" size={13} /> 缺漏</span>
                        : <ScoreChip2 score={r.score} size="sm" />}
                    </div>
                  </div>
                ))}
              </div>
              {errRows.length > 0 && (
                <div className="warn-note">
                  <Icon2 name="info" size={15} />
                  有 {errRows.length} 列得分缺漏，匯入時將自動略過。請確認後再繼續。
                </div>
              )}

              <div className="step-actions">
                <Button2 variant="ghost" onClick={() => setStep(1)}>上一步</Button2>
                <Button2 icon="chevron" onClick={() => setStep(3)}>下一步：確認</Button2>
              </div>
            </Card2>
          )}

          {/* Step 3 — 確認 */}
          {step === 3 && (
            <Card2>
              <SectionTitle2 icon="check">確認匯入</SectionTitle2>
              <div className="confirm-grid">
                <div className="confirm-item">
                  <span className="ci-label">來源</span>
                  <span className="ci-value">{source === "excel" ? "Excel 檔・七年三班_第5次小考.xlsx" : "Google 試算表"}</span>
                </div>
                <div className="confirm-item">
                  <span className="ci-label">評量項目</span>
                  <span className="ci-value">第 5 次小考・統計圖表</span>
                </div>
                <div className="confirm-item">
                  <span className="ci-label">可匯入筆數</span>
                  <span className="ci-value ok">{okRows.length} 筆</span>
                </div>
                <div className="confirm-item">
                  <span className="ci-label">略過筆數</span>
                  <span className="ci-value">{errRows.length} 筆（缺漏）</span>
                </div>
              </div>
              <div className="confirm-note">
                <Icon2 name="info" size={15} />
                匯入後，這些成績會立即出現在「全班成績」與學生的「我的成績」中。
              </div>
              <div className="step-actions">
                <Button2 variant="ghost" onClick={() => setStep(2)}>上一步</Button2>
                <Button2 icon="upload" onClick={() => { commitImport && commitImport(okRows); setDone(true); }}>
                  確認匯入 {okRows.length} 筆
                </Button2>
              </div>
            </Card2>
          )}
        </>
      )}
    </div>
  );
}

/* ============================================================
   AI 學習分析（學生 / 小老師）
   ============================================================ */
function AnalysisScreen({ studentId, grades }) {
  const student = D2.students.find(s => s.id === studentId);
  const myGrades = useMemo2(
    () => grades.filter(g => g.studentId === studentId).slice().sort((a, b) => a.date < b.date ? -1 : 1),
    [grades, studentId]
  );
  const risk = useMemo2(() => D2.riskFor(studentId, grades), [grades, studentId]);
  const trend = myGrades.map(g => g.score);

  // 各類型平均
  const byType = useMemo2(() => {
    return D2.assessmentTypes.map(t => {
      const sc = myGrades.filter(g => g.type === t).map(g => g.score);
      return { type: t, avg: sc.length ? Math.round(sc.reduce((a, b) => a + b, 0) / sc.length) : null };
    }).filter(x => x.avg != null);
  }, [myGrades]);

  const weakest = byType.slice().sort((a, b) => a.avg - b.avg)[0];

  if (!risk) return <div className="page"><Card2>尚無足夠成績可分析。</Card2></div>;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="hello">學習分析</div>
          <div className="page-sub">{student.name}・AI 依你的平時成績預估期末表現</div>
        </div>
      </div>

      {/* 大型風險面板 */}
      <Card2 className={"risk-hero risk-bg-" + risk.level}>
        <div className="hero-left">
          <span className="risk-chip"><Icon2 name="spark" size={15} /> AI 期末預測</span>
          <div className={"hero-status risk-" + risk.level}>
            <RiskLight2 level={risk.level} size={18} />
            <span>{risk.headline}</span>
          </div>
          <p className="hero-advice">{risk.advice}</p>
          <div className="hero-meta">
            <span>整體平均 <b>{risk.overall}</b></span>
            <span>近期平均 <b>{risk.recentAvg}</b></span>
            <span className={risk.trend >= 0 ? "up" : "down"}>
              <Icon2 name={risk.trend >= 0 ? "arrowUp" : "arrowDown"} size={13} />
              趨勢 {risk.trend >= 0 ? "+" : ""}{risk.trend}
            </span>
          </div>
        </div>
        <div className="hero-gauge">
          <div className="gauge-num">{risk.predicted}</div>
          <div className="gauge-lbl">預估期末平均</div>
          <div className="gauge-pass">及格門檻 60 分</div>
        </div>
      </Card2>

      <div className="analysis-grid">
        <Card2>
          <SectionTitle2 icon="chart">學期成績趨勢</SectionTitle2>
          <TrendLine2 points={trend} height={150} />
          <div className="trend-foot">
            <span>第一次評量</span>
            <span className="trend-foot-mid">虛線 = 及格線 60</span>
            <span>最近一次</span>
          </div>
        </Card2>

        <Card2>
          <SectionTitle2 icon="award">各類型表現</SectionTitle2>
          <div className="type-bars">
            {byType.map(b => (
              <div className="type-bar-row" key={b.type}>
                <TypeBadge2 type={b.type} />
                <span className="type-bar-track">
                  <span className={"type-bar-fill lvl-" + D2.gradeLevel(b.avg).key} style={{ width: b.avg + "%" }} />
                </span>
                <ScoreChip2 score={b.avg} size="sm" />
              </div>
            ))}
          </div>
          {weakest && (
            <div className="suggest-note">
              <Icon2 name="info" size={15} />
              <span>建議優先加強 <b>{weakest.type}</b>（目前平均 {weakest.avg} 分），提升空間最大。</span>
            </div>
          )}
        </Card2>
      </div>

      <div className="disclaimer">
        <Icon2 name="info" size={13} /> AI 預測僅供參考，實際成績以老師評定為準。
      </div>
    </div>
  );
}

window.ImportScreen = ImportScreen;
window.AnalysisScreen = AnalysisScreen;
