// KASHA website — 마이페이지 (로그인 필요)
// 탭: 예약 내역(상세 팝업) · 개인정보(이름·비번 수정, 이메일·전화 고정) · 설정(결제수단·2단계 인증)
const MYRES_TONE = { "확정": "success", "대기": "warning", "완료": "accent", "취소": "neutral" };
const CARD_BRANDS = ["신한카드", "국민카드", "토스뱅크", "카카오뱅크", "현대카드"];

function MyPageScreen({ onNavigate }) {
  const { Button, Card, Input, Badge, Icon, Avatar, Toast, Dialog, Switch, SegmentedControl } = window.DS;
  window.KASHADB.useStore();
  const user = window.KASHADB.getCurrentUser() || {};
  const myRes = window.KASHADB.getMyReservations();
  const won = (n) => Number(n || 0).toLocaleString("ko-KR");

  const [tab, setTab] = React.useState("예약 내역");
  const [name, setName] = React.useState(user.name);
  const [pw, setPw] = React.useState(user.password);
  const [toast, setToast] = React.useState("");
  const [detail, setDetail] = React.useState(null);
  const [cardOpen, setCardOpen] = React.useState(false);

  const showToast = (m) => { setToast(m); setTimeout(() => setToast(""), 1800); };
  const dirty = name !== user.name || pw !== user.password;
  const saveInfo = () => { window.KASHADB.updateCurrentUser({ name: name.trim() || user.name, password: pw }); showToast("개인정보가 저장되었어요"); };
  const logout = () => { window.KASHADB.logout(); onNavigate("home"); };

  // 설정 — 결제수단 · 보안
  const onCardRegistered = (pm) => {
    const next = (user.paymentMethods || []).concat([pm]);
    window.KASHADB.updateCurrentUser({ paymentMethods: next });
    setCardOpen(false);
    showToast("결제수단이 등록되었어요");
  };
  const removeCard = (id) => { window.KASHADB.updateCurrentUser({ paymentMethods: (user.paymentMethods || []).filter((c) => c.id !== id) }); showToast("결제수단이 삭제되었어요"); };
  const toggle2FA = (v) => { window.KASHADB.updateCurrentUser({ twoFactor: v }); showToast(v ? "2단계 인증을 켰어요" : "2단계 인증을 껐어요"); };
  const togglePayLock = (v) => { window.KASHADB.updateCurrentUser({ payLock: v }); showToast(v ? "결제 비밀번호를 켰어요" : "결제 비밀번호를 껐어요"); };

  return (
    <div style={{ maxWidth: "var(--container-max)", margin: "0 auto", padding: "48px 24px 96px" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
        <Avatar name={user.name} src={window.img(user.seed || "ph1", 120, 120)} size={56} />
        <div style={{ flex: 1 }}>
          <h1 style={{ fontSize: "var(--text-title-1)", letterSpacing: "var(--tracking-title)" }}>{user.name}님</h1>
          <p style={{ marginTop: 4, color: "var(--text-secondary)", fontSize: 14 }}>{user.email}</p>
        </div>
        <Button variant="secondary" leadingIcon={<Icon name="arrowRight" size={16} />} onClick={logout}>로그아웃</Button>
      </div>

      <div style={{ maxWidth: 420, marginTop: 28 }}>
        <SegmentedControl items={["예약 내역", "개인정보", "설정"]} value={tab} onChange={setTab} />
      </div>

      <div style={{ marginTop: 28 }}>
        {/* 예약 내역 */}
        {tab === "예약 내역" && (
          myRes.length === 0 ? (
            <Card elevation="none" style={{ background: "var(--gray-50)", border: "none", textAlign: "center", padding: "48px 24px", maxWidth: 560 }}>
              <Icon name="calendar" size={32} color="var(--gray-400)" />
              <p style={{ marginTop: 14, color: "var(--text-secondary)", fontSize: 15 }}>아직 예약 내역이 없어요.</p>
              <div style={{ marginTop: 18 }}><Button variant="primary" onClick={() => onNavigate("booking")}>촬영 예약하기</Button></div>
            </Card>
          ) : (
            <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 16 }}>
              {myRes.map((r) => (
                <Card key={r.id} interactive onClick={() => setDetail(r)}>
                  <div style={{ display: "flex", alignItems: "flex-start", gap: 14 }}>
                    <div style={{ width: 64, height: 64, borderRadius: 14, overflow: "hidden", flexShrink: 0 }}>
                      <img src={window.img(r.seed, 140, 140)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                    </div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                        <span style={{ fontSize: 16, fontWeight: 700, color: "var(--text-strong)" }}>{r.pkg}</span>
                        <Badge tone={MYRES_TONE[r.status] || "neutral"}>{r.status}</Badge>
                      </div>
                      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 8, color: "var(--text-secondary)", fontSize: 13 }}>
                        <Icon name="calendar" size={14} color="var(--gray-500)" />{r.date} · {r.time}
                      </div>
                      <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 4, color: "var(--text-secondary)", fontSize: 13 }}>
                        <Icon name="mapPin" size={14} color="var(--gray-500)" />{r.place}
                      </div>
                    </div>
                  </div>
                  <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 12, paddingTop: 12, borderTop: "1px solid var(--border-subtle)" }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: r.paid ? "var(--green-600)" : "var(--yellow-600)" }}>{r.paid ? "결제 완료" : "입금 대기"}</span>
                    <span style={{ fontSize: 13, fontWeight: 600, color: "var(--text-link)" }}>상세보기</span>
                  </div>
                </Card>
              ))}
            </div>
          )
        )}

        {/* 개인정보 */}
        {tab === "개인정보" && (
          <Card style={{ maxWidth: 480 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
              <Input label="이름" value={name} onChange={(e) => setName(e.target.value)} placeholder="이름" />
              <Input label="비밀번호" type="password" value={pw} onChange={(e) => setPw(e.target.value)} helper="영문·숫자 조합을 권장해요" />
              <Input label="이메일 (변경 불가)" value={user.email} disabled />
              <Input label="전화번호 (변경 불가)" value={user.phone} disabled />
            </div>
            <div style={{ marginTop: 20 }}><Button variant="primary" fullWidth disabled={!dirty} onClick={saveInfo}>변경사항 저장</Button></div>
          </Card>
        )}

        {/* 설정 — 결제수단 · 2단계 인증 */}
        {tab === "설정" && (
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 20, maxWidth: 820 }}>
            <Card>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between" }}>
                <h3 style={{ fontSize: 17 }}>결제수단</h3>
                <Button variant="ghost" leadingIcon={<Icon name="plus" size={16} />} onClick={() => setCardOpen(true)}>추가</Button>
              </div>
              <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 14 }}>
                {(user.paymentMethods || []).length === 0 && <p style={{ color: "var(--text-tertiary)", fontSize: 14 }}>등록된 결제수단이 없어요.</p>}
                {(user.paymentMethods || []).map((c) => (
                  <div key={c.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--gray-50)" }}>
                    <span style={{ width: 36, height: 24, borderRadius: 5, background: "var(--ink)", display: "flex", alignItems: "center", justifyContent: "center" }}><Icon name="image" size={14} color="#fff" /></span>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 14, fontWeight: 700, color: "var(--text-strong)" }}>{c.brand}</div>
                      <div style={{ fontSize: 12, color: "var(--text-tertiary)" }}>•••• {c.last4}</div>
                    </div>
                    <button onClick={() => removeCard(c.id)} style={{ border: "none", background: "transparent", color: "var(--red-500)", fontSize: 13, fontWeight: 600, cursor: "pointer", fontFamily: "var(--font-sans)" }}>삭제</button>
                  </div>
                ))}
              </div>
            </Card>

            <Card>
              <h3 style={{ fontSize: 17 }}>보안</h3>
              <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 14 }}>
                <SettingRow title="2단계 인증" desc="로그인 시 인증코드를 한 번 더 확인해요." control={<Switch checked={!!user.twoFactor} onChange={toggle2FA} />} />
                <SettingRow title="로그인 알림" desc="새 기기 로그인 시 알림을 받아요." control={<Switch checked={true} onChange={() => {}} />} />
                <SettingRow title="결제 비밀번호" desc="결제 시 추가 인증을 사용해요." control={<Switch checked={!!user.payLock} onChange={togglePayLock} />} />
              </div>
              <div style={{ marginTop: 16, padding: "12px 14px", borderRadius: "var(--radius-md)", background: "var(--blue-50)", fontSize: 12.5, color: "var(--blue-700)", lineHeight: 1.5 }}>
                2단계 인증 {user.twoFactor ? "켜짐" : "꺼짐"} · 결제 비밀번호 {user.payLock ? "켜짐" : "꺼짐"}. 보안을 위해 켜두는 걸 권장해요.
              </div>
            </Card>
          </div>
        )}
      </div>

      {/* 예약 상세 팝업 */}
      <MyReservationDetail res={detail} onClose={() => setDetail(null)} />

      {/* 결제수단 등록 모달 */}
      <CardRegisterModal open={cardOpen} onClose={() => setCardOpen(false)} onRegister={onCardRegistered} />

      {toast && (
        <div style={{ position: "fixed", left: "50%", bottom: 36, transform: "translateX(-50%)", zIndex: 1100 }}>
          <Toast open tone="success" message={toast} />
        </div>
      )}
    </div>
  );
}

