// Modals — new space, new doc, move session, new session context

function ModalRoot() {
  const { state, dispatch } = useApp();
  const m = state.modal;
  if (!m) return null;
  const close = () => dispatch({ type: "CLOSE_MODAL" });
  const C = {
    "new-space":    NewSpaceModal,
    "edit-space":   EditSpaceModal,
    "new-doc":      NewDocModal,
    "move-session": MoveSessionModal,
    "new-session-ctx": NewSessionContextModal,
    "rename":       RenameModal,
    "rename-session": window.RenameSessionModal,
    "avatar":       window.AvatarModal,
    "change-password": window.ChangePasswordModal,
    "twofa":        window.TwoFAModal,
    "delete-account": window.DeleteAccountModal,
    "payment-method": window.PaymentMethodModal,
    "billing-history": window.BillingHistoryModal,
    "checkout":     window.CheckoutModal,
    "export":       window.ExportModal,
    "import":       window.ImportModal,
  }[m.type];
  if (!C) return null;
  const size = m.type === "billing-history" ? "lg"
    : (m.type === "move-session" || m.type === "new-session-ctx" || m.type === "checkout") ? "lg"
    : "md";
  return (
    <Modal open onClose={close} size={size}>
      <C {...m} onClose={close} />
    </Modal>
  );
}

// ── New space ────────────────────────────────────────────────
function NewSpaceModal({ onClose }) {
  const { dispatch } = useApp();
  const [name, setName] = React.useState("");
  const [color, setColor] = React.useState(PALETTE_OPTIONS[0]);
  const [desc, setDesc] = React.useState("");
  const create = () => {
    if (!name.trim()) return;
    dispatch({ type: "NEW_SPACE", name: name.trim(), color, description: desc.trim() });
    onClose?.();
  };
  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-1">새 공간</div>
        <div className="text-[22px] font-semibold text-ink tracking-tight2">한 가지 주제만 담는 공간</div>
        <div className="text-[13px] text-mute mt-1.5 leading-[1.6]">
          공간은 채팅과 문서가 함께 사는 단위예요. 한 공간엔 하나의 큰 주제만 두는 게 좋습니다.
        </div>
      </div>

      <label className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">이름</span>
        <input
          value={name}
          onChange={e => setName(e.target.value)}
          autoFocus
          placeholder="예: 일, 건강, 글쓰기…"
          className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[15px] text-ink placeholder:text-dim outline-none focus:border-ink2"
          onKeyDown={e => { if (e.key === "Enter" && !e.nativeEvent.isComposing) create(); }}
        />
      </label>

      <div className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">색</span>
        <div className="flex gap-2 flex-wrap">
          {PALETTE_OPTIONS.map(c => (
            <button
              key={c}
              onClick={() => setColor(c)}
              className={cn("w-7 h-7 rounded-full border-2 transition", color === c ? "border-ink scale-110" : "border-transparent")}
              style={{ background: c }}
              aria-label={c}
            />
          ))}
        </div>
      </div>

      <label className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">짧은 설명 <span className="text-dim">(선택)</span></span>
        <input
          value={desc}
          onChange={e => setDesc(e.target.value)}
          placeholder="이 공간에 어떤 것이 들어오는지"
          className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[14px] text-ink placeholder:text-dim outline-none focus:border-ink2"
        />
      </label>

      <div className="flex justify-end gap-2 pt-1">
        <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
        <Btn kind="primary" size="md" onClick={create} disabled={!name.trim()}>만들기</Btn>
      </div>
    </div>
  );
}

