// KASHA — 굿즈 폼 상세 (폼 소개 + 상품 리스트 + 임시 장바구니 → 한 번에 결제)
// 수량 조절·담기는 전부 이 페이지 안에서 처리하고, '결제하기'를 눌러야만 결제 페이지로 이동해요.
const LOW_STOCK = 5;   // 재고 부족 임계값

function GoodsDetailScreen({ formId, onNavigate }) {
  const { Button, Icon } = window.DS;
  window.KASHADB.useStore();
  const f = (window.KASHADB.getGoodsForms() || []).filter((x) => x.id === formId)[0];
  const [active, setActive] = React.useState(0);   // 갤러리 선택 이미지
  const [cart, setCart] = React.useState({});       // 임시 장바구니 { productId: qty } — 세션(언마운트 시 초기화)

  if (!f) {
    return (
      <div style={{ maxWidth: 720, margin: "0 auto", padding: "80px 24px", textAlign: "center" }}>
        <h2 style={{ fontSize: "var(--text-title-2)" }}>상품을 찾을 수 없어요</h2>
        <div style={{ marginTop: 20 }}><Button variant="primary" onClick={() => onNavigate("goods")}>굿즈 상품으로</Button></div>
      </div>
    );
  }
  const status = window.KASHAGoods.effStatus(f);
  const purchasable = status === "open";
  const images = (f.images || []);
  const cover = images[active] || images[0] || "";
  const products = (f.products || []).slice().sort((a, z) => (a.order || 0) - (z.order || 0));
  const won = (n) => (window.won ? window.won(n) : n);

  const capOf = (p) => {
    const stock = p.stock != null ? p.stock : 9999;
    const lim = p.perLimit && p.perLimit > 0 ? p.perLimit : 9999;
    return Math.max(0, Math.min(stock, lim));
  };
  const setQty = (p, next) => {
    const q = Math.max(0, Math.min(capOf(p), next));
    setCart((c) => { const n = Object.assign({}, c); if (q <= 0) delete n[p.id]; else n[p.id] = q; return n; });
  };

  const items = products.map((p) => ({ p, qty: cart[p.id] || 0 })).filter((x) => x.qty > 0);
  const totalQty = items.reduce((s, x) => s + x.qty, 0);
  const totalAmount = items.reduce((s, x) => s + (parseInt(x.p.price, 10) || 0) * x.qty, 0);

  const checkout = () => {
    if (!purchasable || totalQty === 0) return;
    // 결제하기 눌렀을 때만 이동 — 장바구니를 결제 페이지로 전달
    onNavigate("goodsPay", { formId: f.id, cart: items.map((x) => ({ productId: x.p.id, qty: x.qty })) });
  };

  return (
    <div style={{ maxWidth: 1000, margin: "0 auto", padding: "40px 24px 120px" }}>
      <button onClick={() => onNavigate("goods")} style={{ border: "none", background: "transparent", color: "var(--text-tertiary)", fontSize: 14, cursor: "pointer", fontFamily: "var(--font-sans)", display: "flex", alignItems: "center", gap: 6, marginBottom: 20 }}>
        <Icon name="chevronLeft" size={18} /> 굿즈 상품
      </button>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0,1.05fr) minmax(0,1fr)", gap: 40, alignItems: "start" }} className="kgd-grid">
        <div>
          <div style={{ width: "100%", aspectRatio: "3/4", borderRadius: 20, overflow: "hidden", background: "var(--gray-100)" }}>
            {cover ? <img src={cover} alt={f.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : null}
          </div>
          {images.length > 1 && (
            <div style={{ display: "flex", gap: 8, marginTop: 10, flexWrap: "wrap" }}>
              {images.map((u, i) => (
                <button key={i} onClick={() => setActive(i)} style={{ width: 48, height: 64, borderRadius: 8, overflow: "hidden", border: "2px solid " + (i === active ? "var(--ink)" : "transparent"), background: "var(--gray-100)", cursor: "pointer", padding: 0 }}>
                  <img src={u} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                </button>
              ))}
            </div>
          )}
        </div>
        <div>
          {/* 생성자 = 코스어 닉네임 + 프로필 사진 */}
          <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
            <span style={{ width: 32, height: 32, borderRadius: "50%", overflow: "hidden", background: "var(--gray-200)", flexShrink: 0 }}>{f.cosplayerAvatar ? <img src={f.cosplayerAvatar} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : null}</span>
            <span style={{ fontSize: 14, fontWeight: 700, color: "var(--text-secondary)" }}>{f.cosplayerName || "코스어"}</span>
          </div>
          <h1 style={{ fontSize: "var(--text-title-2)", letterSpacing: "var(--tracking-title)", marginTop: 14, lineHeight: 1.3 }}>{f.name}</h1>
          <StatusBanner f={f} status={status} />
          {f.desc && <p style={{ marginTop: 16, color: "var(--text-body)", fontSize: 15, lineHeight: 1.7, whiteSpace: "pre-wrap" }}>{f.desc}</p>}
        </div>
      </div>

      {/* 상품 리스트 (그리드 → 리스트) */}
      <div style={{ marginTop: 40 }}>
        <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
          <h2 style={{ fontSize: "var(--text-title-3)", letterSpacing: "var(--tracking-title)" }}>상품</h2>
          <span style={{ fontSize: 13, color: "var(--text-tertiary)" }}>{purchasable ? "수량을 담아 한 번에 결제해요" : status === "scheduled" ? "오픈 전이에요" : "판매가 마감됐어요"}</span>
        </div>
        {products.length === 0 ? (
          <div style={{ marginTop: 16, padding: "30px 16px", textAlign: "center", background: "var(--gray-50)", borderRadius: 14, color: "var(--text-tertiary)", fontSize: 14 }}>아직 등록된 상품이 없어요.</div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 16 }}>
            {products.map((p) => <ProductRow key={p.id} p={p} qty={cart[p.id] || 0} cap={capOf(p)} purchasable={purchasable} won={won} onQty={(n) => setQty(p, n)} />)}
          </div>
        )}
      </div>

      {/* 특전 — 담는 즉시 달성 여부가 실시간으로 강조돼요 */}
      <window.GoodsPerkBoard form={f} cart={cart} amount={totalAmount} />

      {/* 선택 합계 — 실시간. '결제하기'만 페이지 이동 */}
      {purchasable && (
        <div style={{ position: "sticky", bottom: 0, marginTop: 24, background: "var(--gray-0)", borderTop: "1px solid var(--border-subtle)", padding: "16px 0", zIndex: 5 }}>
          <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 16, flexWrap: "wrap" }}>
            <div>
              <div style={{ fontSize: 13, color: "var(--text-tertiary)" }}>선택 {totalQty}개</div>
              <div style={{ fontSize: 24, fontWeight: 800, color: "var(--text-strong)" }}>{won(totalAmount)}<span style={{ fontSize: 15, fontWeight: 600 }}>원</span></div>
            </div>
            <div style={{ minWidth: 200, flex: "0 1 320px" }}>
              <Button variant="primary" size="lg" fullWidth disabled={totalQty === 0} onClick={checkout}>{totalQty === 0 ? "상품을 담아주세요" : "결제하기"}</Button>
            </div>
          </div>
          <p style={{ marginTop: 8, fontSize: 12, color: "var(--text-tertiary)", textAlign: "center" }}>결제는 계좌이체로 진행돼요. 입금 확인 후 배송·전달이 시작돼요.</p>
        </div>
      )}
      <style>{`@media(max-width:760px){.kgd-grid{grid-template-columns:1fr !important;gap:24px !important}}`}</style>
    </div>
  );
}