// 결제수단 등록 — 카드 직접 입력 또는 간편결제 연결
function CardRegisterModal({ open, onClose, onRegister }) {
  const { Dialog, Button, Input, Select, SegmentedControl, Icon } = window.DS;
  const [mode, setMode] = React.useState("카드");
  const [num, setNum] = React.useState("");
  const [exp, setExp] = React.useState("");
  const [cvc, setCvc] = React.useState("");
  const [brand, setBrand] = React.useState(CARD_BRANDS[0]);
  const [err, setErr] = React.useState("");

  React.useEffect(() => { if (open) { setMode("카드"); setNum(""); setExp(""); setCvc(""); setBrand(CARD_BRANDS[0]); setErr(""); } }, [open]);
  if (!open) return <Dialog open={false} onClose={onClose} />;

  const fmtNum = (v) => v.replace(/\D/g, "").slice(0, 16).replace(/(.{4})/g, "$1 ").trim();
  const digits = num.replace(/\D/g, "");
  const tossReady = !!(window.KASHAPay && window.KASHAPay.realConfigured && window.KASHAPay.realConfigured());

  const registerCard = () => {
    if (digits.length < 8) { setErr("카드 번호를 정확히 입력해 주세요."); return; }
    if (!/^\d{2}\s*\/\s*\d{2}$/.test(exp)) { setErr("유효기간을 MM/YY 형식으로 입력해 주세요."); return; }
    if (cvc.replace(/\D/g, "").length < 3) { setErr("CVC를 입력해 주세요."); return; }
    onRegister({ id: "pm-" + Date.now(), brand: brand, last4: digits.slice(-4), kind: "card" });
  };
  const registerEasy = (label) => {
    // 실제 연동: 토스 빌링(requestBillingAuth)로 카드 등록 → authKey → 서버 빌링키 발급
    onRegister({ id: "pm-" + Date.now(), brand: label, last4: "간편결제", kind: "easypay" });
  };

  return (
    <Dialog open onClose={onClose} style={{ maxWidth: 440, textAlign: "left" }}>
      <div style={{ textAlign: "left" }}>
        <h3 style={{ fontSize: 19, letterSpacing: "var(--tracking-title)" }}>결제수단 등록</h3>
        <div style={{ marginTop: 16, maxWidth: 280 }}>
          <SegmentedControl items={["카드", "간편결제"]} value={mode} onChange={setMode} />
        </div>

        {mode === "카드" ? (
          <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 16 }}>
            <Input label="카드 번호" value={num} onChange={(e) => setNum(fmtNum(e.target.value))} placeholder="0000 0000 0000 0000" style={{ minWidth: 0 }} />
            <div style={{ display: "flex", gap: 12 }}>
              <Input label="유효기간" value={exp} onChange={(e) => setExp(e.target.value)} placeholder="MM/YY" style={{ flex: 1, minWidth: 0 }} />
              <Input label="CVC" type="password" value={cvc} onChange={(e) => setCvc(e.target.value.replace(/\D/g, "").slice(0, 3))} placeholder="000" style={{ flex: 1, minWidth: 0 }} />
            </div>
            <Select label="카드사" value={brand} onChange={(e) => setBrand(e.target.value)} options={CARD_BRANDS} placeholder="" />
            {err && <div style={{ color: "var(--red-500)", fontSize: 13 }}>{err}</div>}
            <Button variant="primary" size="lg" fullWidth onClick={registerCard}>카드 등록</Button>
            <p style={{ fontSize: 12, color: "var(--text-tertiary)", textAlign: "center", lineHeight: 1.5 }}>
              {tossReady ? "토스페이먼츠 빌링으로 안전하게 등록돼요." : "실결제 연동 시 토스 빌링으로 토큰화돼요. (지금은 카드번호 끝 4자리만 보관)"}
            </p>
          </div>
        ) : (
          <div style={{ display: "flex", flexDirection: "column", gap: 10, marginTop: 16 }}>
            <button onClick={() => registerEasy("토스페이")} style={easyBtn("var(--blue-500)")}><span style={easyMark()}>T</span>토스페이 연결</button>
            <button onClick={() => registerEasy("네이버페이")} style={easyBtn("#03C75A")}><span style={easyMark()}>N</span>네이버페이 연결</button>
            <p style={{ fontSize: 12, color: "var(--text-tertiary)", textAlign: "center", lineHeight: 1.5, marginTop: 4 }}>
              간편결제는 해당 서비스 인증창에서 본인 계정을 연결해요.
            </p>
          </div>
        )}
      </div>
    </Dialog>
  );
}
function easyBtn(bg) { return { display: "flex", alignItems: "center", justifyContent: "center", gap: 10, height: 50, borderRadius: "var(--radius-input)", border: "none", background: bg, color: "#fff", fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 700, cursor: "pointer" }; }
function easyMark() { return { width: 22, height: 22, borderRadius: 6, background: "rgba(255,255,255,0.22)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 13 }; }

function SettingRow({ title, desc, control }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12, padding: "12px 0", borderBottom: "1px solid var(--border-subtle)" }}>
      <div>
        <div style={{ fontSize: 15, fontWeight: 600, color: "var(--text-strong)" }}>{title}</div>
        <div style={{ fontSize: 12.5, color: "var(--text-tertiary)", marginTop: 2 }}>{desc}</div>
      </div>
      {control}
    </div>
  );
}