// ── Edit space (name / color / description / delete) ────────
function EditSpaceModal({ spaceId, onClose }) {
  const { state, dispatch } = useApp();
  const sp = state.spaces.find(s => s.id === spaceId);
  if (!sp) return null;
  const [name, setName] = React.useState(sp.name);
  const [color, setColor] = React.useState(sp.dot);
  const [desc, setDesc] = React.useState(sp.description || "");
  const [confirmDel, setConfirmDel] = React.useState(false);

  const save = () => {
    if (!name.trim()) return;
    dispatch({ type: "EDIT_SPACE", id: spaceId, name: name.trim(), color, description: desc.trim() });
    onClose?.();
  };
  const remove = () => {
    if (!confirmDel) { setConfirmDel(true); return; }
    dispatch({ type: "DELETE_SPACE", id: spaceId });
  };

  const docCount = state.docs.filter(d => d.spaceId === spaceId).length;
  const sessionCount = (state.sessions[spaceId] || []).length;

  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-1">공간 편집</div>
        <div className="text-[22px] font-semibold text-ink tracking-tight2 flex items-center gap-2">
          <Dot color={color} size={14} />
          {name || "(이름 없음)"}
        </div>
      </div>

      <label className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">이름</span>
        <input
          value={name}
          onChange={e => setName(e.target.value)}
          autoFocus
          onKeyDown={e => { if (e.key === "Enter" && !e.nativeEvent.isComposing) save(); }}
          className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[15px] text-ink outline-none focus:border-ink2"
        />
      </label>

      <div className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">색</span>
        <div className="flex gap-2 flex-wrap">
          {PALETTE_OPTIONS.map(c => (
            <button
              key={c}
              onClick={() => setColor(c)}
              className={cn("w-7 h-7 rounded-full border-2 transition", color === c ? "border-ink scale-110" : "border-transparent")}
              style={{ background: c }}
              aria-label={c}
            />
          ))}
        </div>
      </div>

      <label className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">짧은 설명 <span className="text-dim">(선택)</span></span>
        <input
          value={desc}
          onChange={e => setDesc(e.target.value)}
          placeholder="이 공간에 어떤 것이 들어오는지"
          className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[14px] text-ink placeholder:text-dim outline-none focus:border-ink2"
        />
      </label>

      <div className="border-t border-ruleSoft pt-4 flex flex-col gap-2.5">
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium">공간 정보</div>
        <div className="text-[12.5px] text-mute leading-[1.6]">
          이 공간에는 문서 <span className="text-ink font-medium">{docCount}</span>개, 세션 <span className="text-ink font-medium">{sessionCount}</span>개가 있어요.
        </div>
        {state.spaces.length > 1 && (
          confirmDel ? (
            <div className="flex items-center gap-2 px-3 py-2.5 rounded-lg bg-[#FBEEEC] border border-[#E8C6C2] text-[12.5px] text-[#8E322D]">
              <span className="flex-1">정말 삭제할까요? 문서 {docCount}개와 세션 {sessionCount}개가 함께 사라져요. 되돌릴 수 없습니다.</span>
              <button onClick={() => setConfirmDel(false)} className="px-2.5 py-1 text-mute hover:text-ink text-[12px]">취소</button>
              <button onClick={remove} className="px-2.5 py-1 rounded-md bg-[#C5524C] text-white text-[12px] font-medium">삭제</button>
            </div>
          ) : (
            <button onClick={remove} className="self-start text-[12.5px] text-[#C5524C] hover:underline">공간 삭제…</button>
          )
        )}
      </div>

      <div className="flex justify-end gap-2 pt-1">
        <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
        <Btn kind="primary" size="md" onClick={save} disabled={!name.trim()}>저장</Btn>
      </div>
    </div>
  );
}

// ── New doc ──────────────────────────────────────────────────
function NewDocModal({ spaceId, onClose }) {
  const { dispatch, getSpace } = useApp();
  const sp = getSpace(spaceId);
  const [title, setTitle] = React.useState("");
  const [aiTitle] = React.useState("회의 — 결정권자 부재 패턴"); // mock AI suggestion
  const create = (t) => {
    dispatch({ type: "NEW_DOC", spaceId, title: t || aiTitle });
    onClose?.();
  };
  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-1 flex items-center gap-2">
          {sp && <><Dot color={sp.dot} size={6} /> {sp.name}</>} 공간 · 새 문서
        </div>
        <div className="text-[20px] font-semibold text-ink tracking-tight2">제목을 정해주세요</div>
        <div className="text-[13px] text-mute mt-1.5 leading-[1.6]">
          AI가 방금 대화에서 지은 제목을 제안하고 있어요. 마음에 들면 그대로, 아니면 직접 적으세요.
        </div>
      </div>

      <div className="flex items-center gap-2 px-3.5 py-3 rounded-lg bg-okSoft border border-okBord text-[13.5px]">
        <Pulse tone="ok" />
        <span className="text-[#3E7C5C]">AI가 지은 제목:</span>
        <span className="text-ink font-medium flex-1 truncate">「{aiTitle}」</span>
        <button onClick={() => create(aiTitle)} className="text-[12px] text-ink font-medium underline decoration-dotted">사용</button>
      </div>

      <label className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">또는 직접</span>
        <input
          value={title}
          onChange={e => setTitle(e.target.value)}
          placeholder="제목"
          autoFocus
          onKeyDown={e => { if (e.key === "Enter" && !e.nativeEvent.isComposing && title.trim()) create(title.trim()); }}
          className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[15px] text-ink placeholder:text-dim outline-none focus:border-ink2"
        />
      </label>

      <div className="flex justify-end gap-2 pt-1">
        <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
        <Btn kind="primary" size="md" onClick={() => create(title.trim() || aiTitle)}>만들기</Btn>
      </div>
    </div>
  );
}

