// app-flow.jsx — Cart, Checkout, KakaoPay, Complete, GroupOrder, MyPage
const lineSum = (cart) => cart.reduce((s, i) => s + i.unit * i.qty, 0);
const qtySum = (cart) => cart.reduce((s, i) => s + i.qty, 0);

// ============ CART ============
function CartScreen({ go, cart, setQty, removeItem }) {
  const total = lineSum(cart);
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#F4F1EA' }}>
      <AppHeader title={`장바구니 ${cart.length ? `(${cart.length})` : ''}`} onBack={() => go('home')} />
      {cart.length === 0 ? (
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 16, fontFamily: 'Noto Serif KR' }}>
          <Star size={54} fill="#E7E0D2" />
          <div style={{ fontSize: 15, color: T.muted, fontWeight: 600 }}>장바구니가 비어 있어요</div>
          <Press onClick={() => go('home')} style={{ background: T.yellow, color: T.ink, fontWeight: 800, fontSize: 14.5, padding: '13px 26px', borderRadius: 26 }}>무대의상 보러가기</Press>
        </div>
      ) : (
        <>
          <div style={{ flex: 1, overflow: 'auto', padding: '14px 16px 8px' }}>
            {cart.map((it, idx) => (
              <div key={idx} style={{ display: 'flex', gap: 13, background: '#FBFAF6', borderRadius: 16, padding: 12, marginBottom: 12, boxShadow: '0 3px 10px rgba(0,0,0,.05)', fontFamily: 'Noto Serif KR' }}>
                <div style={{ width: 78, height: 78, flex: '0 0 78px', borderRadius: 12, background: it.img ? `#222 url("${it.img}") center 24%/cover` : it.grad }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
                    <div style={{ fontSize: 14, fontWeight: 700, color: T.ink, lineHeight: 1.3 }}>{it.name}</div>
                    <Press onClick={() => removeItem(idx)} style={{ flex: '0 0 auto', padding: 2 }}><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={T.muted} strokeWidth="2"><path d="M18 6 6 18M6 6l12 12"/></svg></Press>
                  </div>
                  <div style={{ fontSize: 12, color: T.muted, marginTop: 4, fontWeight: 600 }}>{COL[it.color].name} · {it.size}</div>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 8 }}>
                    <Stepper value={it.qty} setValue={(v) => setQty(idx, v)} min={1} />
                    <span style={{ fontFamily: '"Noto Serif KR"', fontSize: 13, color: T.gold, whiteSpace: 'nowrap' }}>제작 문의</span>
                  </div>
                </div>
              </div>
            ))}
            <div style={{ background: '#FBFAF6', borderRadius: 16, padding: 16, fontFamily: 'Noto Serif KR' }}>
              {[['상품 수', `${qtySum(cart)}벌`], ['예상 금액', '카톡 견적'], ['배송비', '무료']].map((r, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}><span style={{ fontSize: 13.5, color: T.sub }}>{r[0]}</span><span style={{ fontSize: 13.5, fontWeight: 700, color: r[1] === '카톡 견적' ? T.gold : T.ink }}>{r[1]}</span></div>
              ))}
              <div style={{ fontSize: 11.5, color: T.muted, paddingTop: 8, borderTop: `1px solid ${T.line}`, lineHeight: 1.6 }}>맞춤 제작 상품입니다. 정확한 금액은 원단·디테일·치수에 따라 카톡 1:1 상담에서 안내드려요.</div>
            </div>
          </div>
          <div style={{ flex: '0 0 auto', borderTop: `1px solid ${T.line}`, background: '#FBFAF6', padding: '12px 14px' }}>
            <Press onClick={() => go('checkout')} style={{ textAlign: 'center', padding: '16px', borderRadius: 14, background: T.yellow, color: T.ink, fontSize: 16, fontWeight: 800, fontFamily: 'Noto Serif KR' }}>견적·주문 문의하기 · {qtySum(cart)}벌</Press>
          </div>
        </>
      )}
    </div>
  );
}

