/* Phase 3 A.5.1 PoC (2026-05-06): Supabase Auth 게이트 컴포넌트.
 *
 * - source='mock' → 게이트 비활성, children 그대로 렌더 (mockUsers/RoleSim 시뮬레이터 무손상).
 * - source='supabase' + 미인증 → <LoginForm /> 렌더 (로그인 후 onAuthStateChange 로 자동 전환).
 * - source='supabase' + 인증 → children 렌더.
 *
 * 사용:
 *   <SupabaseAuthGate>
 *     <App />  // 평소 페이지 본체
 *   </SupabaseAuthGate>
 *
 * 의존: window.c200Auth (lib/supabaseAuth_v1_0506.js).
 *       미로드/미초기화 시 게이트 비활성 (graceful fallback).
 */
(function () {
  if (typeof window === 'undefined' || !window.React) return;
  const React = window.React;

  function LoginForm() {
    const [email, setEmail] = React.useState('');
    const [password, setPassword] = React.useState('');
    const [busy, setBusy] = React.useState(false);
    const [error, setError] = React.useState(null);

    const onSubmit = async function (e) {
      e.preventDefault();
      if (!email || !password) { setError('이메일/비밀번호 입력'); return; }
      setBusy(true);
      setError(null);
      const result = await window.c200Auth.signInWithPassword(email, password);
      setBusy(false);
      if (!result.ok) setError(result.reason || '로그인 실패');
      /* 성공 시 onAuthStateChange 가 게이트 상태 자동 갱신 */
    };

    const onSwitchToMock = function () {
      try { window.localStorage.setItem('c200-data-source', 'mock'); } catch (_) {}
      const url = new URL(window.location.href);
      url.searchParams.delete('source');
      window.location.href = url.toString();
    };

    const wrapStyle = {
      minHeight: '100vh',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      background: '#0F172A',
      padding: '24px',
    };
    const cardStyle = {
      background: '#fff',
      borderRadius: '12px',
      padding: '32px 36px',
      width: 'min(100%, 380px)',
      boxShadow: '0 12px 40px rgba(0,0,0,0.25)',
      fontFamily: 'Pretendard Variable, sans-serif',
    };
    const labelStyle = { display: 'block', fontSize: '13px', color: '#475569', marginBottom: '6px', marginTop: '14px' };
    const inputStyle = {
      width: '100%', padding: '10px 12px', fontSize: '14px',
      border: '1px solid #cbd5e1', borderRadius: '8px', boxSizing: 'border-box',
    };
    const btnStyle = {
      width: '100%', padding: '11px', marginTop: '20px',
      background: '#0F766E', color: '#fff', border: 'none', borderRadius: '8px',
      fontSize: '14px', fontWeight: 600, cursor: busy ? 'wait' : 'pointer',
      opacity: busy ? 0.7 : 1,
    };
    const linkStyle = {
      display: 'block', marginTop: '14px', textAlign: 'center',
      fontSize: '12px', color: '#64748b', cursor: 'pointer',
      background: 'none', border: 'none', width: '100%',
    };

    return React.createElement('div', { style: wrapStyle },
      React.createElement('form', { style: cardStyle, onSubmit: onSubmit },
        React.createElement('div', { style: { fontSize: '18px', fontWeight: 700, color: '#0F172A' } },
          'Challenge200 — Supabase Auth (A.5.1 PoC)'),
        React.createElement('div', { style: { fontSize: '12px', color: '#64748b', marginTop: '6px', lineHeight: 1.5 } },
          'source=supabase 모드. mockUsers/RoleSim 와 별도. ' +
          'Supabase 대시보드에서 만든 사용자 (admin / parent) 로 로그인.'),
        React.createElement('label', { style: labelStyle, htmlFor: 'auth-email' }, '이메일'),
        React.createElement('input', {
          id: 'auth-email', type: 'email', style: inputStyle, autoComplete: 'username',
          value: email, onChange: function (e) { setEmail(e.target.value); }, disabled: busy,
        }),
        React.createElement('label', { style: labelStyle, htmlFor: 'auth-password' }, '비밀번호'),
        React.createElement('input', {
          id: 'auth-password', type: 'password', style: inputStyle, autoComplete: 'current-password',
          value: password, onChange: function (e) { setPassword(e.target.value); }, disabled: busy,
        }),
        error && React.createElement('div', {
          style: { marginTop: '12px', fontSize: '13px', color: '#b91c1c' }
        }, error),
        React.createElement('button', { type: 'submit', style: btnStyle, disabled: busy },
          busy ? '로그인 중…' : '로그인'),
        React.createElement('button', { type: 'button', style: linkStyle, onClick: onSwitchToMock },
          '← mock 모드로 돌아가기')
      )
    );
  }

  function LoadingSplash() {
    return React.createElement('div', {
      style: {
        minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: '#0F172A', color: '#94a3b8', fontFamily: 'Pretendard Variable, sans-serif',
        fontSize: '14px',
      }
    }, '인증 확인 중…');
  }

  function SupabaseAuthGate(props) {
    /* initial state 를 sync 결정 — supabase 모드 + 미인증 시 children 의 useEffect
       가 한 번이라도 돌면 안 됨 (예: teacher/home 의 RoleSim redirect 가드).
       mount 첫 렌더부터 정확한 분기로 children 렌더 차단. */
    const [state, setState] = React.useState(function () {
      const auth = window.c200Auth;
      const active = !!(auth && auth.isGateActive && auth.isGateActive());
      return { loading: active, gateActive: active, user: null };
    });

    React.useEffect(function () {
      const auth = window.c200Auth;
      if (!auth || !auth.isGateActive || !auth.isGateActive()) {
        setState({ loading: false, gateActive: false, user: null });
        return;
      }

      let alive = true;
      const refresh = function () {
        auth.getCurrentUser().then(function (me) {
          if (!alive) return;
          setState({ loading: false, gateActive: true, user: me });
        });
      };
      refresh();

      const sub = auth.onAuthStateChange(function (event, session) {
        if (!alive) return;
        refresh();
      });

      return function () {
        alive = false;
        if (sub && sub.unsubscribe) sub.unsubscribe();
      };
    }, []);

    if (!state.gateActive) return props.children || null;
    if (state.loading) return React.createElement(LoadingSplash);
    if (!state.user) return React.createElement(LoginForm);
    return props.children || null;
  }

  window.SupabaseAuthGate = SupabaseAuthGate;
  window.SupabaseAuthLoginForm = LoginForm;
})();
