/* Auth screen — Login / Sign-up 목업
 * localStorage 기반. window.CIS.login/signUp 사용.
 * mode: 'login' | 'signup'
 */
function Auth({ mode = 'login', onNavigate, onAuthed }) {
  const [tab, setTab] = useState(mode);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [name, setName] = useState('');
  const [msg, setMsg] = useState(null);   // { type: 'error' | 'ok', text }
  const [busy, setBusy] = useState(false);

  useEffect(() => { setTab(mode); }, [mode]);
  useEffect(() => { setMsg(null); }, [tab]);

  function submit(e) {
    e && e.preventDefault && e.preventDefault();
    if (busy) return;
    setBusy(true);
    setTimeout(() => {   // 목업 딜레이
      const fn = tab === 'signup' ? CIS.signUp : CIS.login;
      const res = fn({ email: email.trim(), password, name: name.trim() });
      if (res.ok) {
        setMsg({ type: 'ok', text: (tab === 'signup' ? '가입 완료 · Signed up' : '로그인 완료 · Logged in') });
        onAuthed && onAuthed(res.user);
        setTimeout(() => onNavigate('landing'), 400);
      } else {
        setMsg({ type: 'error', text: res.msg });
      }
      setBusy(false);
    }, 320);
  }

  return (
    <div style={{
      minHeight: 'calc(100vh - 68px)',
      background: 'radial-gradient(120% 90% at 15% 0%, #E9EEFB 0%, var(--neutral-25) 55%)',
      padding: '48px 20px', display: 'flex', justifyContent: 'center', alignItems: 'flex-start',
    }}>
      <div style={{
        width: '100%', maxWidth: 440,
        background: 'var(--neutral-0)', borderRadius: 20,
        border: '1px solid var(--border-default)', boxShadow: 'var(--shadow-lg)',
        padding: 36,
      }}>
        {/* Brand */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 24 }}>
          <img src="../../assets/logo-mark.svg" width="32" height="32" alt="" style={{ borderRadius: 8 }}/>
          <div style={{ lineHeight: 1.15 }}>
            <div style={{ fontSize: 13, fontWeight: 700, letterSpacing: '-0.01em' }}>Career Intelligence Suite</div>
            <div style={{ fontSize: 10.5, color: 'var(--fg-3)', letterSpacing: '0.14em', fontWeight: 500 }}>ACCOUNT</div>
          </div>
        </div>

        {/* Tabs */}
        <div style={{
          display: 'flex', background: 'var(--neutral-100)', padding: 4, borderRadius: 10,
          marginBottom: 24, gap: 4,
        }}>
          {[
            { id: 'login',  ko: '로그인', en: 'Login' },
            { id: 'signup', ko: '회원가입', en: 'Sign up' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              flex: 1, padding: '9px 12px', borderRadius: 8,
              background: tab === t.id ? 'var(--neutral-0)' : 'transparent',
              color: tab === t.id ? 'var(--fg-1)' : 'var(--fg-3)',
              border: 'none', cursor: 'pointer',
              fontSize: 13, fontWeight: tab === t.id ? 700 : 500,
              boxShadow: tab === t.id ? 'var(--shadow-xs)' : 'none',
              transition: 'all 140ms',
              fontFamily: 'var(--font-sans)',
            }}>
              {t.ko} <span style={{ fontSize: 11, color: 'var(--fg-3)', fontWeight: 500 }}>({t.en})</span>
            </button>
          ))}
        </div>

        {/* Title */}
        <h1 style={{
          fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em', margin: '0 0 6px',
        }}>{tab === 'signup' ? '3분 만에 시작하기' : '다시 오신 걸 환영해요'}</h1>
        <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: '0 0 22px' }}>
          {tab === 'signup'
            ? 'AI 모의 면접과 지원 현황을 하나의 계정으로 · Start with one account.'
            : '지원 이력 · 모의 면접 결과가 계정에 저장돼요 · Your history is saved.'}
        </p>

        <form onSubmit={submit} style={{ display: 'grid', gap: 14 }}>
          {tab === 'signup' && (
            <Field label="이름 (Name)" required>
              <input value={name} onChange={e => setName(e.target.value)}
                placeholder="한지현" autoComplete="name"
                style={fieldStyle}/>
            </Field>
          )}
          <Field label="이메일 (Email)" required>
            <input type="email" value={email} onChange={e => setEmail(e.target.value)}
              placeholder="you@example.com" autoComplete="email"
              style={fieldStyle} required/>
          </Field>
          <Field label="비밀번호 (Password)" required
            hint={tab === 'signup' ? '8자 이상 · 8+ characters' : null}>
            <input type="password" value={password} onChange={e => setPassword(e.target.value)}
              placeholder="••••••••" autoComplete={tab === 'signup' ? 'new-password' : 'current-password'}
              style={fieldStyle} required minLength={tab === 'signup' ? 8 : 1}/>
          </Field>

          {msg && (
            <div style={{
              padding: '10px 12px',
              background: msg.type === 'error' ? 'var(--danger-50, #FDECEC)' : 'var(--success-50, #E7F7EE)',
              color:      msg.type === 'error' ? 'var(--danger-600, #B91C1C)' : 'var(--success-700, #0A6D30)',
              borderRadius: 8, fontSize: 12.5, fontWeight: 500,
              display: 'flex', alignItems: 'center', gap: 8,
            }}>
              <Icon name={msg.type === 'error' ? 'alert-circle' : 'check-circle-2'} size={14}/>
              {msg.text}
            </div>
          )}

          <button type="submit" disabled={busy} style={{
            marginTop: 4, padding: '13px 16px',
            background: busy ? 'var(--brand-300)' : 'var(--brand-500)',
            color: '#fff', border: 'none', borderRadius: 10,
            fontSize: 14.5, fontWeight: 700, cursor: busy ? 'wait' : 'pointer',
            fontFamily: 'var(--font-sans)', letterSpacing: '-0.005em',
            display: 'inline-flex', justifyContent: 'center', alignItems: 'center', gap: 6,
          }}>
            {busy && <Icon name="loader-2" size={14}/>}
            {tab === 'signup' ? '회원가입 (Sign up)' : '로그인 (Login)'}
          </button>
        </form>

        {/* Divider */}
        <div style={{
          display: 'flex', alignItems: 'center', gap: 12,
          fontSize: 11, color: 'var(--fg-3)', margin: '22px 0 16px',
        }}>
          <div style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }}/>
          또는 · OR
          <div style={{ flex: 1, height: 1, background: 'var(--border-subtle)' }}/>
        </div>

        {/* Social (mockup) */}
        <div style={{ display: 'grid', gap: 8 }}>
          <SocialBtn icon="google" label="Google로 계속하기 · Continue with Google"/>
          <SocialBtn icon="github" label="GitHub로 계속하기 · Continue with GitHub"/>
        </div>

        {/* Footer note */}
        <div style={{
          marginTop: 22, padding: 12, background: 'var(--neutral-50)',
          borderRadius: 8, fontSize: 11.5, color: 'var(--fg-3)', lineHeight: 1.55,
        }}>
          <b style={{ color: 'var(--fg-2)' }}>ℹ️ 데모 안내 · Demo notice</b><br/>
          본 데모는 localStorage 기반 목업입니다. 실제 개인정보는 서버로 전송되지 않으며, 브라우저에만 저장돼요.
          <br/>
          <span style={{ color: 'var(--fg-3)' }}>This is a localStorage-based mockup. No data leaves your browser.</span>
        </div>

        <div style={{ marginTop: 18, textAlign: 'center', fontSize: 12.5, color: 'var(--fg-3)' }}>
          {tab === 'login' ? (
            <>계정이 없으신가요? · New here?{' '}
              <a onClick={() => setTab('signup')} style={linkStyle}>회원가입 (Sign up)</a>
            </>
          ) : (
            <>이미 계정이 있으신가요? · Have an account?{' '}
              <a onClick={() => setTab('login')} style={linkStyle}>로그인 (Login)</a>
            </>
          )}
        </div>
      </div>
    </div>
  );
}

