// Login.jsx — orb + reveal panel. Wired to POST /auth/login (sign-in mode)
// and POST /auth/register (sign-up mode, single-toggle UI).
function Login({ onLogin }) {
  const [open, setOpen] = React.useState(false);
  const [mode, setMode] = React.useState('signin'); // 'signin' | 'signup'
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [password2, setPassword2] = React.useState('');
  const [displayName, setDisplayName] = React.useState('');
  const [invite, setInvite] = React.useState('');
  const [tos, setTos] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const panelRef = React.useRef(null);

  // On mobile, the panel sits below the orb in document flow. After the user
  // taps the orb, smoothly scroll the panel to the viewport center so the
  // form is immediately visible without needing a manual swipe. Desktop is
  // unaffected (panel is centered absolutely there).
  React.useEffect(() => {
    if (!open) return;
    const t = setTimeout(() => {
      if (panelRef.current && window.matchMedia('(max-width: 820px)').matches) {
        panelRef.current.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    }, 60);
    return () => clearTimeout(t);
  }, [open]);

  const switchTo = (next) => {
    setMode(next); setErr(null); setPassword(''); setPassword2('');
  };

  // Lightweight strength estimator. Counts character classes + length tier.
  // Not a security boundary — backend enforces a min length of 8 regardless.
  const strength = React.useMemo(() => {
    if (!password) return { label: '', pct: 0, tone: 'fg-5' };
    const classes = [/[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/].filter(r => r.test(password)).length;
    const len = password.length;
    let score = 0;
    if (len >= 8)  score++;
    if (len >= 12) score++;
    if (classes >= 2) score++;
    if (classes >= 3) score++;
    const tiers = [
      { label: '매우 약함', pct: 10,  tone: 'zg-danger' },
      { label: '약함',     pct: 30,  tone: 'zg-danger' },
      { label: '보통',     pct: 55,  tone: 'fg-4' },
      { label: '강함',     pct: 80,  tone: 'fg-2' },
      { label: '매우 강함', pct: 100, tone: 'fg-2' },
    ];
    return tiers[Math.min(score, 4)];
  }, [password]);

  const canSubmit = mode === 'signin'
    ? !!(email && password)
    : !!(email && password && password === password2 && password.length >= 8 && tos);

  const submit = async (e) => {
    e.preventDefault();
    if (busy || !canSubmit) return;
    setBusy(true); setErr(null);
    try {
      let data;
      if (mode === 'signin') {
        data = await window.API.login(email.trim(), password);
      } else {
        data = await window.API.register({
          email: email.trim(),
          password,
          display_name: displayName.trim() || null,
          invite_code: invite.trim() || null,
          accepted_tos: tos,
        });
      }
      if (onLogin) onLogin(data.access_token, data.user);
    } catch (ex) {
      setErr(ex.message || (mode === 'signin' ? 'Sign-in failed' : 'Sign-up failed'));
    } finally {
      setBusy(false);
    }
  };

  const fillGuest = () => { setEmail('guest'); setPassword('guest'); setErr(null); setMode('signin'); };

  return (
    <div className={'ch-login' + (open ? ' open' : '')} data-screen-label="Login">
      <div className="scene">
        <div className="orb" onClick={() => setOpen(true)}>
          <div className="ring r3"></div>
          <div className="ring r2"></div>
          <div className="ring"></div>
          <div className="glow2"></div>
          <div className="glow"></div>
          <div className="halo"></div>
          <img className="logo" src="../../assets/zigu-logo-gold.png" alt="ZIGU"/>
        </div>
        <div className="hint">로고를 눌러 시작</div>
        <form className="panel" onSubmit={submit} ref={panelRef}>
          <div className="eb">GBR · 개발자</div>
          <h2>{mode === 'signin' ? '다시 오신 걸 환영합니다.' : '계정을 만들어 시작해요.'}</h2>

          <label className="field">이메일 {mode === 'signin' && <span style={{color:'var(--fg-5)', fontFamily:'var(--font-mono)', fontSize:10, fontWeight:400}}>또는 사용자명</span>}
            <input
              type={mode === 'signin' ? 'text' : 'email'} required value={email}
              onChange={e => setEmail(e.target.value)}
              autoComplete={mode === 'signin' ? 'username' : 'email'}
              spellCheck="false" autoCapitalize="off"
              placeholder="you@example.com"
            />
          </label>

          {mode === 'signup' && (
            <label className="field">표시 이름 <span style={{color:'var(--fg-5)', fontFamily:'var(--font-mono)', fontSize:10, fontWeight:400}}>선택</span>
              <input
                type="text" value={displayName}
                onChange={e => setDisplayName(e.target.value)}
                autoComplete="name" maxLength={80}
                placeholder="홍길동"
              />
            </label>
          )}

          <label className="field">비밀번호
            <input
              type="password" required value={password}
              onChange={e => setPassword(e.target.value)}
              autoComplete={mode === 'signin' ? 'current-password' : 'new-password'}
              placeholder="••••••••" minLength={mode === 'signup' ? 8 : undefined}
            />
          </label>

          {mode === 'signup' && (
            <>
              <div style={{margin:'-6px 0 4px', display:'flex', alignItems:'center', gap:8}}>
                <div style={{flex:1, height:4, background:'var(--bg-canvas)', borderRadius:2, overflow:'hidden'}}>
                  <div style={{
                    width: strength.pct + '%', height:'100%',
                    background: 'var(--' + strength.tone + ')',
                    transition: 'width 0.15s ease',
                  }}/>
                </div>
                <span style={{fontFamily:'var(--font-mono)', fontSize:10, color:'var(--' + strength.tone + ')', minWidth:60, textAlign:'right'}}>
                  {strength.label}
                </span>
              </div>
              <label className="field">비밀번호 확인
                <input
                  type="password" required value={password2}
                  onChange={e => setPassword2(e.target.value)}
                  autoComplete="new-password" placeholder="••••••••"
                />
                {password2 && password !== password2 && (
                  <span style={{color:'var(--zg-danger)', fontSize:11, marginTop:4}}>비밀번호가 일치하지 않습니다.</span>
                )}
              </label>
              <label className="field">초대 코드
                <input
                  type="text" value={invite}
                  onChange={e => setInvite(e.target.value)}
                  spellCheck="false" autoCapitalize="off"
                  maxLength={64}
                  placeholder="관리자에게 받은 코드"
                  style={{fontFamily:'var(--font-mono)'}}
                />
              </label>
              <label style={{display:'flex', gap:8, alignItems:'flex-start', fontSize:12, lineHeight:1.5}}>
                <input
                  type="checkbox" checked={tos}
                  onChange={e => setTos(e.target.checked)}
                  style={{marginTop:3, flex:'none'}}
                />
                <span>
                  <a href="terms.html"   target="_blank" rel="noopener">이용약관</a>{' '}및{' '}
                  <a href="privacy.html" target="_blank" rel="noopener">개인정보처리방침</a>에 동의합니다.
                </span>
              </label>
            </>
          )}

          {mode === 'signin' && (
            <div className="row">
              <label style={{display:'flex', gap: 6, alignItems:'center'}}>
                <input type="checkbox" defaultChecked/> 로그인 유지
              </label>
              <a onClick={() => alert('비밀번호 분실 시 관리자에게 초기화를 요청하세요.')} style={{cursor:'pointer'}}>비밀번호 찾기?</a>
            </div>
          )}

          {err && (
            <div style={{
              fontSize: 12, color: 'var(--zg-danger)',
              border: '1px solid rgba(201,92,74,0.4)', background: 'rgba(201,92,74,0.08)',
              borderRadius: 'var(--r-2)', padding: '8px 10px', marginTop: 4, lineHeight: 1.4,
            }} role="alert">{err}</div>
          )}

          <button type="submit" className="primary" disabled={busy || !canSubmit}>
            {busy
              ? (mode === 'signin' ? '로그인 중…' : '가입 중…')
              : (mode === 'signin' ? '로그인' : '계정 만들기')}
          </button>

          <div className="divider">또는</div>

          {mode === 'signin' ? (
            <>
              <button type="button" className="sso" onClick={() => switchTo('signup')} disabled={busy}>
                계정이 없으신가요? 회원가입
              </button>
              <button type="button" className="sso" onClick={fillGuest} disabled={busy} style={{marginTop:6}}>
                데모 · guest / guest
              </button>
            </>
          ) : (
            <button type="button" className="sso" onClick={() => switchTo('signin')} disabled={busy}>
              이미 계정이 있으신가요? 로그인
            </button>
          )}

          <div className="foot">서버 · {(window.API && window.API.serverUrl) || '/api'}</div>
        </form>
      </div>
    </div>
  );
}
window.Login = Login;