// ============ CHECKOUT ============
function CheckoutScreen({ go, cart, user, login, placeOrder, toast }) {
  const total = lineSum(cart);

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#F4F1EA' }}>
      <AppHeader title="주문 · 견적 문의" onBack={() => go('cart')} />
      <div style={{ flex: 1, overflow: 'auto', padding: '14px 16px 8px', fontFamily: 'Noto Serif KR' }}>
        {/* login gate */}
        {!user ? (
          <div style={{ background: '#FBFAF6', borderRadius: 18, padding: 20, marginBottom: 14, textAlign: 'center', border: `2px solid ${T.kakao}` }}>
            <Star size={34} fill={T.deep} />
            <div style={{ fontSize: 16.5, fontWeight: 800, color: T.ink, marginTop: 10 }}>회원가입 없이 바로 시작</div>
            <div style={{ fontSize: 13, color: T.sub, marginTop: 6, lineHeight: 1.55 }}>카카오 계정으로 로그인하면<br/>배송지·연락처를 자동으로 불러와요.</div>
            <Press onClick={login} style={{ marginTop: 16 }}>
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, background: T.kakao, borderRadius: 12, padding: '15px' }}>
                <svg width="20" height="20" viewBox="0 0 24 24"><path d="M12 3C6.5 3 2 6.6 2 11c0 2.8 1.9 5.3 4.7 6.7l-1 3.6c-.1.4.3.7.6.5l4.3-2.8c.4 0 .9.1 1.4.1 5.5 0 10-3.6 10-8s-4.5-8-10-8Z" fill="#3C1E1E"/></svg>
                <span style={{ fontSize: 15.5, fontWeight: 800, color: T.kakaoInk }}>카카오로 시작하기</span>
              </div>
            </Press>
          </div>
        ) : (
          <div style={{ background: '#FBFAF6', borderRadius: 16, padding: 16, marginBottom: 14 }}>
            <SectionTitle>배송지</SectionTitle>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ fontSize: 14.5, fontWeight: 800, color: T.ink }}>{user.name}</span>
              <span style={{ fontSize: 11, fontWeight: 700, color: T.deep, background: '#EFEAE0', padding: '2px 7px', borderRadius: 6 }}>카카오 연동</span>
            </div>
            <div style={{ fontSize: 13.5, color: T.sub, marginTop: 6, lineHeight: 1.5 }}>{user.phone}<br/>{user.addr}</div>
            <Press onClick={() => toast('카카오 주소록에서 배송지를 변경할 수 있어요')} style={{ marginTop: 10, fontSize: 13, fontWeight: 700, color: T.deep }}>배송지 변경 ›</Press>
          </div>
        )}

        {/* order items */}
        <div style={{ background: '#FBFAF6', borderRadius: 16, padding: 16, marginBottom: 14 }}>
          <SectionTitle>주문상품 {cart.length}건</SectionTitle>
          {cart.map((it, i) => (
            <div key={i} style={{ display: 'flex', gap: 12, padding: '10px 0', borderTop: i ? `1px solid ${T.line}` : 'none' }}>
              <div style={{ width: 52, height: 52, borderRadius: 10, background: it.img ? `#222 url("${it.img}") center 24%/cover` : it.grad, flex: '0 0 52px' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13.5, fontWeight: 700, color: T.ink, lineHeight: 1.3 }}>{it.name}</div>
                <div style={{ fontSize: 12, color: T.muted, marginTop: 3 }}>{COL[it.color].name} · {it.size} · {it.qty}벌</div>
              </div>
              <span style={{ fontSize: 12.5, fontWeight: 700, color: T.gold, alignSelf: 'center', whiteSpace: 'nowrap' }}>제작 문의</span>
            </div>
          ))}
        </div>

        {/* 진행 안내 */}
        <div style={{ background: '#FBFAF6', borderRadius: 16, padding: 16, marginBottom: 14 }}>
          <SectionTitle>견적 · 결제 안내</SectionTitle>
          <div style={{ display: 'flex', alignItems: 'center', gap: 11, padding: '13px 14px', borderRadius: 12, border: `2px solid ${T.ink}`, background: '#FFFDF5' }}>
            <div style={{ width: 38, height: 38, borderRadius: 9, background: T.kakao, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <svg width="22" height="22" viewBox="0 0 24 24"><path d="M12 3C6.5 3 2 6.6 2 11c0 2.8 1.9 5.3 4.7 6.7l-1 3.6c-.1.4.3.7.6.5l4.3-2.8c.4 0 .9.1 1.4.1 5.5 0 10-3.6 10-8s-4.5-8-10-8Z" fill="#3C1E1E"/></svg>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14.5, fontWeight: 800, color: T.ink }}>카카오톡 1:1 견적</div>
              <div style={{ fontSize: 12, color: T.muted, marginTop: 2 }}>치수·원단 확정 후 결제 안내</div>
            </div>
          </div>
          <div style={{ fontSize: 11.5, color: T.muted, marginTop: 10, lineHeight: 1.5 }}>맞춤제작 상품은 카톡 상담에서 디테일·치수를 확정한 뒤 최종 견적과 결제(계좌이체·카드)를 안내드립니다.</div>
        </div>

        {/* 견적 요약 */}
        <div style={{ background: '#FBFAF6', borderRadius: 16, padding: 16 }}>
          {[['주문 상품', `${cart.length}종 ${qtySum(cart)}벌`], ['예상 금액', '카톡 견적'], ['배송비', '무료']].map((r, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}><span style={{ fontSize: 13.5, color: T.sub }}>{r[0]}</span><span style={{ fontSize: 13.5, fontWeight: 700, color: r[1] === '카톡 견적' ? T.gold : T.ink }}>{r[1]}</span></div>
          ))}
        </div>
      </div>

      {/* CTA */}
      <div style={{ flex: '0 0 auto', borderTop: `1px solid ${T.line}`, background: '#FBFAF6', padding: '12px 14px' }}>
        <Press onClick={() => user ? placeOrder() : login()} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '16px', borderRadius: 14, background: T.kakao, fontFamily: 'Noto Serif KR' }}>
          <svg width="20" height="20" viewBox="0 0 24 24"><path d="M12 3C6.5 3 2 6.6 2 11c0 2.8 1.9 5.3 4.7 6.7l-1 3.6c-.1.4.3.7.6.5l4.3-2.8c.4 0 .9.1 1.4.1 5.5 0 10-3.6 10-8s-4.5-8-10-8Z" fill="#3C1E1E"/></svg>
          <span style={{ fontSize: 16, fontWeight: 800, color: T.kakaoInk }}>{user ? '카카오톡으로 견적·주문 보내기' : '카카오로 시작하기'}</span>
        </Press>
      </div>
    </div>
  );
}