// 예약 상세 팝업 (결제 정보 포함)
function MyReservationDetail({ res, onClose }) {
  const { Dialog, Button, Badge, Icon } = window.DS;
  if (!res) return <Dialog open={false} onClose={onClose} />;
  const won = (n) => Number(n || 0).toLocaleString("ko-KR");
  const pay = res.orderId ? window.KASHADB.getPaymentByOrderId(res.orderId) : null;

  return (
    <Dialog open={!!res} onClose={onClose} style={{ maxWidth: 460, textAlign: "left" }}>
      <div style={{ textAlign: "left" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 52, height: 52, borderRadius: 14, overflow: "hidden", flexShrink: 0 }}>
            <img src={window.img(res.seed, 120, 120)} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <h3 style={{ fontSize: 19 }}>{res.pkg}</h3>
              <Badge tone={MYRES_TONE[res.status] || "neutral"}>{res.status}</Badge>
            </div>
            <div style={{ fontSize: 13, color: "var(--text-tertiary)", marginTop: 2 }}>{res.id}</div>
          </div>
        </div>

        <div style={{ background: "var(--gray-50)", borderRadius: "var(--radius-md)", padding: "16px 18px", marginTop: 18, display: "flex", flexDirection: "column", gap: 12 }}>
          <DR icon="calendar" label="일정" value={`${res.date} ${res.time}`} />
          <DR icon="mapPin" label="장소" value={res.place} />
          {res.addons && res.addons.length > 0 && <DR icon="plus" label="옵션" value={res.addons.join(", ")} />}
          <DR icon="phone" label="연락처" value={res.phone} />
        </div>

        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 16, padding: "0 2px" }}>
          <span style={{ fontSize: 14, color: "var(--text-secondary)" }}>결제 금액</span>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ fontSize: 19, fontWeight: 700, color: "var(--text-strong)" }}>{won(res.amount)}원</span>
            {res.paid ? <Badge tone="success">결제완료</Badge> : <Badge tone="warning">입금대기</Badge>}
          </div>
        </div>

        {pay && (
          <div style={{ background: "var(--blue-50)", borderRadius: "var(--radius-md)", padding: "12px 16px", marginTop: 14, display: "flex", flexDirection: "column", gap: 8 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ width: 20, height: 20, borderRadius: 5, background: "var(--blue-500)", display: "flex", alignItems: "center", justifyContent: "center", color: "#fff", fontSize: 11, fontWeight: 800 }}>T</span>
              <strong style={{ fontSize: 13.5, color: "var(--blue-700)" }}>토스페이먼츠 · {pay.methodLabel}</strong>
            </div>
            <div style={{ fontSize: 12, color: "var(--gray-600)" }}>승인 {window.KASHADB.fmtApprovedAt(pay.approvedAt)}</div>
          </div>
        )}

        {res.memo && (
          <div style={{ marginTop: 14, padding: "12px 14px", borderRadius: "var(--radius-sm)", background: "var(--gray-50)", fontSize: 13, color: "var(--gray-700)", lineHeight: 1.5 }}>
            <strong>메모</strong> · {res.memo}
          </div>
        )}

        <div style={{ marginTop: 22 }}><Button variant="primary" fullWidth onClick={onClose}>닫기</Button></div>
      </div>
    </Dialog>
  );
}

function DR({ icon, label, value }) {
  const { Icon } = window.DS;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      <Icon name={icon} size={16} color="var(--gray-500)" />
      <span style={{ fontSize: 13, color: "var(--text-tertiary)", width: 56, flexShrink: 0 }}>{label}</span>
      <span style={{ fontSize: 14, fontWeight: 600, color: "var(--text-strong)", flex: 1, textAlign: "right" }}>{value}</span>
    </div>
  );
}
window.MyPageScreen = MyPageScreen;
