// KASHA website — 인증 (로그인 / 회원가입 + 이메일 인증)
// 마이페이지는 로그인해야 접근할 수 있어요. 로그인 성공 시 세션이 설정되고
// 상위(App)가 자동으로 마이페이지를 보여줍니다.
function AuthScreen({ onNavigate }) {
  const { Button, Card, Input, Icon, Logo } = window.DS;
  const DB = window.KASHADB;
  // 라이브(서버 백엔드)에선 인증코드를 화면에 노출하지 않아요(이메일로만). 로컬 개발만 데모 코드 표시.
  const liveBackend = !!(window.KASHA_BACKEND && window.KASHA_BACKEND.enabled);

  const [mode, setMode] = React.useState("login"); // login | signup | verify
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [phone, setPhone] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [code, setCode] = React.useState("");
  const [sentCode, setSentCode] = React.useState(""); // 발송 실패/미설정 시 데모 코드 표시
  const [emailSent, setEmailSent] = React.useState(false); // 실제 이메일 발송 성공 여부
  const [sending, setSending] = React.useState(false);
  const [err, setErr] = React.useState("");

  const reset = () => { setErr(""); };

  const doLogin = async () => {
    reset();
    const r = DB.login(email.trim(), password);
    if (r.error) { setErr(r.error === "BAD_CREDENTIALS" ? "이메일 또는 비밀번호가 올바르지 않아요." : "이메일 인증이 필요해요."); return; }
    if (r.twoFactorRequired) {
      setSending(true);
      const sent = await window.KASHAEmail.sendCode({ toEmail: r.email, toName: name || "", code: r.code, purpose: "login" });
      setSending(false);
      if (!sent.ok && liveBackend) { setErr("인증코드 메일 발송에 실패했어요. 잠시 후 다시 시도해 주세요."); return; }
      setEmailSent(!!sent.ok);
      setSentCode(sent.ok ? "" : r.code); // 로컬(백엔드 없음)에서만 데모 코드 표시
      setCode(""); setMode("login2fa");
      return;
    }
    if (r.ok) window.KASHASuccess.show({ title: "로그인 완료", message: "다시 오신 걸 환영해요!" });
  };

  const doVerify2FA = () => {
    reset();
    const r = DB.verifyLogin2FA(email.trim(), code.trim());
    if (r.error) setErr(r.error === "BAD_CODE" ? "인증코드가 일치하지 않아요." : "인증 정보를 확인해 주세요.");
    else window.KASHASuccess.show({ title: "인증 완료", message: "2단계 인증으로 안전하게 로그인했어요." });
  };

  // ── SNS 로그인 (구글·애플·네이버) ──
  const snsGuide = (provider, e) => {
    const reason = e && e.reason;
    const P = provider === "google" ? "구글" : provider === "apple" ? "애플" : "네이버";
    if (reason === "GOOGLE_NOT_CONFIGURED") return "구글 로그인을 켜려면 data/auth-config.js 에 구글 OAuth 클라이언트 ID를 넣어주세요.";
    if (reason === "APPLE_NOT_CONFIGURED") return "애플 로그인은 Apple Developer 등록 + HTTPS 도메인이 필요해요 (auth-config.js).";
    if (reason === "APPLE_NEEDS_HTTPS") return "애플 로그인은 HTTPS 도메인에서만 동작해요. 배포 후 이용해 주세요.";
    if (reason === "NAVER_NOT_CONFIGURED") return "네이버 로그인을 켜려면 auth-config.js 에 네이버 Client ID를 넣어주세요.";
    if (reason === "NAVER_NEEDS_BACKEND") return "네이버는 프로필 조회에 서버 프록시가 필요해요. 백엔드 연동 후 이용할 수 있어요.";
    if (reason && String(reason).indexOf("SDK_MISSING") >= 0) return P + " SDK를 불러오지 못했어요. 네트워크를 확인해 주세요.";
    if (reason === "GOOGLE_ERROR") return "구글 로그인이 취소되었어요.";
    return P + " 로그인 중 문제가 발생했어요.";
  };
  const snsLogin = async (provider) => {
    reset();
    try {
      const fn = provider === "google" ? window.KASHASNS.signInGoogle : provider === "apple" ? window.KASHASNS.signInApple : window.KASHASNS.signInNaver;
      const info = await fn();
      const r = DB.loginWithSNS(info);
      if (r.error) { setErr("로그인 정보를 가져오지 못했어요."); return; }
      const P = provider === "google" ? "구글" : provider === "apple" ? "애플" : "네이버";
      window.KASHASuccess.show({ title: P + " 로그인 완료", message: "환영해요!" });
    } catch (e) { setErr(snsGuide(provider, e)); }
  };

  const doSignup = async () => {
    reset();
    if (!name.trim() || !email.trim() || !password) { setErr("이름·이메일·비밀번호를 입력해 주세요."); return; }
    const r = DB.signupRequest({ name: name.trim(), email: email.trim(), phone: phone.trim(), password });
    if (r.error) { setErr(r.error === "EMAIL_EXISTS" ? "이미 가입된 이메일이에요." : "입력값을 확인해 주세요."); return; }
    setSending(true);
    const sent = await window.KASHAEmail.sendCode({ toEmail: email.trim(), toName: name.trim(), code: r.code, purpose: "signup" });
    setSending(false);
    if (!sent.ok && liveBackend) { setErr("인증코드 메일 발송에 실패했어요. 잠시 후 다시 시도해 주세요."); return; }
    setEmailSent(!!sent.ok);
    setSentCode(sent.ok ? "" : r.code); // 로컬(백엔드 없음)에서만 데모 코드 표시
    setMode("verify");
  };

  const doVerify = () => {
    reset();
    const r = DB.verifyAndCreate(email.trim(), code.trim());
    if (r.error) setErr(r.error === "BAD_CODE" ? "인증코드가 일치하지 않아요." : "인증 정보를 확인해 주세요.");
    else window.KASHASuccess.show({ title: "가입 완료", message: "KASHA에 오신 걸 환영해요!" });
  };

  const field = { marginBottom: 14 };

  return (
    <div style={{ minHeight: "calc(100vh - 69px)", display: "flex", alignItems: "flex-start", justifyContent: "center", padding: "64px 24px", background: "var(--gray-50)" }}>
      <div style={{ width: "100%", maxWidth: 420 }}>
        <div style={{ textAlign: "center", marginBottom: 28 }}>
          <Logo size={30} />
          <h1 style={{ fontSize: "var(--text-title-2)", letterSpacing: "var(--tracking-title)", marginTop: 18 }}>
            {mode === "verify" ? "이메일 인증" : mode === "login2fa" ? "2단계 인증" : mode === "signup" ? "회원가입" : "로그인"}
          </h1>
          <p style={{ marginTop: 8, color: "var(--text-secondary)", fontSize: 14 }}>
            {mode === "verify" ? "보내드린 인증코드를 입력해 주세요."
              : mode === "login2fa" ? "보안을 위해 인증코드를 한 번 더 확인해요."
              : "마이페이지는 로그인 후 이용할 수 있어요."}
          </p>
        </div>

        <Card>
          {mode === "login" && (
            <div>
              <div style={field}><Input label="이메일" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" /></div>
              <div style={field}><Input label="비밀번호" type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="비밀번호" /></div>
              {err && <ErrText msg={err} />}
              <div style={{ marginTop: 8 }}><Button variant="primary" size="lg" fullWidth disabled={sending} onClick={doLogin}>{sending ? "확인 중…" : "로그인"}</Button></div>
              <SwitchRow text="아직 회원이 아니신가요?" action="회원가입" onClick={() => { setMode("signup"); reset(); }} />
              <SnsButtons onClick={snsLogin} />
            </div>
          )}

          {mode === "signup" && (
            <div>
              <div style={field}><Input label="이름" value={name} onChange={(e) => setName(e.target.value)} placeholder="홍길동" /></div>
              <div style={field}><Input label="이메일" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="you@example.com" /></div>
              <div style={field}><Input label="전화번호" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="010-0000-0000" /></div>
              <div style={field}><Input label="비밀번호" type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="비밀번호" /></div>
              {err && <ErrText msg={err} />}
              <div style={{ marginTop: 8 }}><Button variant="primary" size="lg" fullWidth disabled={sending} onClick={doSignup}>{sending ? "메일 보내는 중…" : "인증코드 받기"}</Button></div>
              <SwitchRow text="이미 계정이 있으신가요?" action="로그인" onClick={() => { setMode("login"); reset(); }} />
              <SnsButtons onClick={snsLogin} />
            </div>
          )}

          {mode === "login2fa" && (
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--blue-50)", marginBottom: 16 }}>
                <Icon name="check" size={18} color="var(--blue-500)" />
                <span style={{ fontSize: 13.5, color: "var(--blue-700)", lineHeight: 1.5 }}>
                  비밀번호 확인 완료. <strong>{email}</strong> 로 보낸 인증코드를 입력해 주세요.
                </span>
              </div>
              {sentCode && (
                <div style={{ textAlign: "center", marginBottom: 16, padding: "12px", borderRadius: "var(--radius-md)", background: "var(--gray-50)", border: "1px dashed var(--border-default)" }}>
                  <span style={{ fontSize: 12, color: "var(--text-tertiary)" }}>데모용 인증코드 (실제 서비스에서는 이메일/앱으로만)</span>
                  <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "0.2em", color: "var(--text-strong)", marginTop: 4 }}>{sentCode}</div>
                </div>
              )}
              {emailSent && !sentCode && <SentNote email={email} />}
              <div style={field}><Input label="인증코드 6자리" value={code} onChange={(e) => setCode(e.target.value)} placeholder="000000" /></div>
              {err && <ErrText msg={err} />}
              <div style={{ marginTop: 8 }}><Button variant="primary" size="lg" fullWidth onClick={doVerify2FA}>인증하고 로그인</Button></div>
              <SwitchRow text="" action="다시 로그인" onClick={() => { setMode("login"); setCode(""); reset(); }} />
            </div>
          )}

          {mode === "verify" && (
            <div>
              <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "14px 16px", borderRadius: "var(--radius-md)", background: "var(--blue-50)", marginBottom: 16 }}>
                <Icon name="phone" size={18} color="var(--blue-500)" />
                <span style={{ fontSize: 13.5, color: "var(--blue-700)", lineHeight: 1.5 }}>
                  <strong>{email}</strong> 로 인증코드를 보냈어요.
                </span>
              </div>
              {sentCode && (
                <div style={{ textAlign: "center", marginBottom: 16, padding: "12px", borderRadius: "var(--radius-md)", background: "var(--gray-50)", border: "1px dashed var(--border-default)" }}>
                  <span style={{ fontSize: 12, color: "var(--text-tertiary)" }}>데모용 인증코드 (실제 서비스에서는 이메일로만 발송)</span>
                  <div style={{ fontSize: 24, fontWeight: 800, letterSpacing: "0.2em", color: "var(--text-strong)", marginTop: 4 }}>{sentCode}</div>
                </div>
              )}
              {emailSent && !sentCode && <SentNote email={email} />}
              <div style={field}><Input label="인증코드 6자리" value={code} onChange={(e) => setCode(e.target.value)} placeholder="000000" /></div>
              {err && <ErrText msg={err} />}
              <div style={{ marginTop: 8 }}><Button variant="primary" size="lg" fullWidth onClick={doVerify}>인증하고 시작하기</Button></div>
              <SwitchRow text="" action="이메일 다시 입력" onClick={() => { setMode("signup"); reset(); }} />
            </div>
          )}
        </Card>

        <div style={{ textAlign: "center", marginTop: 20 }}>
          <button onClick={() => onNavigate("home")} style={{ border: "none", background: "transparent", color: "var(--text-tertiary)", fontSize: 14, cursor: "pointer", fontFamily: "var(--font-sans)" }}>홈으로 돌아가기</button>
        </div>
      </div>
    </div>
  );
}