function SectionTitle({ children }) {
  return <div style={{ fontSize: 13, fontWeight: 800, color: T.muted, marginBottom: 12, letterSpacing: 0.2 }}>{children}</div>;
}

// ============ KAKAOPAY SHEET ============
function KakaoPaySheet({ open, onClose, amount, user, onPaid }) {
  const [stage, setStage] = React.useState('confirm'); // confirm | auth | done
  React.useEffect(() => { if (open) setStage('confirm'); }, [open]);

  const auth = () => { setStage('auth'); setTimeout(() => { setStage('done'); setTimeout(onPaid, 850); }, 1100); };

  return (
    <Sheet open={open} onClose={stage === 'confirm' ? onClose : undefined} pad={false}>
      <div style={{ fontFamily: 'Noto Serif KR' }}>
        {/* kakao header */}
        <div style={{ background: T.kakao, padding: '16px 20px 18px', display: 'flex', alignItems: 'center', gap: 8 }}>
          <svg width="24" height="24" viewBox="0 0 24 24"><path d="M12 3C6.5 3 2 6.6 2 11c0 2.8 1.9 5.3 4.7 6.7l-1 3.6c-.1.4.3.7.6.5l4.3-2.8c.4 0 .9.1 1.4.1 5.5 0 10-3.6 10-8s-4.5-8-10-8Z" fill="#3C1E1E"/></svg>
          <span style={{ fontSize: 17, fontWeight: 800, color: T.kakaoInk }}>pay</span>
        </div>
        <div style={{ padding: '22px 22px 24px' }}>
          {stage === 'done' ? (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div style={{ width: 66, height: 66, borderRadius: 33, background: '#1F9E7A', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><svg width="34" height="34" viewBox="0 0 24 24" fill="none" stroke="#FBFAF6" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="m5 12 5 5 9-11"/></svg></div>
              <div style={{ fontSize: 18, fontWeight: 800, color: T.ink, marginTop: 16 }}>결제 완료</div>
              <div style={{ fontSize: 14, color: T.muted, marginTop: 6 }}>{KRW(amount)} 결제되었습니다</div>
            </div>
          ) : (
            <>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 13, color: T.muted, fontWeight: 600 }}>STAR 무대의상</div>
                <div style={{ fontFamily: '"Noto Serif KR"', fontSize: 34, color: T.ink, marginTop: 6 }}>{KRW(amount)}</div>
              </div>
              <div style={{ background: '#F7F4EE', borderRadius: 14, padding: '14px 16px', marginTop: 20 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <span style={{ fontSize: 13, color: T.muted, fontWeight: 600 }}>결제수단</span>
                  <span style={{ fontSize: 14, fontWeight: 800, color: T.ink }}>카카오페이 머니</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 12 }}>
                  <span style={{ fontSize: 13, color: T.muted, fontWeight: 600 }}>잔액</span>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: T.sub, whiteSpace: 'nowrap' }}>1,240,000원</span>
                </div>
              </div>
              {stage === 'auth' ? (
                <div style={{ textAlign: 'center', marginTop: 26, padding: '10px 0' }}>
                  <div style={{ width: 40, height: 40, border: `3px solid ${T.kakao}`, borderTopColor: 'transparent', borderRadius: 20, margin: '0 auto', animation: 'starspin .8s linear infinite' }} />
                  <div style={{ fontSize: 14, color: T.sub, fontWeight: 600, marginTop: 14 }}>인증하는 중…</div>
                </div>
              ) : (
                <Press onClick={auth} style={{ marginTop: 22, textAlign: 'center', padding: '16px', borderRadius: 14, background: T.kakaoInk }}>
                  <span style={{ fontSize: 16, fontWeight: 800, color: '#FBFAF6' }}>지문으로 결제하기</span>
                </Press>
              )}
              <div style={{ fontSize: 11, color: T.muted, textAlign: 'center', marginTop: 12, lineHeight: 1.5 }}>카드 등록·계좌 입력 없이 카카오페이로 안전하게 결제됩니다.</div>
            </>
          )}
        </div>
      </div>
    </Sheet>
  );
}