const fieldStyle = {
  width: '100%', padding: '11px 12px',
  border: '1px solid var(--border-default)', borderRadius: 8,
  fontSize: 13.5, fontFamily: 'var(--font-sans)', outline: 'none',
  background: 'var(--neutral-0)', color: 'var(--fg-1)',
  boxSizing: 'border-box',
};
const linkStyle = {
  color: 'var(--brand-600)', fontWeight: 600, cursor: 'pointer', textDecoration: 'none',
};

function Field({ label, hint, required, children }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{
        fontSize: 12, fontWeight: 600, color: 'var(--fg-2)',
        marginBottom: 6, display: 'flex', justifyContent: 'space-between',
        gap: 8, alignItems: 'baseline', flexWrap: 'wrap',
      }}>
        <span style={{ whiteSpace: 'nowrap' }}>{label}{required && <span style={{ color: 'var(--danger-500, #DC2E2E)', marginLeft: 3 }}>*</span>}</span>
        {hint && <span style={{ fontWeight: 400, color: 'var(--fg-3)', whiteSpace: 'nowrap' }}>{hint}</span>}
      </div>
      {children}
    </label>
  );
}

function SocialBtn({ icon, label }) {
  return (
    <button type="button" onClick={() => alert('데모에서는 소셜 로그인이 비활성화되어 있어요.\nSocial login is disabled in this demo.')}
      style={{
        padding: '11px 14px', background: 'var(--neutral-0)',
        border: '1px solid var(--border-strong)', borderRadius: 8,
        fontSize: 13, fontWeight: 500, cursor: 'pointer',
        fontFamily: 'var(--font-sans)', color: 'var(--fg-1)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
      <Icon name={icon === 'google' ? 'chrome' : 'github'} size={15}/>
      {label}
    </button>
  );
}

window.Auth = Auth;