// 상태 배너 — 예약(카운트다운)/마감 안내
function StatusBanner({ f, status }) {
  if (status === "scheduled") {
    return (
      <div style={{ marginTop: 12, padding: "12px 16px", borderRadius: 12, background: "var(--blue-50)", display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ fontSize: 13, fontWeight: 700, color: "var(--blue-600)" }}>오픈 예정</span>
        {f.openAt && <DetailCountdown openAt={f.openAt} />}
      </div>
    );
  }
  if (status === "closed") {
    return <div style={{ marginTop: 12, padding: "10px 16px", borderRadius: 12, background: "var(--red-50)", fontSize: 13, fontWeight: 700, color: "var(--red-500)" }}>판매가 마감됐어요</div>;
  }
  return <div style={{ marginTop: 10, display: "inline-flex", fontSize: 13, fontWeight: 600, color: "var(--blue-600)", background: "var(--blue-50)", padding: "6px 12px", borderRadius: 999 }}>{window.KASHAGoods.closeLabel(f)}</div>;
}
function DetailCountdown({ openAt }) {
  const target = React.useMemo(() => Date.parse(openAt), [openAt]);
  const [now, setNow] = React.useState(Date.now());
  React.useEffect(() => { const id = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(id); }, []);
  const diff = target - now;
  if (isNaN(target)) return null;
  if (diff <= 0) return <span style={{ fontSize: 13, fontWeight: 700, color: "var(--green-500)" }}>지금 오픈됐어요 · 새로고침</span>;
  const s = Math.floor(diff / 1000), d = Math.floor(s / 86400), h = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
  const pad = (n) => String(n).padStart(2, "0");
  return <span style={{ fontSize: 13.5, fontWeight: 700, color: "var(--blue-600)", fontVariantNumeric: "tabular-nums" }}>{d > 0 ? "D-" + d + " " : ""}{pad(h)}:{pad(m)}:{pad(sec)} 후 오픈</span>;
}

