/* blueyetutor — /library
 * Tabs: 파일별 / 단원별
 *  - 파일별: subject filter → expandable PDF list (rename/delete, MCQ grid + FRQ list, unit editor per problem)
 *  - 단원별: subject + MCQ/FRQ + unit → pooled grid across PDFs (also unit-editable)
 *
 * Assumed endpoints:
 *   GET    /api/pdfs                          → PdfIndexRow[]
 *   GET    /api/pdfs/{pdf_id}/problems        → Problem[]
 *   PATCH  /api/pdfs/{pdf_id}  { display_name }
 *   DELETE /api/pdfs/{pdf_id}
 *   PATCH  /api/problems/{pdf_id}/{qtype}/{qnum}/units { units }
 *   GET    /api/subjects                      → [name]
 *   GET    /api/units?subject=&qtype=         → [{unit, count}]
 *   GET    /api/problems/browse?subject=&qtype=&units=
 */
const { useState: libUseState, useMemo: libUseMemo, useEffect: libUseEffect } = React;

function LibraryPage() {
  const store = useStore();
  const [view, setView] = libUseState("file");
  return (
    <div className="page col" style={{ gap: 20 }}>
      <div className="page-header">
        <div className="eyebrow">Library</div>
        <h1>처리한 모든 파일을 한 자리에</h1>
      </div>
      {store.pdfs.length === 0 ? (
        <EmptyState title="처리된 PDF 없음"
          hint="업로드 페이지에서 AP 기출 PDF를 처리하면 여기 누적됩니다."
          action={<Button variant="primary" onClick={() => location.hash = "#/upload"}>업로드로 이동</Button>}
        />
      ) : (
        <>
          <div className="row" style={{ alignItems: "center", justifyContent: "space-between" }}>
            <Segmented
              options={[{ value: "file", label: "파일별" }, { value: "unit", label: "단원별" }]}
              value={view} onChange={setView}
            />
            <span className="muted small">{store.pdfs.length} files · {store.problems.length} problems</span>
          </div>
          {view === "file" ? <LibraryByFile /> : <LibraryByUnit />}
        </>
      )}
    </div>
  );
}

// ---------- 파일별 ----------
function LibraryByFile() {
  const store = useStore();
  const subjects = ["전체", ...new Set(store.pdfs.map(d => d.subject || "(미분류)"))];
  const [sel, setSel] = libUseState("전체");
  const [q, setQ] = libUseState("");
  const view = sel === "전체" ? store.pdfs : store.pdfs.filter(d => (d.subject || "(미분류)") === sel);
  const needle = q.trim().toLowerCase();
  const nameOf = d => (d.display_name || d.pdf_id || "").toLowerCase();
  const shown = needle ? view.filter(d => nameOf(d).includes(needle)) : view;

  return (
    <div className="col" style={{ gap: 16 }}>
      {/* subject filter */}
      <div className="cluster">
        {subjects.map(s => (
          <button key={s} className={"chip " + (sel === s ? "active" : "")} onClick={() => setSel(s)}>
            {s} <span className="muted">({s === "전체" ? store.pdfs.length : store.pdfs.filter(d => (d.subject || "(미분류)") === s).length})</span>
          </button>
        ))}
      </div>

      {/* aggregate metrics */}
      <div className="metric-grid">
        <Metric label={`${sel} · PDF 수`} value={view.length} highlight />
        <Metric label="MCQ 누적" value={view.reduce((s, d) => s + d.mcq, 0)} />
        <Metric label="FRQ 누적" value={view.reduce((s, d) => s + d.frq, 0)} />
        <Metric label="라벨된 문제" value={view.reduce((s, d) => s + d.labeled, 0)} highlight />
      </div>

      {/* filename search */}
      <div className="filepick-search">
        <Icon.Search className="ic-sm" />
        <input className="input" placeholder="파일 이름으로 검색…" value={q}
               onChange={e => setQ(e.target.value)} />
        {needle && <span className="muted small">{shown.length} / {view.length}</span>}
      </div>

      {/* flat list */}
      <div className="col" style={{ gap: 8 }}>
        {shown.length === 0 ? (
          <div className="muted small" style={{ padding: "12px 4px" }}>
            {needle ? `"${q}" 와 일치하는 파일이 없어요.` : "표시할 파일이 없어요."}
          </div>
        ) : shown.map(d => <LibraryPdfRow key={d.pdf_id} pdf={d} />)}
      </div>
    </div>
  );
}