// ── Move session ─────────────────────────────────────────────
function MoveSessionModal({ fromSpaceId, sessionId, title, onClose }) {
  const { state, dispatch, getSpace } = useApp();
  const from = getSpace(fromSpaceId);
  const isFromDefault = fromSpaceId === "__default__";
  const [target, setTarget] = React.useState(state.spaces[0]?.id || null);

  const move = () => {
    if (!target) return;
    dispatch({
      type: "MOVE_SESSION",
      fromSpaceId, toSpaceId: target,
      sessionId,
      title: title || (isFromDefault ? "기본 채팅에서 옮겨옴" : title),
    });
  };

  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-1">세션 옮기기</div>
        <div className="text-[20px] font-semibold text-ink tracking-tight2">
          {isFromDefault ? "기본 채팅의 대화를 공간으로" : `「${title}」을(를) 다른 공간으로`}
        </div>
        <div className="text-[13px] text-mute mt-1.5 leading-[1.6]">
          {isFromDefault
            ? "기본 채팅의 메시지를 그대로 가져와 선택한 공간의 새 세션으로 시작합니다."
            : <>이 세션이 이전 공간에서 만들어둔 <span className="text-ink">문서는 그대로 남습니다</span>. 세션만 이동해요.</>
          }
        </div>
      </div>

      {!isFromDefault && (
        <div className="px-3.5 py-2.5 rounded-lg bg-lockBg border border-lockBord text-[12.5px] text-[#5C5347] leading-[1.55] flex items-start gap-2">
          <span className="w-3.5 h-3.5 rounded-[3px] bg-[#7A6F5C] mt-0.5 shrink-0" />
          <span>지금까지 만든 문서는 이전 공간(<Dot color={from?.dot} size={6} className="inline-block mx-0.5" /> {from?.name})에 남고, 앞으로 새 메시지에서 만들어지는 문서는 새 공간에 생깁니다.</span>
        </div>
      )}

      <div className="flex flex-col gap-1.5">
        <span className="text-[12px] text-mute">옮길 공간</span>
        <div className="grid grid-cols-1 gap-1">
          {state.spaces.filter(s => s.id !== fromSpaceId).map(s => (
            <button
              key={s.id}
              onClick={() => setTarget(s.id)}
              className={cn(
                "flex items-center gap-2.5 px-3 py-2.5 rounded-lg border text-left transition",
                target === s.id ? "bg-chipBg border-rule" : "bg-paper border-rule hover:bg-cream"
              )}
            >
              <Dot color={s.dot} />
              <span className="text-[14px] text-ink font-medium flex-1">{s.name}</span>
              <span className="text-[11.5px] text-dim">{s.description}</span>
              {target === s.id && <span className="text-[12px] text-[#3E7C5C]">✓ 선택됨</span>}
            </button>
          ))}
        </div>
      </div>

      <div className="flex justify-end gap-2 pt-1">
        <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
        <Btn kind="primary" size="md" onClick={move} disabled={!target}>옮기기</Btn>
      </div>
    </div>
  );
}