// 상품 행 — 재고 상태 표현 + 수량 스테퍼
function ProductRow({ p, qty, cap, purchasable, won, onQty }) {
  const { Icon } = window.DS;
  const shipText = { digital: "디지털", ship: "실물 배송", handoff: "실물 전달" };
  const shipList = (Array.isArray(p.shipTypes) && p.shipTypes.length ? p.shipTypes : [p.shipType || "ship"]);
  const shipLabelText = shipList.map((v) => shipText[v] || v).join(" · ");   // 복수 배송 방식 표시
  const soldOut = p.stock != null && p.stock <= 0;
  const low = !soldOut && p.stock != null && p.stock <= LOW_STOCK;
  const disabled = soldOut || !purchasable;
  const border = soldOut ? "1.5px solid var(--border-default)" : low ? "1.5px solid var(--red-400, var(--red-500))" : "1px solid var(--border-subtle)";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 14px", borderRadius: 16, border: border, background: soldOut ? "var(--gray-50)" : "var(--gray-0)", opacity: soldOut ? 0.7 : 1 }}>
      <div style={{ width: 72, height: 96, borderRadius: 12, overflow: "hidden", background: "var(--gray-100)", flexShrink: 0, filter: soldOut ? "grayscale(1)" : "none" }}>
        {(p.images || [])[0] ? <img src={p.images[0]} alt={p.name} style={{ width: "100%", height: "100%", objectFit: "cover" }} /> : null}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
          <span style={{ fontSize: 11.5, fontWeight: 700, color: "var(--blue-600)", background: "var(--blue-50)", padding: "2px 8px", borderRadius: 999 }}>{p.kind}</span>
          <span style={{ fontSize: 11.5, fontWeight: 600, color: "var(--text-tertiary)" }}>{shipLabelText || "배송"}</span>
        </div>
        <div style={{ marginTop: 6, fontSize: 15, fontWeight: 700, color: "var(--text-strong)", lineHeight: 1.35 }}>{p.name}</div>
        <div style={{ marginTop: 3, display: "flex", alignItems: "center", gap: 8 }}>
          <span style={{ fontSize: 15.5, fontWeight: 800 }}>{won(p.price)}<span style={{ fontSize: 12, fontWeight: 600 }}>원</span></span>
          {soldOut ? <span style={{ fontSize: 12.5, fontWeight: 800, color: "var(--gray-500)" }}>품절</span>
            : <span style={{ fontSize: 12.5, fontWeight: low ? 800 : 600, color: low ? "var(--red-500)" : "var(--text-tertiary)" }}>재고 {p.stock}{low ? " · 마감 임박" : ""}{p.perLimit ? " · 1인 " + p.perLimit + "개" : ""}</span>}
        </div>
      </div>
      {/* 수량 스테퍼 — 품절/오픈전이면 비활성 */}
      <div style={{ flexShrink: 0 }}>
        {disabled ? (
          <span style={{ fontSize: 12.5, fontWeight: 700, color: "var(--gray-400)" }}>{soldOut ? "품절" : "—"}</span>
        ) : (
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <button onClick={() => onQty(qty - 1)} disabled={qty <= 0} style={stepBtn(qty <= 0)} aria-label="빼기">−</button>
            <span style={{ fontSize: 16, fontWeight: 700, minWidth: 22, textAlign: "center" }}>{qty}</span>
            <button onClick={() => onQty(qty + 1)} disabled={qty >= cap} style={stepBtn(qty >= cap)} aria-label="더하기">+</button>
          </div>
        )}
      </div>
    </div>
  );
}
function stepBtn(dis) { return { width: 34, height: 34, borderRadius: 9, border: "1.5px solid var(--border-default)", background: "#fff", fontSize: 18, fontWeight: 700, cursor: dis ? "not-allowed" : "pointer", color: dis ? "var(--gray-300)" : "var(--text-strong)", lineHeight: 1 }; }
window.GoodsDetailScreen = GoodsDetailScreen;