// ============ COMPLETE ============
function CompleteScreen({ go, order, toast }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', background: '#F4F1EA', fontFamily: 'Noto Serif KR' }}>
      <div style={{ flex: 1, overflow: 'auto', padding: '40px 20px 20px', textAlign: 'center' }}>
        <div style={{ position: 'relative', width: 92, height: 92, margin: '0 auto' }}>
          <div style={{ position: 'absolute', inset: 0, borderRadius: 46, background: 'radial-gradient(circle, rgba(224,168,46,.45), transparent 70%)' }} />
          <div style={{ position: 'relative', width: 92, height: 92, display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Star size={88} fill="#E0A82E" glow="rgba(224,168,46,.6)" /></div>
        </div>
        <div style={{ fontFamily: '"Noto Serif KR"', fontSize: 26, color: T.ink, marginTop: 18 }}>주문 완료!</div>
        <div style={{ fontSize: 14, color: T.sub, marginTop: 8, lineHeight: 1.6 }}>이제 무대 위에서 별처럼 빛날 일만 남았어요.<br/>제작 진행상황은 카카오톡으로 안내드릴게요.</div>

        <div style={{ background: '#FBFAF6', borderRadius: 18, padding: 18, marginTop: 24, textAlign: 'left', boxShadow: '0 4px 14px rgba(0,0,0,.05)' }}>
          {[['주문번호', order.no], ['결제금액', KRW(order.total)], ['상품', `${order.first}${order.count > 1 ? ` 외 ${order.count - 1}건` : ''}`], ['예상 제작·배송', order.eta]].map((r, i) => (
            <div key={i} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '9px 0', borderTop: i ? `1px solid ${T.line}` : 'none' }}>
              <span style={{ fontSize: 13, color: T.muted, fontWeight: 600, flex: '0 0 auto' }}>{r[0]}</span>
              <span style={{ fontSize: 13.5, fontWeight: 700, color: T.ink, textAlign: 'right' }}>{r[1]}</span>
            </div>
          ))}
        </div>

        <div style={{ background: '#FBFAF6', border: `1.5px dashed ${T.deep}`, borderRadius: 16, padding: 16, marginTop: 14, textAlign: 'left' }}>
          <div style={{ fontSize: 13.5, fontWeight: 800, color: T.ink }}>💬 다음 단계는 카톡으로</div>
          <div style={{ fontSize: 12.5, color: T.sub, marginTop: 6, lineHeight: 1.55 }}>맞춤 사이즈 확인, 단체 인원별 사이즈 정리, 디테일 변경은 카카오톡 채널 상담으로 빠르게 도와드려요.</div>
        </div>
      </div>
      <div style={{ flex: '0 0 auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 10 }}>
        <Press onClick={() => toast('카카오톡 채널 상담을 연결합니다')} style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, padding: '16px', borderRadius: 14, background: T.kakao }}>
          <svg width="20" height="20" viewBox="0 0 24 24"><path d="M12 3C6.5 3 2 6.6 2 11c0 2.8 1.9 5.3 4.7 6.7l-1 3.6c-.1.4.3.7.6.5l4.3-2.8c.4 0 .9.1 1.4.1 5.5 0 10-3.6 10-8s-4.5-8-10-8Z" fill="#3C1E1E"/></svg>
          <span style={{ fontSize: 15.5, fontWeight: 800, color: T.kakaoInk }}>카카오톡 채널 상담 연결</span>
        </Press>
        <div style={{ display: 'flex', gap: 10 }}>
          <Press onClick={() => go('my')} style={{ flex: 1, textAlign: 'center', padding: '15px', borderRadius: 14, border: `1.5px solid ${T.line}`, color: T.ink, fontSize: 14.5, fontWeight: 700 }}>주문내역</Press>
          <Press onClick={() => go('home')} style={{ flex: 1, textAlign: 'center', padding: '15px', borderRadius: 14, background: T.gold, color: T.ink, fontSize: 14.5, fontWeight: 700 }}>홈으로</Press>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { CartScreen, CheckoutScreen, KakaoPaySheet, CompleteScreen, SectionTitle, lineSum, qtySum });