// ── New session context ──────────────────────────────────────
function NewSessionContextModal({ spaceId, onClose }) {
  const { state, dispatch, getSpace, docsForSpace } = useApp();
  const sp = getSpace(spaceId);
  const docs = docsForSpace(spaceId);
  const [active, setActive] = React.useState(() => new Set(docs.filter(d => d.autoReflected).map(d => d.id)));
  const toggle = (id) => {
    const n = new Set(active);
    n.has(id) ? n.delete(id) : n.add(id);
    setActive(n);
  };
  const start = () => {
    dispatch({ type: "NEW_SESSION", spaceId, title: "새 세션" });
    onClose?.();
  };
  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-1 flex items-center gap-2">
          {sp && <><Dot color={sp.dot} size={6} /> {sp.name}</>} 공간 · 새 세션
        </div>
        <div className="text-[20px] font-semibold text-ink tracking-tight2">맥락 활성화</div>
        <div className="text-[13px] text-mute mt-1.5 leading-[1.6]">
          새 세션을 시작할 때 함께 끌어올 문서를 선택하세요. 비워두고 시작해도 됩니다 — 대화에서 언급되면 알아서 들어와요.
        </div>
      </div>

      <div className="flex flex-col gap-1 max-h-[320px] overflow-y-auto scroll-paper border border-rule rounded-lg p-1.5 bg-cream">
        {docs.map(d => (
          <label key={d.id} className="flex items-center gap-3 px-2.5 py-2 rounded-md hover:bg-paper cursor-pointer">
            <input
              type="checkbox"
              checked={active.has(d.id)}
              onChange={() => toggle(d.id)}
              className="accent-ink w-4 h-4"
            />
            <div className="flex-1 min-w-0">
              <div className="text-[13.5px] text-ink font-medium truncate">{d.title}</div>
              <div className="text-[11px] text-dim truncate">{d.updated} · {d.size}</div>
            </div>
            {d.locked && <span className="text-[10.5px] text-dim">잠금</span>}
          </label>
        ))}
        {docs.length === 0 && <div className="text-[12.5px] text-dim p-3">이 공간에는 아직 문서가 없어요.</div>}
      </div>

      <div className="flex items-center justify-between text-[11.5px] text-mute pt-1">
        <span>{active.size}개 선택됨</span>
        <div className="flex gap-2">
          <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
          <Btn kind="primary" size="md" onClick={start}>세션 시작</Btn>
        </div>
      </div>
    </div>
  );
}

// ── Rename modal ────────────────────────────────────────────
function RenameModal({ docId, currentTitle, onClose }) {
  const { dispatch } = useApp();
  const [t, setT] = React.useState(currentTitle || "");
  const save = () => {
    dispatch({ type: "RENAME_DOC", docId, title: t.trim() || currentTitle });
    onClose?.();
  };
  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[20px] font-semibold text-ink tracking-tight2">제목 바꾸기</div>
      </div>
      <input
        value={t}
        onChange={e => setT(e.target.value)}
        autoFocus
        onKeyDown={e => { if (e.key === "Enter" && !e.nativeEvent.isComposing) save(); }}
        className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[16px] text-ink outline-none focus:border-ink2"
      />
      <div className="flex justify-end gap-2">
        <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
        <Btn kind="primary" size="md" onClick={save}>저장</Btn>
      </div>
    </div>
  );
}

// ── Rename session modal ────────────────────────────────────
function RenameSessionModal({ kind, spaceId, sessionId, currentTitle, onClose }) {
  const { dispatch } = useApp();
  const [t, setT] = React.useState(currentTitle || "");
  const save = () => {
    dispatch({ type: "RENAME_SESSION", kind, spaceId, sessionId, title: t.trim() || currentTitle });
    onClose?.();
  };
  return (
    <div className="p-6 flex flex-col gap-5">
      <div>
        <div className="text-[11.5px] text-mute uppercase tracking-[0.08em] font-medium mb-1">세션 이름</div>
        <div className="text-[20px] font-semibold text-ink tracking-tight2">채팅 제목 바꾸기</div>
      </div>
      <input
        value={t}
        onChange={e => setT(e.target.value)}
        autoFocus
        onKeyDown={e => { if (e.key === "Enter" && !e.nativeEvent.isComposing) save(); }}
        placeholder="세션 제목"
        className="bg-cream border border-rule rounded-lg px-3 py-2.5 text-[16px] text-ink outline-none focus:border-ink2"
      />
      <div className="flex justify-end gap-2">
        <Btn kind="ghost" size="md" onClick={onClose}>취소</Btn>
        <Btn kind="primary" size="md" onClick={save}>저장</Btn>
      </div>
    </div>
  );
}

Object.assign(window, { ModalRoot, NewSpaceModal, EditSpaceModal, NewDocModal, MoveSessionModal, NewSessionContextModal, RenameModal, RenameSessionModal });
