// ===== Login Screen =====

const POLICY_CONTENT = {
  terms: {
    title: '서비스 약관',
    body: `Bannerly 서비스 이용약관

제1조 (목적)
이 약관은 CJ 내부 배너 자동 생성 서비스 "Bannerly"(이하 "서비스")의 이용 조건과 절차, 이용자와 운영자의 권리·의무 및 책임 사항을 규정함을 목적으로 합니다.

제2조 (서비스 범위)
서비스는 CJ 임직원 전용으로 제공되는 사내 배너 제작 도구입니다. 외부 공개 또는 상업적 재배포는 허용되지 않습니다.

제3조 (이용자의 의무)
이용자는 서비스를 업무 목적 외로 사용할 수 없으며, 생성된 배너는 CJ 브랜드 가이드라인을 준수하여야 합니다.

제4조 (서비스 변경 및 중단)
운영자는 서비스의 내용을 변경하거나 중단할 수 있으며, 이로 인한 손해에 대해 별도로 정한 사항이 없는 한 책임지지 않습니다.

최종 수정: 2025년 1월`
  },
  privacy: {
    title: '개인정보처리방침',
    body: `Bannerly 개인정보처리방침

1. 수집하는 개인정보
   - 이메일 주소, 이름, 소속 부서

2. 수집 목적
   - 서비스 로그인 인증 및 배너 작업 이력 관리

3. 보유 기간
   - 퇴직/탈퇴 시까지 보유 후 즉시 삭제

4. 제3자 제공
   - 개인정보를 외부에 제공하지 않습니다.

5. 보안
   - Supabase(EU 리전)를 통한 암호화 저장. 비밀번호는 bcrypt 해시로 처리됩니다.

문의: 서비스 관리자

최종 수정: 2025년 1월`
  },
  help: {
    title: '도움말',
    body: `Bannerly 도움말

■ 배너 만들기
1. 상단 메뉴에서 "배너 만들기"를 클릭합니다.
2. 왼쪽 카테고리에서 상품을 선택하거나 채팅으로 상품을 지정합니다.
3. 배너 유형(앱푸시 / 상품배너 550 / 상품배너 H1 / 1E)을 선택합니다.
4. 이미지를 업로드하고 배치 결과를 확인합니다.
5. "저장" 버튼으로 배너를 내 배너에 보관합니다.

■ 배경 제거(누끼)
- 이미지를 선택한 후 "배경 제거 편집기 열기"를 클릭하면 AI 누끼 도구가 열립니다.
- 체크한 이미지만 배경이 제거되며, 완료 후 "완료" 버튼을 누르면 편집기로 전달됩니다.

■ 내 배너
- 저장한 배너를 확인하고 다운로드하거나 이어서 편집할 수 있습니다.
- 행사명으로 검색하거나 날짜 범위로 필터링할 수 있습니다.

■ 문의
서비스 이용 중 문제가 생기면 사내 메신저로 운영팀에 문의하세요.`
  }
};

function PolicyModal({ kind, onClose }) {
  const p = POLICY_CONTENT[kind];
  if (!p) return null;
  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(20,20,26,.45)", display: "grid", placeItems: "center", zIndex: 10000 }}>
      <div onClick={(e) => e.stopPropagation()} style={{ position: "relative", width: 520, maxWidth: "94vw", maxHeight: "80vh", overflowY: "auto", background: "#fff", borderRadius: 16, padding: 24, boxShadow: "0 12px 40px rgba(0,0,0,.2)" }}>
        <button onClick={onClose} title="닫기" style={{ position: "absolute", top: 14, right: 14, border: "none", background: "none", cursor: "pointer", fontSize: 22, lineHeight: 1, color: "#8a8a96", padding: 4 }}>×</button>
        <div style={{ fontSize: 17, fontWeight: 800, marginBottom: 14, color: "#1c1c22" }}>{p.title}</div>
        <pre style={{ fontFamily: "inherit", fontSize: 13, lineHeight: 1.75, color: "#3f3f46", whiteSpace: "pre-wrap", margin: 0 }}>{p.body}</pre>
      </div>
    </div>
  );
}

