// Explore — space wiki home

function ExploreView() {
  const { state, dispatch, getSpace, docsForSpace } = useApp();
  const bp = useBreakpoint();
  const space = getSpace(state.view.spaceId);
  if (!space) return null;
  const sessions = state.sessions[space.id] || [];
  const activeSession = sessions.find(s => s.active);
  const recentSessions = sessions.filter(s => !s.active);
  const docs = docsForSpace(space.id);
  const [filter, setFilter] = React.useState("전체");

  const filtered = filter === "전체"
    ? docs
    : filter === "잠금"
      ? docs.filter(d => d.locked)
      : docs.filter(d => (d.tags || []).includes(filter));

  const grouped = {
    "최근 자동 반영": filtered.filter(d => d.autoReflected),
    "이번 주": filtered.filter(d => !d.autoReflected && ["어제", "3일 전", "오늘"].includes(d.updated)),
    "그 전":  filtered.filter(d => !d.autoReflected && !["어제", "3일 전", "오늘"].includes(d.updated)),
  };

  // Collect filter chip counts from tags
  const tagCounts = {};
  docs.forEach(d => (d.tags || []).forEach(t => { tagCounts[t] = (tagCounts[t] || 0) + 1; }));
  const chips = [
    ["전체", docs.length],
    ...Object.entries(tagCounts),
    ["잠금", docs.filter(d => d.locked).length],
  ];

  return (
    <>
      <Topbar
        mobileTitle={`${space.name} · 탐색`}
        left={
          <Crumb>
            <Dot color={space.dot} />
            <span className="text-ink font-medium">{space.name}</span>
            <span className="text-dim">· 탐색</span>
          </Crumb>
        }
      />

      <div className="flex-1 overflow-y-auto scroll-paper">
        <div className="mx-auto w-full max-w-[920px] px-4 sm:px-8 py-7 flex flex-col gap-6">

          {/* Header */}
          <div className="flex flex-col gap-2">
            <div className="text-[28px] font-semibold text-ink tracking-tight2 flex items-center gap-3 group">
              <Dot color={space.dot} size={14} />
              <span>{space.name}</span>
              <button
                onClick={() => dispatch({ type: "OPEN_MODAL", modal: { type: "edit-space", spaceId: space.id } })}
                className="text-[12.5px] text-mute hover:text-ink underline decoration-dotted underline-offset-4 transition"
                aria-label="공간 편집"
              >편집</button>
            </div>
            <div className="text-[13px] text-mute">
              문서 {docs.length} · 세션 {sessions.length} · 마지막 활동 {activeSession?.when || "—"}
            </div>
            {space.description && <div className="text-[13px] text-mute italic">{space.description}</div>}
          </div>

          {/* Session zone */}
          <div className="grid grid-cols-1 md:grid-cols-[1fr_340px] gap-4">
            <div className="bg-paper border border-rule rounded-xl p-5 flex flex-col gap-3">
              {activeSession ? (
                <>
                  <div className="flex items-center gap-2 text-[11.5px] text-[#3E7C5C] font-medium uppercase tracking-[0.06em]">
                    <Pulse tone="ok" /> 현재 진행 중인 세션
                  </div>
                  <div>
                    <div className="text-[18px] font-semibold text-ink tracking-tight1">{activeSession.title}</div>
                    <div className="text-[12.5px] text-mute mt-1">
                      {activeSession.when} · {activeSession.turns}턴 · 문서 {activeSession.docsTouched}건에 진행 중
                    </div>
                  </div>
                  <div className="flex flex-wrap gap-2 mt-1">
                    <Btn kind="primary" size="md" onClick={() => dispatch({ type: "GO", view: { type: "chat", spaceId: space.id, sessionId: activeSession.id } })}>
                      이어서 채팅 →
                    </Btn>
                    <Btn kind="ghost" size="md" onClick={() => dispatch({ type: "NEW_SESSION", spaceId: space.id })}>
                      새 세션 시작
                    </Btn>
                  </div>
                </>
              ) : (
                <>
                  <div className="text-[12.5px] text-mute">이 공간에는 진행 중인 세션이 없어요.</div>
                  <Btn kind="primary" size="md" onClick={() => dispatch({ type: "NEW_SESSION", spaceId: space.id })}>
                    새 세션 시작
                  </Btn>
                </>
              )}
            </div>
            <div className="border border-dashed border-rule rounded-xl p-4 flex flex-col gap-1 max-h-[260px]">
              <div className="flex items-baseline justify-between text-[11.5px] text-mute font-medium uppercase tracking-[0.06em] px-1 pb-1.5">
                <span>최근 세션</span>
                {sessions.length > 1 && <span className="normal-case font-normal text-[11px] text-dim">{sessions.length - 1}개</span>}
              </div>
              <div className="overflow-y-auto scroll-paper flex-1 -mx-1 px-1 flex flex-col gap-0.5">
                {recentSessions.length === 0 && <div className="px-1 py-1.5 text-[12.5px] text-dim">아직 다른 세션이 없어요.</div>}
                {recentSessions.map(s => (
                  <button
                    key={s.id}
                    onClick={() => dispatch({ type: "PICK_SESSION", spaceId: space.id, sessionId: s.id })}
                    className="flex items-start gap-2 px-2 py-1.5 rounded-md hover:bg-cream text-left"
                  >
                    <Dot color="#C4BAA3" size={6} className="mt-1.5" />
                    <div className="flex-1 min-w-0">
                      <div className="text-[13px] font-medium text-ink truncate">{s.title}</div>
                      <div className="text-[11px] text-dim mt-0.5">
                        {s.when} · {s.turns}턴
                        {s.docsTouched > 0 ? ` · ${s.docsTouched}건 영향` : " · 변경 없음"}
                      </div>
                    </div>
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Docs */}
          <div>
            <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-3 flex items-center gap-2">
              <span>문서</span>
              <span className="w-1 h-1 rounded-full bg-rule" />
              <span className="normal-case font-normal text-dim tracking-normal">{docs.length}개</span>
              <button
                onClick={() => dispatch({ type: "OPEN_MODAL", modal: { type: "new-doc", spaceId: space.id } })}
                className="ml-auto normal-case tracking-normal text-[11.5px] font-medium text-ink hover:underline"
              >＋ 새 문서</button>
            </div>

            {/* Filter chips */}
            <div className="flex gap-1.5 flex-wrap mb-3.5">
              {chips.filter(([_, c]) => c > 0).map(([t, c]) => (
                <button
                  key={t}
                  onClick={() => setFilter(t)}
                  className={cn(
                    "px-3 py-1 rounded-full text-[12px] transition",
                    filter === t ? "bg-ink text-cream font-medium" : "bg-paper border border-rule text-[#5C5347] hover:bg-cream"
                  )}
                >{t} {c}</button>
              ))}
            </div>

            <div className="flex flex-col gap-6">
              {Object.entries(grouped).map(([label, ds]) => ds.length > 0 && (
                <div key={label}>
                  <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-2.5 flex items-center gap-2">
                    {label === "최근 자동 반영" && <Pulse tone="ok" />}
                    {label}
                  </div>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                    {ds.map(d => <DocCard key={d.id} doc={d} />)}
                  </div>
                </div>
              ))}
              {filtered.length === 0 && (
                <div className="text-[13px] text-dim text-center py-8">선택한 필터에 맞는 문서가 없어요.</div>
              )}
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

function DocCard({ doc }) {
  const { dispatch, state } = useApp();
  // Extract first plain-text line from markdown for preview
  const md = docMarkdown(doc);
  const preview = md
    .split("\n")
    .map(l => l.trim())
    .find(l => l && !l.startsWith("#") && !l.startsWith(">") && !l.startsWith("-") && !l.startsWith("*") && !l.startsWith("```"))
    || md.replace(/^#+\s*/, "").split("\n")[0] || "";
  const isFlash = state.flashDocIds.has(doc.id);
  return (
    <button
      onClick={() => dispatch({ type: "GO", view: { type: "doc", docId: doc.id } })}
      className={cn(
        "text-left rounded-lg px-3.5 py-3 flex flex-col gap-1 border transition",
        doc.autoReflected || isFlash ? "bg-paper border-rule shadow-paper" : "border-ruleSoft hover:bg-paper"
      )}
    >
      <div className="flex items-center gap-2">
        {(doc.autoReflected || isFlash) && <Pulse tone={doc.isNew ? "warn" : "ok"} />}
        <div className="text-[14px] font-medium text-ink tracking-tight1 flex-1 truncate">{doc.title}</div>
        {doc.locked && <span className="text-[10.5px] text-dim border border-rule rounded px-1.5 py-px">잠금</span>}
        {doc.isNew && <span className="text-[10.5px] text-accent bg-warnSoft rounded px-1.5 py-px">NEW</span>}
      </div>
      <div className="text-[12.5px] text-body leading-[1.55] line-clamp-2">{preview}</div>
      <div className="flex items-center gap-2 text-[11px] text-dim mt-0.5">
        <span>{doc.updated} 업데이트</span><span>·</span><span>{doc.size}</span>
      </div>
    </button>
  );
}

// Empty space onboarding
function EmptySpaceView() {
  const { state, dispatch, getSpace } = useApp();
  const space = getSpace(state.view.spaceId);
  if (!space) return null;
  return (
    <>
      <Topbar
        mobileTitle={space.name}
        left={
          <Crumb>
            <Dot color={space.dot} />
            <span className="text-ink font-medium">{space.name}</span>
            <span className="text-dim">· 처음 시작</span>
          </Crumb>
        }
      />
      <div className="flex-1 flex items-center justify-center px-4">
        <div className="max-w-[480px] w-full text-center flex flex-col items-center gap-4 py-10">
          <Dot color={space.dot} size={40} />
          <div className="text-[22px] font-semibold text-ink tracking-tight2">「{space.name}」 공간이 만들어졌어요</div>
          <div className="text-[14px] text-mute leading-[1.65]">
            여기서 나누는 대화는 자동으로 이 공간 안의 문서에 정리됩니다.<br />
            첫 메시지를 보내거나 새 문서를 만들어 시작해보세요.
          </div>
          <div className="flex flex-wrap gap-2 justify-center mt-3">
            <Btn kind="primary" size="md" onClick={() => dispatch({ type: "NEW_SESSION", spaceId: space.id })}>
              새 세션으로 채팅 시작
            </Btn>
            <Btn kind="ghost" size="md" onClick={() => dispatch({ type: "OPEN_MODAL", modal: { type: "new-doc", spaceId: space.id } })}>
              빈 문서 만들기
            </Btn>
          </div>
        </div>
      </div>
    </>
  );
}

Object.assign(window, { ExploreView, EmptySpaceView, DocCard });
