// History — auto-organize ledger + undo + AI reasoning panel

function HistoryView() {
  const { state, dispatch, getSpace, getDoc } = useApp();
  const [detailId, setDetailId] = React.useState(state.view.detailId || null);
  const bp = useBreakpoint();
  const docFilter = state.view.docId || null;
  const focusedDoc = docFilter && getDoc(docFilter);

  // group history (optionally filtered) by time bucket
  const historyList = docFilter
    ? state.history.filter(h => h.docId === docFilter)
    : state.history;
  const groups = {};
  historyList.forEach(h => {
    const k = h.time === "방금" || h.time.endsWith("분 전") ? "지금" : h.time;
    (groups[k] = groups[k] || []).push(h);
  });

  const actionLabel = {
    create: "새 문서",
    update: "수정",
    merge:  "병합",
    skip:   "넘어감",
    delete: "삭제",
  };
  const actionTone = {
    create: "warn", update: "ok", merge: "ok", skip: "dim", delete: "warn",
  };

  const selected = state.history.find(h => h.id === detailId);

  // On mobile, show only list OR only detail at a time
  const showDetail = !!selected;

  return (
    <>
      <Topbar
        mobileTitle={focusedDoc ? `「${focusedDoc.title}」 이력` : "자동 정리 이력"}
        left={
          <Crumb>
            {focusedDoc ? (
              <>
                <button onClick={() => dispatch({ type: "GO", view: { type: "doc", docId: focusedDoc.id } })} className="hover:text-ink transition">← 문서로</button>
                <span className="text-dim">·</span>
                <span className="text-ink font-medium truncate max-w-[40vw]">「{focusedDoc.title}」 이력</span>
              </>
            ) : (
              <>
                <span className="text-ink font-medium">자동 정리 이력</span>
                <span className="text-dim">· 앱이 한 일을 모두 남깁니다</span>
              </>
            )}
          </Crumb>
        }
      />

      <div className="flex-1 flex min-h-0">
        {/* List */}
        <div className={cn(
          "flex-1 min-w-0 overflow-y-auto scroll-paper",
          showDetail && bp === "mobile" && "hidden"
        )}>
          <div className="mx-auto w-full max-w-[720px] px-4 sm:px-8 py-7 flex flex-col gap-6">
            {Object.entries(groups).map(([label, items]) => (
              <div key={label}>
                <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-2 px-1">{label}</div>
                <div className="flex flex-col gap-1.5">
                  {items.map(h => {
                    const sp = getSpace(h.spaceId);
                    const isFlash = state.flashHistoryIds.has(h.id);
                    return (
                      <button
                        key={h.id}
                        onClick={() => setDetailId(h.id)}
                        className={cn(
                          "text-left rounded-lg px-3.5 py-3 flex items-start gap-3 border transition",
                          detailId === h.id ? "bg-paper border-rule" : "border-transparent hover:bg-paper hover:border-ruleSoft",
                          isFlash && "bg-paper border-rule",
                          h.undone && "opacity-50"
                        )}
                      >
                        <div className="mt-1 shrink-0">
                          <Pulse tone={actionTone[h.action]} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2 flex-wrap text-[12px] text-mute mb-0.5">
                            {sp && <><Dot color={sp.dot} size={6} /><span>{sp.name}</span><span>·</span></>}
                            <span>{actionLabel[h.action]}</span>
                            <span>·</span>
                            <span>{h.time}</span>
                            {h.undone && <Pill tone="lock" className="text-[10.5px]">되돌림</Pill>}
                          </div>
                          <div className="text-[14px] font-medium text-ink truncate">{h.title}</div>
                          <div className="text-[12.5px] text-body mt-0.5 line-clamp-2">{h.detail}</div>
                        </div>
                        {h.undoable && !h.undone && (
                          <span
                            onClick={(e) => { e.stopPropagation(); dispatch({ type: "UNDO_HISTORY", id: h.id }); }}
                            className="text-[11.5px] text-dim hover:text-ink underline decoration-dotted shrink-0 mt-0.5 cursor-pointer"
                          >되돌리기</span>
                        )}
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
            {historyList.length === 0 && (
              <div className="text-center text-[13px] text-dim py-12">
                {focusedDoc ? "이 문서에 대한 자동 정리 기록이 아직 없어요." : "아직 이력이 없어요."}
              </div>
            )}
          </div>
        </div>

        {/* Detail panel */}
        {selected && (bp !== "mobile") && (
          <div className="w-[400px] shrink-0 border-l border-ruleSoft bg-parch2 overflow-y-auto scroll-paper">
            <HistoryDetail h={selected} onClose={() => setDetailId(null)} />
          </div>
        )}
        {selected && bp === "mobile" && (
          <div className="absolute inset-0 bg-cream z-20 flex flex-col push-enter">
            <Topbar mobileTitle="자동 정리 — 상세" left={<button onClick={() => setDetailId(null)} className="text-ink">← 이력</button>} />
            <div className="flex-1 overflow-y-auto scroll-paper">
              <HistoryDetail h={selected} onClose={() => setDetailId(null)} />
            </div>
          </div>
        )}
      </div>
    </>
  );
}

function HistoryDetail({ h, onClose }) {
  const { dispatch, getSpace, getDoc } = useApp();
  const sp = getSpace(h.spaceId);
  const d = h.docId && getDoc(h.docId);
  return (
    <div className="px-5 py-6 flex flex-col gap-5">
      <div className="flex items-center justify-between">
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium">AI 판단 패널</div>
        <button onClick={onClose} className="text-[12.5px] text-dim hover:text-ink">닫기</button>
      </div>

      <div>
        <div className="flex items-center gap-2 text-[12px] text-mute mb-1.5">
          {sp && <><Dot color={sp.dot} size={6} /><span>{sp.name}</span><span>·</span></>}
          <span>{h.time}</span>
        </div>
        <div className="text-[20px] font-semibold text-ink tracking-tight2">{h.title}</div>
        <div className="text-[13px] text-body mt-1.5 leading-[1.6]">{h.detail}</div>
      </div>

      <div className="bg-paper border border-rule rounded-lg p-4">
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-2">왜 이렇게 판단했나</div>
        <div className="text-[13.5px] text-body leading-[1.7]">{h.why || "—"}</div>
      </div>

      <div className="flex flex-wrap gap-2">
        {d && (
          <Btn size="md" kind="ghost" onClick={() => dispatch({ type: "GO", view: { type: "doc", docId: d.id } })}>
            문서 열기 →
          </Btn>
        )}
        {h.undoable && !h.undone && (
          <Btn size="md" kind="primary" onClick={() => dispatch({ type: "UNDO_HISTORY", id: h.id })}>
            되돌리기
          </Btn>
        )}
        {h.undone && <Pill tone="lock">되돌림</Pill>}
      </div>

      <div className="text-[11.5px] text-dim leading-[1.6] mt-2 border-t border-rule pt-3">
        자동 정리 이력은 영구적입니다. 되돌려도 “되돌림” 표시로 남고,
        다시 되살리기를 통해 같은 변경을 재적용할 수 있어요.
      </div>
    </div>
  );
}

Object.assign(window, { HistoryView, HistoryDetail });
