// 약관 동의 화면 — 앱의 terms_agreement_screen.dart 와 같은 역할.
//
// 웹 로그인(kakaoWebAuth / naverWebAuth / Google popup)은 동의를 받는 절차가 없어서
// getOrCreateUser() 가 만든 users/{uid}.agreedTerms 가 false 로 남아 있었다.
// 서버 completeOnboarding 은 terms / privacy / thirdParty 세 가지가 모두 true 여야 통과한다.

// 게이트 화면은 네비·푸터 없이 단독으로 뜨므로 뷰포트 기준으로 가운데 정렬한다
const GATE_WRAP = {
  minHeight: "100vh",
  display: "grid",
  placeItems: "center",
  padding: "40px 20px",
  boxSizing: "border-box",
};

const ONBOARDING_ITEMS = [
  {
    key: "terms",
    label: "이용약관 동의",
    href: "/terms",
  },
  {
    key: "privacy",
    label: "개인정보 수집·이용 동의",
    href: "/privacy",
  },
  {
    key: "thirdParty",
    label: "개인정보 제3자 제공 동의",
    href: "/privacy",
    desc: "배송 접수를 위해 택배사에 이름·연락처·주소를 제공합니다.",
  },
];

const TermsAgreement = ({ user, onDone }) => {
  const [checked, setChecked] = React.useState({
    terms: false, privacy: false, thirdParty: false,
  });
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");

  const allOn = ONBOARDING_ITEMS.every(i => checked[i.key]);
  const toggleAll = (on) =>
    setChecked(Object.fromEntries(ONBOARDING_ITEMS.map(i => [i.key, on])));

  const submit = async () => {
    if (!allOn || submitting) return;
    setSubmitting(true);
    setError("");
    try {
      const callable = window.firebaseHttpsCallable(
        window.firebaseFunctions, "completeOnboarding"
      );
      await callable({
        agreements: { terms: true, privacy: true, thirdParty: true },
      });
      onDone();
    } catch (e) {
      console.error("[onboarding] completeOnboarding error", e);
      setError(e?.message || "동의 처리 중 오류가 발생했어요. 다시 시도해주세요.");
    } finally {
      setSubmitting(false);
    }
  };

  const logout = () => {
    if (window.firebaseSignOut && window.firebaseAuth) {
      window.firebaseSignOut(window.firebaseAuth);
    }
  };

  return (
    // 네비가 없는 독립 화면이라 페이지 컨테이너 대신 뷰포트 정중앙에 놓는다
    <main style={GATE_WRAP}>
      <div style={{ width: "100%", maxWidth: 520 }}>
        <div className="page-head" style={{ padding: "0 0 28px" }}>
          <h1>약관 동의</h1>
          <p>솔브잇 이용을 위해 아래 항목에 동의해주세요. 모두 필수 항목입니다.</p>
        </div>

        <div className="tracking-card" style={{ marginBottom: 0 }}>
          {user?.email && (
            <div style={{
              marginBottom: 16, fontSize: 14, color: "var(--muted)",
            }}>
              <strong style={{ color: "var(--text)" }}>{user.email}</strong> 계정으로 진행합니다.
            </div>
          )}

          <label className="checkbox-row" style={{
            padding: "14px 16px", background: "var(--primary-50)",
            borderRadius: 10, marginBottom: 12, fontWeight: 600,
          }}>
            <input type="checkbox" checked={allOn}
              onChange={e => toggleAll(e.target.checked)}/>
            <span>전체 동의</span>
          </label>

          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {ONBOARDING_ITEMS.map(item => (
              <label key={item.key} className="checkbox-row" style={{
                padding: "14px 16px", background: "var(--bg-2)",
                borderRadius: 10, alignItems: "flex-start",
              }}>
                <input type="checkbox" checked={checked[item.key]}
                  onChange={e =>
                    setChecked(c => ({ ...c, [item.key]: e.target.checked }))
                  }/>
                <span style={{ flex: 1 }}>
                  <span>
                    {item.label} <span style={{ color: "var(--muted)" }}>(필수)</span>
                  </span>
                  {item.desc && (
                    <span style={{
                      display: "block", marginTop: 4,
                      fontSize: 13, color: "var(--muted)",
                    }}>{item.desc}</span>
                  )}
                  <a href={item.href} target="_blank" rel="noopener noreferrer"
                    onClick={e => e.stopPropagation()}
                    style={{
                      display: "block", width: "fit-content", marginTop: 4,
                      fontSize: 13, color: "var(--primary)",
                    }}>자세히 보기</a>
                </span>
              </label>
            ))}
          </div>

          {error && (
            <div style={{
              marginTop: 14, padding: "10px 14px",
              background: "#fef2f2", color: "#b91c1c",
              borderRadius: 10, fontSize: 14,
            }}>{error}</div>
          )}

          <button className="btn btn-primary btn-block"
            style={{ marginTop: 20 }}
            disabled={!allOn || submitting}
            onClick={submit}>
            {submitting ? "처리 중…" : "동의하고 시작하기"}
          </button>

          <button className="btn btn-outline btn-block"
            style={{ marginTop: 10 }}
            disabled={submitting}
            onClick={logout}>
            다른 계정으로 로그인
          </button>
        </div>
      </div>
    </main>
  );
};

// 동의 여부를 확인하는 동안 — 이때 실제 화면을 그리면 그 틈에 게이트를 빠져나갈 수 있다
const GateLoading = () => (
  <main style={GATE_WRAP}>
    <div style={{ color: "var(--muted)", fontSize: 14 }}>확인 중…</div>
  </main>
);

// 확인 실패 — 통과시키지 않고 재시도를 시킨다 (fail-closed)
const GateError = ({ onRetry }) => (
  <main style={GATE_WRAP}>
    <div style={{ textAlign: "center" }}>
      <div style={{ fontWeight: 600, marginBottom: 6 }}>
        계정 정보를 확인하지 못했어요
      </div>
      <div style={{ fontSize: 14, color: "var(--muted)", marginBottom: 16 }}>
        네트워크 상태를 확인하고 다시 시도해주세요.
      </div>
      <button className="btn btn-primary" onClick={onRetry}>다시 시도</button>
    </div>
  </main>
);

window.TermsAgreement = TermsAgreement;
window.GateLoading = GateLoading;
window.GateError = GateError;