function LoginScreen({ onLogin }) {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [err, setErr] = useState("");
  const [policy, setPolicy] = useState(null); // 'terms' | 'privacy' | 'help'
  // 비밀번호 재설정 팝업
  const [showReset, setShowReset] = useState(false);
  const [resetEmail, setResetEmail] = useState("");
  const [resetBusy, setResetBusy] = useState(false);
  const [resetMsg, setResetMsg] = useState("");
  const [resetErr, setResetErr] = useState("");

  const openReset = () => {setResetEmail(email);setResetMsg("");setResetErr("");setShowReset(true);};
  const sendReset = async () => {
    setResetErr(""); setResetMsg("");
    if (!resetEmail.trim()) {setResetErr("이메일을 입력해 주세요");return;}
    if (!window.__auth || !window.__auth.resetPassword) {setResetErr("서버 설정이 없어 메일을 보낼 수 없어요");return;}
    setResetBusy(true);
    const r = await window.__auth.resetPassword(resetEmail.trim());
    setResetBusy(false);
    if (r && r.ok) {
      setResetMsg("재설정 메일을 보냈어요. 메일함(스팸함 포함)을 확인해 주세요.");
    } else {
      const raw = (r && r.error) || '';
      // Supabase 영문 오류를 한국어로 변환 — 사용자에게 영문 노출 금지
      const korean =
        /invalid|disposable|blocked/i.test(raw) ? '이 이메일 주소로는 메일을 보낼 수 없습니다. 회사 이메일을 입력해 주세요.' :
        /not found|no user/i.test(raw) ? '등록되지 않은 이메일입니다.' :
        /rate.limit|too many/i.test(raw) ? '잠시 후 다시 시도해 주세요.' :
        raw ? '메일 발송에 실패했습니다.' : '메일 발송에 실패했습니다.';
      setResetErr(korean);
    }
  };

  const submit = async (e) => {
    e?.preventDefault();
    setErr("");
    setLoading(true);
    try {
      const normalizedEmail = email.trim().toLowerCase();
      const localAccount = window.__BANNERLY_LOCAL_TEST_ACCOUNT;
      if (localAccount && normalizedEmail === localAccount.email && password === localAccount.password) {
        const localUser = { id: "local-qa-user", email: localAccount.email, local: true };
        const localProfile = { email: localAccount.email, name: localAccount.name, role: localAccount.role };
        window.__bannerlyLocalQa = true;
        window.__bannerlyUser = localAccount.email;
        window.__bannerlyUserId = localUser.id;
        window.__bannerlyName = localAccount.name;
        window.__bannerlyRole = localAccount.role;
        onLogin(localUser, localProfile);
        return;
      }
      window.__bannerlyLocalQa = false;
      // 서버(Supabase) 설정이 없으면(로컬 폴백) 이메일만으로 통과
      if (!window.__auth || !window.__auth.hasConfig()) {
        onLogin({ email }, { role: "user" });
        return;
      }
      const res = await window.__auth.signIn(normalizedEmail, password);
      if (!res.ok) {
        const message = /invalid login credentials/i.test(res.error || "")
          ? "이메일 또는 비밀번호가 올바르지 않습니다"
          : (res.error || "이메일 또는 비밀번호가 올바르지 않습니다");
        setErr(message);
        setLoading(false);
        return;
      }
      onLogin(res.user, res.profile);
    } catch (e2) {
      setErr("로그인 중 오류가 발생했습니다. 잠시 후 다시 시도해 주세요.");
      setLoading(false);
    }
  };

  return (
    <div className="login-shell">
      {/* Left visual panel */}
      <aside className="login-visual">
        <div className="login-visual-inner">
          <div className="login-brand"></div>

          <div style={{ marginTop: "auto" }}>
            <h1 style={{ fontSize: 32, fontWeight: 700, lineHeight: 1.2, letterSpacing: "-0.02em", margin: 0, color: "white" }}>
              이커머스 배너,<br/>이제 5분이면 됩니다.
            </h1>
            <p style={{ fontSize: 14, color: "rgba(255,255,255,.75)", marginTop: 16, lineHeight: 1.6 }}>
              AI 누끼 자동 처리부터 가이드 준수 배치까지.<br/>
              디자이너 없이도 일관된 배너를 만드세요.
            </p>

            <div className="login-features">
              <Feature icon={<I.Wand size={14}/>} text="AI 누끼 자동 처리"/>
              <Feature icon={<I.Layers size={14}/>} text="가이드 기반 자동 배치"/>
              <Feature icon={<I.Sparkles size={14}/>} text="대비 · 색상 자동 보정"/>
            </div>
          </div>
        </div>
      </aside>

      {/* Right form */}
      <main className="login-form-pane">
        <div className="login-form-card">
          <div style={{ marginBottom: 28 }}>
            <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: "-0.01em", color: "var(--text-0)" }}>
              로그인
            </div>
            <div style={{ fontSize: 13, color: "var(--text-2)", marginTop: 6 }}>
              회사 계정으로 로그인하세요
            </div>
          </div>

          <form onSubmit={submit}>
            <div style={{ marginBottom: 14 }}>
              <div className="login-label">이메일</div>
              <input
                className="login-input"
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                placeholder="name@company.com"
                autoFocus
              />
            </div>

            <div style={{ marginBottom: 14 }}>
              <div className="login-label">
                <span>비밀번호</span>
              </div>
              <input
                className="login-input"
                type="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="••••••••"
              />
            </div>

            {/* 로그인 상태는 Supabase 세션이 항상 유지되므로 별도 체크박스 없음 */}

            {err && (
              <div style={{ margin: "4px 0 12px", padding: "9px 12px", borderRadius: 8, background: "#fdecec", color: "#c0392b", fontSize: 12.5, lineHeight: 1.4 }}>
                {err}
              </div>
            )}

            <button
              type="submit"
              className="login-submit"
              disabled={loading}
            >
              {loading ? (
                <>
                  <span className="login-spinner"/> 로그인 중…
                </>
              ) : (
                <>
                  로그인 <I.Right size={14}/>
                </>
              )}
            </button>
          </form>

          <div style={{ marginTop: 16, textAlign: "center" }}>
            <a href="#" className="login-link" onClick={(e) => {e.preventDefault();openReset();}}>비밀번호를 잊으셨나요?</a>
          </div>

          {/* [보류] SSO / Microsoft — 회사 IdP 연동(엔터프라이즈) 후 활성화. 복원 시 주석 해제.
          <div className="login-divider"><span>또는</span></div>
          <div className="login-sso">
            <button type="button" className="sso-btn"><SSOIcon kind="sso"/> SSO로 로그인</button>
            <button type="button" className="sso-btn"><SSOIcon kind="ms"/> Microsoft 계정</button>
          </div>
          */}

        </div>

        {policy && <PolicyModal kind={policy} onClose={() => setPolicy(null)} />}

        {showReset && (
          <div onClick={() => setShowReset(false)} style={{ position: "fixed", inset: 0, background: "rgba(20,20,26,.45)", display: "grid", placeItems: "center", zIndex: 10000 }}>
            <div onClick={(e) => e.stopPropagation()} style={{ position: "relative", width: 360, maxWidth: "92vw", background: "#fff", borderRadius: 16, padding: 24, boxShadow: "0 12px 40px rgba(0,0,0,.2)" }}>
              <button onClick={() => setShowReset(false)} title="닫기" style={{ position: "absolute", top: 14, right: 14, border: "none", background: "none", cursor: "pointer", fontSize: 22, lineHeight: 1, color: "#8a8a96", padding: 4 }}>×</button>
              <div style={{ fontSize: 17, fontWeight: 800, marginBottom: 6, color: "var(--text-0)" }}>비밀번호 재설정</div>
              <div style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 16, lineHeight: 1.5 }}>가입한 이메일 주소를 입력하면 재설정 링크를 보내드려요.</div>
              <input className="login-input" type="email" placeholder="name@company.com" value={resetEmail} autoFocus
                onChange={(e) => setResetEmail(e.target.value)} onKeyDown={(e) => {if (e.key === "Enter") sendReset();}} style={{ marginBottom: 12 }} />
              {resetErr && <div style={{ margin: "0 0 12px", padding: "9px 12px", borderRadius: 8, background: "#fdecec", color: "#c0392b", fontSize: 12.5 }}>{resetErr}</div>}
              {resetMsg && <div style={{ margin: "0 0 12px", padding: "9px 12px", borderRadius: 8, background: "#e9f7ef", color: "#12833f", fontSize: 12.5, lineHeight: 1.4 }}>{resetMsg}</div>}
              <button className="login-submit" style={{ width: "100%" }} disabled={resetBusy} onClick={sendReset}>{resetBusy ? "보내는 중…" : "재설정 메일 보내기"}</button>
            </div>
          </div>
        )}

        <footer className="login-footer">
          <span>© 2025 Bannerly</span>
          <div style={{ display: "flex", gap: 14 }}>
            <a href="#" className="login-link" onClick={(e) => {e.preventDefault();setPolicy('terms');}}>서비스 약관</a>
            <a href="#" className="login-link" onClick={(e) => {e.preventDefault();setPolicy('privacy');}}>개인정보처리방침</a>
            <a href="#" className="login-link" onClick={(e) => {e.preventDefault();setPolicy('help');}}>도움말</a>
          </div>
        </footer>
      </main>
    </div>
  );
}

function Feature({ icon, text }) {
  return (
    <div className="login-feature">
      <span className="login-feature-ic">{icon}</span>
      <span>{text}</span>
    </div>
  );
}

function Stat({ n, label }) {
  return (
    <div className="login-stat">
      <div className="login-stat-n">{n}</div>
      <div className="login-stat-l">{label}</div>
    </div>
  );
}

function SSOIcon({ kind }) {
  if (kind === "ms") {
    return (
      <svg width="14" height="14" viewBox="0 0 23 23">
        <rect x="1" y="1" width="10" height="10" fill="#f25022"/>
        <rect x="12" y="1" width="10" height="10" fill="#7fba00"/>
        <rect x="1" y="12" width="10" height="10" fill="#00a4ef"/>
        <rect x="12" y="12" width="10" height="10" fill="#ffb900"/>
      </svg>
    );
  }
  return (
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="3" y="11" width="18" height="11" rx="2"/>
      <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
    </svg>
  );
}

Object.assign(window, { LoginScreen });
