/* Denky — 피팅룸 (입어볼 옷을 모아두고, 골라서 한꺼번에 입어본다)
 *
 * 예전에는 '여러 벌 한꺼번에 입어보기'가 장바구니에 있었다. 그래서 입어보려고 사지도 않을 옷을
 * 장바구니에 담아야 했고, 장바구니에 '살 것'과 '입어볼 것'이 섞였다.
 * 이제 장바구니는 구매만, 여기는 입어보기만 맡는다.
 */

// 한 번에 입어볼 수 있는 옷 수 — 백엔드 MAX_LAYERS·스마트앱과 같은 값.
// 우리가 파는 옷은 상의·하의·아우터·원피스뿐이라(신발·가방 없음) 자리가 안 겹치는 최대 조합이
// '상의+하의+아우터=3벌'이다. 4벌째부터는 같은 자리에 옷이 겹쳐 렌더가 망가진다.
const FITROOM_MAX_FIT = 3;

function FitRoomScreen({ go, openProduct, auth, toast }) {
  const [lines, setLines] = React.useState(null);   // null = 로딩중
  const [picked, setPicked] = React.useState([]);   // 고른 줄의 서버 id
  const [fitting, setFitting] = React.useState(false);
  const [result, setResult] = React.useState(null); // {url, worn}

  // 목록 불러오기 — 다른 화면(상세)에서 담아도 이 화면이 다시 뜰 때 최신으로 맞춘다.
  // 게스트도 담은 줄이 보인다(브라우저 보관) — 가입 유도는 '입어보기' 누르는 순간에 한다.
  const reload = React.useCallback(() => {
    API.fitRoom().then((d) => setLines((d && d.items) || [])).catch(() => setLines([]));
  }, [auth && auth.loggedIn]);

  React.useEffect(() => { reload(); }, [reload]);
  // 상세에서 담았을 때 배지·목록이 곧바로 따라오도록 전역 훅을 열어둔다.
  React.useEffect(() => {
    window.denkyRefreshFitRoom = reload;
    return () => { if (window.denkyRefreshFitRoom === reload) window.denkyRefreshFitRoom = null; };
  }, [reload]);

  function togglePick(id) {
    setPicked((cur) => (cur.includes(id) ? cur.filter((x) => x !== id) : cur.concat([id])));
  }

  async function removeLine(id) {
    try {
      const d = await API.removeFromFitRoom(id);
      setLines((d && d.items) || []);
      setPicked((cur) => cur.filter((x) => x !== id));
    } catch (e) { if (toast) toast((e && e.message) || "빼지 못했어요"); }
  }

  async function clearAll() {
    if (!window.confirm("담아둔 옷을 전부 뺄까요?\n장바구니와 찜은 그대로 있어요.")) return;
    try {
      const d = await API.clearFitRoom();
      setLines((d && d.items) || []);
      setPicked([]);
      if (toast) toast("피팅룸을 비웠어요");
    } catch (e) { if (toast) toast((e && e.message) || "비우지 못했어요"); }
  }

  // 고른 옷들을 한꺼번에 입어본다. (겹쳐 입기 — 피팅 횟수는 1회만 든다)
  async function fitPicked() {
    if (!picked.length) return;
    if (picked.length > FITROOM_MAX_FIT) {
      if (toast) toast(`한 번에 최대 ${FITROOM_MAX_FIT}벌까지 입어볼 수 있어요`);
      return;
    }
    // 피팅은 회원 기능 — 담기는 게스트도 되지만, 입어보는 순간 가입을 권한다(가입하면 무료 피팅 제공).
    if (!auth || !auth.loggedIn) {
      if (toast) toast("회원가입하면 무료 피팅으로 바로 입어볼 수 있어요");
      go("signup");
      return;
    }
    if (!auth.hasBase) {
      if (toast) toast("피팅에 쓸 아바타를 먼저 만들어 주세요");
      go("mypage", { tab: "profile" });
      return;
    }
    // 겹쳐 입는 순서가 결과를 좌우해서 상의·원피스 → 하의 → 아우터 순으로 보낸다.
    const rank = (l) => ({ "상의": 0, "원피스": 0, "하의": 1, "아우터": 2 }[l.product.category] ?? 3);
    const worn = lines.filter((l) => picked.includes(l.id)).slice().sort((a, b) => rank(a) - rank(b));
    setFitting(true);
    try {
      const rec = await API.tryon({
        productIds: worn.map((l) => l.product.id),
        userImage: auth.baseImage,
        // 담을 때 고른 색 — 백엔드가 색만 뽑아 각 옷을 그 색으로 렌더한다.
        colors: worn.map((l) => (l.selected_options ? Object.values(l.selected_options).join(" ") : null)),
      });
      setFitting(false);
      setPicked([]);
      setResult({ url: rec.result_url, worn: worn.map((l) => API.normalize(l.product)) });
    } catch (e) {
      setFitting(false);
      if (toast) toast(e && e.status === 401 ? "로그인이 필요해요. 다시 로그인해 주세요."
        : ((e && e.message) || "피팅 중 문제가 생겼어요. 잠시 후 다시 시도해 주세요."));
    }
  }

  if (lines === null) {
    return (
      <div style={{ display: "grid", placeItems: "center", padding: "80px 0" }}>
        <div className="spinner spinner-dark" style={{ width: 34, height: 34 }}></div>
      </div>
    );
  }

  return (
    <div className="wrap" style={{ paddingTop: 20, paddingBottom: 60 }}>
      <div className="row" style={{ justifyContent: "space-between", alignItems: "center", marginBottom: 6 }}>
        <h1 className="t-h1" style={{ margin: 0 }}>피팅룸{lines.length ? ` ${lines.length}` : ""}</h1>
        {lines.length > 0 && (
          <button type="button" onClick={clearAll}
            style={{ border: 0, background: "none", cursor: "pointer", fontSize: 13, color: "var(--sub)" }}>비우기</button>
        )}
      </div>

      {lines.length === 0 ? (
        <div className="empty">
          <div className="ill"><Icon name="sparkle" size={48} stroke={1.4} /></div>
          <h3 className="t-h2" style={{ margin: "0 0 8px" }}>피팅룸이 비어 있어요</h3>
          <p className="t-body t-sub" style={{ margin: "0 0 24px" }}>
            상품에서 [피팅룸에 담기]를 누르면<br />여기서 여러 벌을 한꺼번에 입어볼 수 있어요.
          </p>
          <Btn variant="primary" onClick={() => go("catalog")}>옷 보러 가기</Btn>
        </div>
      ) : (
        <>
          <p className="t-small t-sub" style={{ margin: "0 0 10px" }}>
            입어볼 옷을 골라 주세요 (최대 {FITROOM_MAX_FIT}벌 · 피팅 1회 차감)
          </p>
          <FitDisclaimer />
          <div className="stack" style={{ gap: 10 }}>
            {lines.map((l) => {
              const np = API.normalize(l.product);
              const on = picked.includes(l.id);
              const optText = l.selected_options ? Object.values(l.selected_options).join(" / ") : null;
              return (
                <div key={l.id} className="row" style={{ gap: 10, alignItems: "center", padding: 10,
                  background: "#fff", borderRadius: 14, border: `1px solid ${on ? "var(--primary)" : "var(--border)"}` }}>
                  <button type="button" onClick={() => togglePick(l.id)} aria-label="고르기"
                    style={{ width: 26, height: 26, flex: "none", borderRadius: "50%", cursor: "pointer",
                      border: `1.6px solid ${on ? "var(--primary)" : "var(--border)"}`,
                      background: on ? "var(--primary)" : "#fff", color: "#fff", fontSize: 14, fontWeight: 800,
                      display: "grid", placeItems: "center" }}>{on ? "✓" : ""}</button>
                  <img src={np.image} alt="" onClick={() => openProduct(np)}
                    style={{ width: 52, height: 66, flex: "none", objectFit: "cover", borderRadius: 8, cursor: "pointer" }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <p className="t-small" style={{ margin: 0, color: "var(--ink)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{np.name}</p>
                    {optText && <p className="t-caption t-sub" style={{ margin: "3px 0 0" }}>{optText}</p>}
                  </div>
                  <button type="button" onClick={() => removeLine(l.id)} aria-label="빼기"
                    style={{ border: 0, background: "none", cursor: "pointer", fontSize: 16, color: "var(--sub)", padding: 6 }}>✕</button>
                </div>
              );
            })}
          </div>

          <div style={{ marginTop: 18 }}>
            {fitting ? (
              <div style={{ padding: "26px 0", border: "1px solid var(--border)", borderRadius: 14, background: "#fff", display: "grid", placeItems: "center" }}>
                <div className="spinner spinner-dark" style={{ width: 28, height: 28 }}></div>
                <p className="t-small" style={{ margin: "12px 0 2px", fontWeight: 600, color: "var(--ink)" }}>고른 옷을 입혀보는 중이에요…</p>
                <p className="t-caption t-sub" style={{ margin: 0 }}>30초쯤 걸려요</p>
              </div>
            ) : (
              <div className="row" style={{ gap: 10 }}>
                <Btn variant="primary" size="lg" block disabled={!picked.length} onClick={fitPicked} style={{ flex: 1 }}>
                  {picked.length ? `${picked.length}벌 한꺼번에 입어보기` : "입어볼 옷을 골라 주세요"}
                </Btn>
                {picked.length > 0 && (
                  <Btn variant="ghost" size="lg" onClick={() => setPicked([])}>해제</Btn>
                )}
              </div>
            )}
          </div>
        </>
      )}

      {/* 합성 결과 — 큰 이미지 + 입은 옷별 사러가기 */}
      {result && (
        <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,.9)", display: "grid", placeItems: "center", zIndex: 1000, padding: 20 }}
          onClick={() => setResult(null)}>
          <div onClick={(e) => e.stopPropagation()} style={{ textAlign: "center" }}>
            <img src={result.url} alt="피팅 결과" style={{ maxWidth: "min(92vw, 520px)", maxHeight: "70vh", borderRadius: 14, objectFit: "contain" }} />
            {/* ★사러가기 바로 위★ — 사기로 마음먹기 직전에 사이즈표를 떠올리게 한다 */}
            <FitDisclaimer compact onDark />
            <div className="stack" style={{ gap: 8, marginTop: 6 }}>
              {result.worn.map((wp) => (
                <Btn key={wp.id} variant="outline" block onClick={() => { setResult(null); openProduct(wp); }}>
                  {wp.name} 사러가기
                </Btn>
              ))}
              <Btn variant="primary" block onClick={() => setResult(null)}>닫기</Btn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