function ErrText({ msg }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 6, color: "var(--red-500)", fontSize: 13, marginBottom: 12 }}>
    <window.DS.Icon name="x" size={15} color="var(--red-500)" />{msg}
  </div>;
}
function SwitchRow({ text, action, onClick }) {
  return (
    <div style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 6, marginTop: 18, fontSize: 14 }}>
      {text && <span style={{ color: "var(--text-tertiary)" }}>{text}</span>}
      <button onClick={onClick} style={{ border: "none", background: "transparent", color: "var(--blue-500)", fontWeight: 700, cursor: "pointer", fontFamily: "var(--font-sans)", fontSize: 14 }}>{action}</button>
    </div>
  );
}
function SnsButtons({ onClick }) {
  const providers = [
    { id: "google", label: "Google로 계속하기", bg: "#fff", color: "#1f1f1f", border: "1px solid var(--border-default)", mark: "G", markColor: "#4285F4" },
    { id: "apple", label: "Apple로 계속하기", bg: "#000", color: "#fff", border: "none", mark: "", markColor: "#fff" },
    { id: "naver", label: "네이버로 계속하기", bg: "#03C75A", color: "#fff", border: "none", mark: "N", markColor: "#fff" },
  ];
  return (
    <div style={{ marginTop: 20 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, margin: "4px 0 16px" }}>
        <div style={{ flex: 1, height: 1, background: "var(--border-subtle)" }} />
        <span style={{ fontSize: 12, color: "var(--text-tertiary)" }}>또는 SNS로 계속</span>
        <div style={{ flex: 1, height: 1, background: "var(--border-subtle)" }} />
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {providers.map((p) => (
          <button key={p.id} onClick={() => onClick(p.id)}
            style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 10, height: 48, borderRadius: "var(--radius-input)", border: p.border, background: p.bg, color: p.color, fontFamily: "var(--font-sans)", fontSize: 15, fontWeight: 600, cursor: "pointer" }}>
            <span style={{ width: 20, height: 20, borderRadius: 5, background: p.id === "google" ? "#fff" : "rgba(255,255,255,0.18)", display: "flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 13, color: p.markColor }}>
              {p.id === "apple" ? <window.DS.Icon name="star" size={14} color="#fff" /> : p.mark}
            </span>
            {p.label}
          </button>
        ))}
      </div>
    </div>
  );
}

function SentNote({ email }) {
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 16, padding: "12px 14px", borderRadius: "var(--radius-md)", background: "var(--green-50)", color: "var(--green-600)", fontSize: 13, lineHeight: 1.5 }}>
      <window.DS.Icon name="check" size={17} color="var(--green-500)" />
      <span><strong>{email}</strong> 메일함으로 인증코드를 보냈어요. 받은 편지함을 확인해 주세요.</span>
    </div>
  );
}
window.AuthScreen = AuthScreen;