function LibraryPdfRow({ pdf }) {
  const store = useStore();
  const [open, setOpen] = libUseState(false);
  const [editMode, setEditMode] = libUseState(false);   // ← 핵심: row-level 수정 모드
  const [confirmDel, setConfirmDel] = libUseState(false);
  const [name, setName] = libUseState(pdf.display_name || pdf.pdf_id);
  const probs = libUseMemo(() => store.problems.filter(p => p.pdf_id === pdf.pdf_id), [store.problems, pdf.pdf_id]);
  const mcqs = probs.filter(p => p.qtype === "MCQ");
  const frqs = probs.filter(p => p.qtype === "FRQ");

  const onEditAnswer = p => async v =>
    window.storeActions.setProblemAnswer(p.id, v);
  const onEditSubject = p => async s =>
    window.storeActions.setProblemSubject(p.id, s);

  return (
    <div className="card">
      <div className="card-header" style={{ cursor: "pointer" }} onClick={() => setOpen(!open)}>
        {open ? <Icon.ChevDown /> : <Icon.ChevRight />}
        <Icon.File />
        <strong>{pdf.display_name || pdf.pdf_id}</strong>
        {/* 과목 Badge — 수정 모드면 클릭 가능한 trigger 로 바뀐다. */}
        {editMode
          ? <PdfSubjectBadgeEditor pdf={pdf} />
          : <Badge>{pdf.subject || "(미분류)"}</Badge>}
        <span className="muted small">MCQ {pdf.mcq} · FRQ {pdf.frq} · 라벨 {pdf.labeled}</span>
        <div className="spacer" />
        {pdf.mcq + pdf.frq === 0 && <Badge kind="warn">미지원 / 0문제</Badge>}
        {open && (
          <Button size="sm" variant={editMode ? "primary" : "ghost"}
            onClick={e => { e.stopPropagation(); setEditMode(!editMode); }}>
            <Icon.Edit /> {editMode ? "수정 종료" : "수정"}
          </Button>
        )}
      </div>
      {open && (
        <div className="card-body col" style={{ gap: 16 }}>
          {/* rename + delete — 단순 운영 / 항상 노출 */}
          <div className="row" style={{ alignItems: "flex-end", gap: 8, flexWrap: "wrap" }}>
            <Field label="표시 이름 (자유 — 예: 'Physics 2 2015 Asia')">
              <input className="input" value={name} onChange={e => setName(e.target.value)} />
            </Field>
            <Button onClick={() => window.storeActions.renamePdf(pdf.pdf_id, name)}
                    disabled={name === (pdf.display_name || pdf.pdf_id) || !name.trim()}>이름 저장</Button>
            {confirmDel ? (
              <Button variant="danger" onClick={() => window.storeActions.deletePdf(pdf.pdf_id)}><Icon.Trash /> 진짜 삭제</Button>
            ) : (
              <Button variant="ghost" onClick={() => setConfirmDel(true)}><Icon.Trash /> 삭제</Button>
            )}
          </div>
          <div className="muted mono tiny">{pdf.pdf_id}</div>
          {editMode && (
            <Banner kind="info">
              <strong>수정 모드</strong> · 과목 / 답 / 단원을 모두 직접 바꿀 수 있어요.
              답 / 단원은 카드 안에서 직접 클릭. 마치면 우상단 "수정 종료".
            </Banner>
          )}

          {mcqs.length > 0 && (
            <div>
              <h4 style={{ margin: "8px 0" }}>MCQ <span className="muted small">({mcqs.length})</span></h4>
              <div className="problem-grid">
                {mcqs.map(p => (
                  <ProblemCard key={p.id} problem={p}
                    editable={editMode}
                    showUnitEditor={editMode}
                    onEditAnswer={onEditAnswer(p)}
                    onEditSubject={onEditSubject(p)}
                    onSaveUnits={u => window.storeActions.setProblemUnits(p.pdf_id, p.qtype, p.qnum, u)} />
                ))}
              </div>
            </div>
          )}
          {frqs.length > 0 && (
            <div>
              <h4 style={{ margin: "8px 0" }}>FRQ <span className="muted small">({frqs.length})</span></h4>
              <div className="problem-grid frq">
                {frqs.map(p => (
                  <ProblemCard key={p.id} problem={p}
                    editable={editMode}
                    showUnitEditor={editMode}
                    onEditAnswer={onEditAnswer(p)}
                    onEditSubject={onEditSubject(p)}
                    scoringPaths={p.scoring_paths}
                    onSaveUnits={u => window.storeActions.setProblemUnits(p.pdf_id, p.qtype, p.qnum, u)} />
                ))}
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

// 과목 Badge 가 곧 trigger — 클릭 시 Modal 열려 6 과목 중 선택.
// editMode 일 때만 LibraryPdfRow 헤더가 이 컴포넌트를 그린다.
function PdfSubjectBadgeEditor({ pdf }) {
  const [open, setOpen] = libUseState(false);
  const [next, setNext] = libUseState(pdf.subject || "");
  const [busy, setBusy] = libUseState(false);
  const all = Object.keys(TAXONOMY);
  return (
    <>
      <button type="button" title="클릭해서 과목 변경"
        onClick={e => { e.stopPropagation(); setNext(pdf.subject || all[0]); setOpen(true); }}
        style={{ border: "none", background: "transparent", padding: 0, cursor: "pointer" }}>
        <Badge kind="warn">{pdf.subject || "(미분류)"} ✎</Badge>
      </button>
      <Modal open={open} title="과목 변경" onClose={() => setOpen(false)}
        footer={<>
          <Button variant="ghost" onClick={() => setOpen(false)}>닫기</Button>
          <Button variant="primary" disabled={busy || !next || next === pdf.subject}
            onClick={async () => {
              setBusy(true);
              await window.storeActions.setPdfSubject(pdf.pdf_id, next);
              setBusy(false); setOpen(false);
            }}>
            {busy ? "변경 중…" : "변경"}
          </Button>
        </>}>
        <div className="col" style={{ gap: 10 }}>
          <div className="muted small">
            현재: <Badge>{pdf.subject || "(미분류)"}</Badge>
            <br />이 PDF 의 모든 문제 ({(pdf.mcq || 0) + (pdf.frq || 0)}개) 의
            과목 라벨을 한 번에 바꿉니다. 단원 라벨은 그대로 — 다음 라벨링
            때 새 과목 기준으로 채워집니다.
          </div>
          <Field label="새 과목">
            <select className="select" value={next} onChange={e => setNext(e.target.value)}>
              {all.map(s => <option key={s} value={s}>{s}</option>)}
            </select>
          </Field>
        </div>
      </Modal>
    </>
  );
}

// ---------- 단원별 ----------
function LibraryByUnit() {
  const store = useStore();
  const subjects = Object.keys(TAXONOMY).filter(s => store.pdfs.some(d => d.subject === s));
  const [subject, setSubject] = libUseState(subjects[0] || "");
  const [qtype, setQtype] = libUseState("MCQ");
  const counts = libUseMemo(() => window.unitsFor(subject, qtype), [subject, qtype, store.problems]);
  const ordered = (TAXONOMY[subject] || []).filter(u => counts[u]);
  const [unit, setUnit] = libUseState(ordered[0] || "");
  React.useEffect(() => { setUnit(ordered[0] || ""); }, [subject, qtype]);
  const problems = libUseMemo(() => window.browseProblems(subject, qtype, unit ? [unit] : []), [subject, qtype, unit, store.problems]);
  const names = Object.fromEntries(store.pdfs.map(p => [p.pdf_id, p.display_name || p.pdf_id]));

  if (subjects.length === 0) {
    return <EmptyState title="라벨된 문제 없음" hint="업로드를 마치면 단원별로 풀이 차오릅니다." />;
  }

  return (
    <div className="col" style={{ gap: 16 }}>
      <div className="row" style={{ gap: 12, alignItems: "flex-end", flexWrap: "wrap" }}>
        <Field label="과목">
          <select className="select" value={subject} onChange={e => setSubject(e.target.value)}>
            {subjects.map(s => <option key={s} value={s}>{s}</option>)}
          </select>
        </Field>
        <Field label="유형">
          <Segmented options={["MCQ", "FRQ"]} value={qtype} onChange={setQtype} />
        </Field>
        <Field label={`단원 (${ordered.length}개)`}>
          <select className="select" value={unit} onChange={e => setUnit(e.target.value)} disabled={ordered.length === 0}>
            {ordered.map(u => <option key={u} value={u}>{u} ({counts[u]})</option>)}
          </select>
        </Field>
      </div>

      {ordered.length === 0 ? (
        <Banner kind="info">이 과목·{qtype} 에 라벨된 단원이 없습니다.</Banner>
      ) : (
        <>
          <div className="muted small">{unit} — {qtype} · {problems.length} 문제 (전 파일 횡단)</div>
          <div className={"problem-grid" + (qtype === "FRQ" ? " frq" : "")}>
            {/* 단원별 grid 는 표시만 — 단원/답 수정은 "파일별" 탭의 수정 모드에서 (박현우 명시). */}
            {problems.map(p => (
              <ProblemCard key={p.id} problem={p} source={names[p.pdf_id]}
                scoringPaths={qtype === "FRQ" ? p.scoring_paths : undefined} />
            ))}
          </div>
        </>
      )}
    </div>
  );
}

Object.assign(window, { LibraryPage });
