// KASHA website — payment / checkout screen (토스페이먼츠 연동 흐름 목업)
// 우리 결제수단 id → 토스페이먼츠 method 코드 매핑 (실연동 시 그대로 사용)
const TOSS_METHOD = {
  card: { method: "CARD", label: "카드" },
  toss: { method: "간편결제", label: "토스페이" },
  kakao: { method: "간편결제", label: "카카오페이" },
  transfer: { method: "TRANSFER", label: "계좌이체" },
};

// 예약 성공 시 전환 트래킹(GA4/픽셀) + 서버 SMS 알림 (설정 시에만 동작)
function notifyBooking(pkgName, phone, total, status) {
  try {
    if (!window.KASHAIntegrations) return;
    window.KASHAIntegrations.track("Purchase", { value: total, currency: "KRW", content_name: pkgName });
    window.KASHAIntegrations.notifySms({ to: phone, text: "[KASHA] " + pkgName + " 예약이 접수되었어요. (" + status + ") 확인 후 안내드릴게요." });
  } catch (e) {}
}

function PaymentScreen({ order, onNavigate }) {
  const { Button, Card, Input, Checkbox, Icon, Badge } = window.DS;
  const pkg = window.PACKAGES.find((p) => p.id === (order && order.pkgId)) || window.PACKAGES[0];
  const won = (n) => n.toLocaleString("ko-KR");
  const addonList = window.effectiveAddons(pkg);   // 상품 옵션 + 전역 옵션 템플릿

  const [method, setMethod] = React.useState("card");
  // 예약 단계에서 고른 옵션을 이어받아요
  const [selAddons, setSelAddons] = React.useState((order && order.addonIds) || []);
  const [coupon, setCoupon] = React.useState("");
  const [applied, setApplied] = React.useState(0);
  const [agree, setAgree] = React.useState({ terms: false, privacy: false });
  const [done, setDone] = React.useState(false);
  const [paying, setPaying] = React.useState(false);
  const [payError, setPayError] = React.useState("");
  const [receipt, setReceipt] = React.useState(null);

  const toggleAddon = (id) => setSelAddons((s) => s.includes(id) ? s.filter((x) => x !== id) : [...s, id]);
  const addonTotal = addonList.filter((a) => selAddons.includes(a.id)).reduce((s, a) => s + a.price, 0);
  const subtotal = pkg.priceNum + addonTotal;
  const total = Math.max(0, subtotal - applied);
  const canPay = agree.terms && agree.privacy;

  const applyCoupon = () => setApplied(coupon.trim() ? 20000 : 0);

  const pay = async () => {
    setPayError("");
    const m = window.PAYMENT_METHODS.find((x) => x.id === method) || {};
    const tm = TOSS_METHOD[method] || { method: "CARD", label: m.label || "카드" };
    const addonLabels = addonList.filter((a) => selAddons.includes(a.id)).map((a) => a.label);

    // ── 계좌이체: 결제창 없이 예약 신청(대기) → 관리자 송금 확인 후 확정 ──
    if (method === "transfer") {
      window.KASHADB.addReservation({
        name: order.name, phone: order.phone, email: order.email, pkg: pkg.name,
        date: order.date, time: order.time, place: order.place,
        amount: total, paid: false, status: "대기", addons: addonLabels, seed: pkg.seed,
        method: "TRANSFER", methodLabel: "계좌이체", memo: "계좌이체 입금 대기",
      });
      setReceipt({ transfer: true });
      notifyBooking(pkg.name, order.phone, total, "계좌이체 접수");
      window.KASHANotify.send("received", { email: order.email, name: order.name, pkg: pkg.name, date: order.date, time: order.time, place: order.place, amount: total });
      window.KASHASuccess.show({ title: "예약 신청 완료", message: "입금 확인 후 예약이 확정돼요." });
      setDone(true);
      return;
    }

    // ── 카드결제·토스페이·네이버페이: 결제창으로 이동 → 승인 → 예약 확정 ──
    const tx = window.KASHADB.createPayment({
      orderName: pkg.name + " 촬영", amount: total,
      method: tm.method, methodLabel: tm.label,
      customerName: order.name, customerPhone: order.phone,
    });
    // 실제 토스 리다이렉트 복귀 시 예약 생성을 위한 주문 정보
    const orderObj = {
      pkgId: pkg.id, pkgName: pkg.name, seed: pkg.seed,
      name: order.name, phone: order.phone, email: order.email, place: order.place,
      date: order.date, time: order.time, amount: total, addons: addonLabels,
      method: tm.method, methodLabel: tm.label,
    };

    setPaying(true);
    try {
      const result = await window.KASHAPay.requestPayment({
        orderId: tx.orderId, orderName: tx.orderName,
        method: tm.method, methodLabel: tm.label,
        amount: { currency: "KRW", value: total }, customerName: order.name,
      }, orderObj);

      if (result && result.redirecting) return; // 실제 토스 결제창으로 이동 중(페이지 전환)

      // 목업 결제 승인됨 → 예약 확정
      window.KASHADB.addReservation({
        name: order.name, phone: order.phone, email: order.email, pkg: pkg.name,
        date: order.date, time: order.time, place: order.place,
        amount: total, paid: true, status: "확정", addons: addonLabels, seed: pkg.seed,
        orderId: tx.orderId, paymentKey: result.paymentKey, method: tm.method, methodLabel: tm.label,
      });
      setReceipt(result);
      notifyBooking(pkg.name, order.phone, total, "결제 완료");
      window.KASHANotify.send("paid", { email: order.email, name: order.name, pkg: pkg.name, date: order.date, time: order.time, place: order.place, amount: total, method: tm.label, orderId: tx.orderId, paymentKey: result.paymentKey, approvedAt: window.KASHADB.fmtApprovedAt(result.approvedAt) });
      window.KASHASuccess.show({ title: "결제가 완료되었어요", message: `${pkg.name} 촬영 예약이 확정되었어요.` });
      setDone(true);
    } catch (e) {
      setPayError((e && e.message) || "결제에 실패했어요. 다시 시도해 주세요.");
    } finally {
      setPaying(false);
    }
  };

  if (done) {
    const isTransfer = receipt && receipt.transfer;
    return (
      <div style={{ maxWidth: 560, margin: "0 auto", padding: "80px 24px", textAlign: "center" }}>
        <div style={{ width: 76, height: 76, borderRadius: "50%", background: isTransfer ? "var(--yellow-50)" : "var(--green-50)", display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto" }}>
          <Icon name={isTransfer ? "clock" : "check"} size={40} color={isTransfer ? "var(--yellow-600)" : "var(--green-500)"} strokeWidth={2.5} />
        </div>
        <h1 style={{ fontSize: "var(--text-title-1)", letterSpacing: "var(--tracking-title)", marginTop: 28 }}>{isTransfer ? "예약 신청이 접수되었어요" : "예약이 완료되었어요"}</h1>
        <p style={{ marginTop: 14, color: "var(--text-secondary)", fontSize: "var(--text-body-lg)", lineHeight: "var(--leading-relaxed)" }}>
          {isTransfer
            ? <>{order.name || "고객"}님, 아래 계좌로 입금해 주세요.<br />입금이 확인되면 예약이 <strong>확정</strong>돼요.</>
            : <>{order.name || "고객"}님, {pkg.name} 촬영 예약이 확정되었어요.<br />확인 문자를 보내드렸어요.</>}
        </p>
        <Card elevation="none" style={{ background: "var(--gray-50)", border: "none", marginTop: 28, textAlign: "left" }}>
          <Row label="촬영" value={pkg.name} />
          <Row label="일정" value={`${order.date} · ${order.time}`} />
          <Row label="장소" value={order.place} />
          <div style={{ borderTop: "1px solid var(--border-subtle)", margin: "14px 0 0", paddingTop: 14 }}>
            <Row label={isTransfer ? "입금 금액" : "결제 금액"} value={`${won(total)}원`} strong />
          </div>
          {isTransfer && (
            <div style={{ borderTop: "1px solid var(--border-subtle)", margin: "14px 0 0", paddingTop: 14, display: "flex", flexDirection: "column", gap: 10 }}>
              <Row label="입금 계좌" value="신한 110-123-456789" />
              <Row label="예금주" value="KASHA 스튜디오" />
              <Row label="상태" value="입금 대기 (확인 후 확정)" accent />
            </div>
          )}
          {receipt && !isTransfer && (
            <div style={{ borderTop: "1px solid var(--border-subtle)", margin: "14px 0 0", paddingTop: 14, display: "flex", flexDirection: "column", gap: 10 }}>
              <Row label="결제 수단" value={receipt.methodLabel} />
              <Row label="주문번호" value={receipt.orderId} />
              <Row label="결제키" value={`${(receipt.paymentKey || "").slice(0, 16)}…`} />
              <Row label="승인 시각" value={window.KASHADB.fmtApprovedAt(receipt.approvedAt)} />
            </div>
          )}
        </Card>
        <div style={{ marginTop: 28 }}>
          <Button variant="primary" size="lg" fullWidth onClick={() => onNavigate("home")}>홈으로</Button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "32px 24px 96px" }}>
      <button onClick={() => onNavigate("booking", { pkgId: pkg.id })}
        style={{ border: "none", background: "transparent", display: "flex", alignItems: "center", gap: 6, color: "var(--text-secondary)", fontSize: 15, fontWeight: 600, cursor: "pointer", padding: 0, marginBottom: 24 }}>
        <Icon name="arrowLeft" size={18} /> 예약 정보 수정
      </button>

      <h1 style={{ fontSize: "var(--text-title-1)", letterSpacing: "var(--tracking-title)" }}>결제</h1>

      <div style={{ display: "grid", gridTemplateColumns: "1.2fr 0.8fr", gap: 32, marginTop: 28, alignItems: "start" }}>
        {/* Left: details */}
        <div style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          {/* Booking summary */}
          <Section title="예약 내용">
            <div style={{ display: "flex", gap: 16 }}>
              <div style={{ width: 96, height: 96, borderRadius: 14, overflow: "hidden", flexShrink: 0 }}>
                <img src={window.img(pkg.gallery[0], 200, 200)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ fontSize: 17, fontWeight: 700, color: "var(--text-strong)" }}>{pkg.name}</span>
                  {pkg.popular && <Badge tone="accent">인기</Badge>}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 8, color: "var(--text-secondary)", fontSize: 14 }}>
                  <Icon name="calendar" size={15} color="var(--gray-500)" />{order.date} · {order.time}
                </div>
                <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 5, color: "var(--text-secondary)", fontSize: 14 }}>
                  <Icon name="mapPin" size={15} color="var(--gray-500)" />{order.place}
                </div>
              </div>
            </div>
          </Section>

          {/* Add-ons */}
          <Section title="추가 옵션">
            <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
              {addonList.map((a) => {
                const on = selAddons.includes(a.id);
                return (
                  <button key={a.id} onClick={() => toggleAddon(a.id)}
                    style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 18px", borderRadius: "var(--radius-md)", border: `1.5px solid ${on ? "var(--ink)" : "var(--border-subtle)"}`, background: on ? "var(--gray-50)" : "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", textAlign: "left", transition: "border-color var(--dur-fast) var(--ease-standard)" }}>
                    <span style={{ width: 22, height: 22, borderRadius: 7, background: on ? "var(--ink)" : "#fff", border: `1.5px solid ${on ? "var(--ink)" : "var(--border-strong)"}`, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                      {on && <Icon name="check" size={15} color="#fff" strokeWidth={3} />}
                    </span>
                    <span style={{ flex: 1, fontSize: 15, fontWeight: 600, color: "var(--text-strong)" }}>{a.label}</span>
                    <span style={{ fontSize: 15, fontWeight: 700, color: "var(--text-strong)" }}>+{won(a.price)}원</span>
                  </button>
                );
              })}
            </div>
          </Section>

          {/* Payment method */}
          <Section title="결제 수단">
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              {window.PAYMENT_METHODS.map((m) => {
                const on = method === m.id;
                return (
                  <button key={m.id} onClick={() => setMethod(m.id)}
                    style={{ display: "flex", alignItems: "center", gap: 10, padding: "16px 18px", borderRadius: "var(--radius-md)", border: `1.5px solid ${on ? "var(--ink)" : "var(--border-subtle)"}`, background: on ? "var(--gray-50)" : "#fff", cursor: "pointer", fontFamily: "var(--font-sans)", transition: "border-color var(--dur-fast) var(--ease-standard)" }}>
                    <span style={{ width: 32, height: 32, borderRadius: 9, background: on ? "var(--ink)" : "var(--gray-100)", display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>
                      <Icon name={m.icon} size={18} color={on ? "#fff" : "var(--gray-600)"} />
                    </span>
                    <span style={{ fontSize: 15, fontWeight: 600, color: "var(--text-strong)" }}>{m.label}</span>
                  </button>
                );
              })}
            </div>
            <div style={{ display: "flex", alignItems: "center", gap: 10, marginTop: 16, padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--blue-50)", color: "var(--blue-700)", fontSize: 13.5, lineHeight: 1.5 }}>
              <Icon name="check" size={18} color="var(--blue-500)" />
              결제하기를 누르면 토스페이먼츠 결제창이 열려요. 카드·간편결제 정보는 결제창에서 안전하게 입력해요.
            </div>
          </Section>
        </div>

        {/* Right: order summary (sticky) */}
        <div style={{ position: "sticky", top: 92 }}>
          <Card>
            <h3 style={{ fontSize: 18 }}>결제 금액</h3>
            <div style={{ display: "flex", gap: 8, marginTop: 18 }}>
              <Input placeholder="쿠폰 코드" value={coupon} onChange={(e) => setCoupon(e.target.value)} style={{ flex: 1 }} />
              <Button variant="secondary" onClick={applyCoupon}>적용</Button>
            </div>
            <div style={{ borderTop: "1px solid var(--border-subtle)", margin: "18px 0", paddingTop: 18, display: "flex", flexDirection: "column", gap: 12 }}>
              <Row label="촬영 가격" value={`${won(pkg.priceNum)}원`} />
              {addonTotal > 0 && <Row label="추가 옵션" value={`${won(addonTotal)}원`} />}
              {applied > 0 && <Row label="쿠폰 할인" value={`-${won(applied)}원`} accent />}
            </div>
            <div style={{ borderTop: "1px solid var(--border-subtle)", paddingTop: 18, display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <span style={{ fontSize: 16, fontWeight: 700, color: "var(--text-strong)" }}>총 결제금액</span>
              <span style={{ fontSize: 26, fontWeight: 700, color: "var(--text-strong)", letterSpacing: "var(--tracking-title)" }}>{won(total)}<span style={{ fontSize: 15, fontWeight: 500, color: "var(--text-tertiary)" }}>원</span></span>
            </div>

            <div style={{ marginTop: 20, display: "flex", flexDirection: "column", gap: 12 }}>
              <Checkbox checked={agree.terms} onChange={(v) => setAgree((a) => ({ ...a, terms: v }))} label="이용약관 동의 (필수)" />
              <Checkbox checked={agree.privacy} onChange={(v) => setAgree((a) => ({ ...a, privacy: v }))} label="개인정보 수집·이용 동의 (필수)" />
            </div>

            <div style={{ marginTop: 22 }}>
              <Button variant="primary" size="lg" fullWidth disabled={!canPay || paying} onClick={pay}>
                {paying ? "결제창 진행 중…" : `${won(total)}원 결제하기`}
              </Button>
            </div>
            {payError && <p style={{ marginTop: 10, fontSize: 13, color: "var(--red-500)", textAlign: "center" }}>{payError}</p>}
            <p style={{ marginTop: 12, fontSize: 12, color: "var(--text-tertiary)", textAlign: "center" }}>토스페이먼츠로 안전하게 결제돼요 · 예약일 7일 전까지 100% 환불</p>
          </Card>
        </div>
      </div>
    </div>
  );
}

function Section({ title, children }) {
  return (
    <div>
      <h2 style={{ fontSize: "var(--text-title-3)", letterSpacing: "var(--tracking-title)", marginBottom: 16 }}>{title}</h2>
      {children}
    </div>
  );
}

function Row({ label, value, strong, accent }) {
  return (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
      <span style={{ fontSize: 14, color: "var(--text-secondary)" }}>{label}</span>
      <span style={{ fontSize: strong ? 18 : 15, fontWeight: strong ? 700 : 600, color: accent ? "var(--blue-500)" : "var(--text-strong)" }}>{value}</span>
    </div>
  );
}
window.PaymentScreen = PaymentScreen;
