// Auth system — signup, login, role-based access
// getUsers, saveUsers, getAuth, setAuth, clearAuth are defined in firebase-init.jsx (Firestore)

// ═══════════════════════════════════════════════════════════
// LOGIN SCREEN
// ═══════════════════════════════════════════════════════════
function AuthLogin({ onLogin, onGoSignup }) {
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [showReset, setShowReset] = React.useState(false);
  const [resetEmail, setResetEmail] = React.useState('');
  const [resetMsg, setResetMsg] = React.useState('');

  const submit = async () => {
    setErr('');
    if (!email || !pw) { setErr('이메일과 비밀번호를 입력하세요'); return; }
    setLoading(true);
    try {
      // Firebase Auth 로그인
      await firebaseLogin(email, pw);
      // Firestore 사용자 데이터 확인
      const users = await getUsers();
      const user = users.find(u => u.email === email);
      if (!user) { setErr('등록되지 않은 이메일입니다'); setLoading(false); return; }
      if (user.status === 'REJECTED') { setErr('가입이 반려되었습니다. 관리자에게 문의하세요.'); setLoading(false); return; }
      // 이메일 인증 확인 (관리자 제외)
      if (user.role !== 'admin' && !isEmailVerified()) {
        setErr('이메일 인증이 완료되지 않았습니다. 메일함을 확인해주세요.');
        setLoading(false);
        return;
      }
      // 이메일 인증 완료 시 PENDING_VERIFY → PENDING (관리자 승인 대기)
      if (user.status === 'PENDING_VERIFY' && isEmailVerified()) {
        await updateUserByEmail(user.email, { status: 'PENDING' });
        user.status = 'PENDING';
      }
      if (user.status === 'PENDING') { setErr('이메일 인증 완료! 관리자 승인 대기 중입니다.'); setLoading(false); return; }
      setAuth(user);
      onLogin(user);
    } catch(e) {
      if (e.code === 'auth/user-not-found') setErr('등록되지 않은 이메일입니다');
      else if (e.code === 'auth/wrong-password' || e.code === 'auth/invalid-credential') setErr('비밀번호가 일치하지 않습니다');
      else if (e.code === 'auth/too-many-requests') setErr('로그인 시도가 너무 많습니다. 잠시 후 다시 시도하세요.');
      else setErr('로그인 실패: ' + (e.message || ''));
    }
    setLoading(false);
  };

  const handleReset = async () => {
    setResetMsg('');
    if (!resetEmail) { setResetMsg('이메일을 입력하세요'); return; }
    try {
      await firebaseResetPassword(resetEmail);
      setResetMsg('비밀번호 재설정 메일을 발송했습니다. 메일함을 확인하세요.');
    } catch(e) {
      if (e.code === 'auth/user-not-found') setResetMsg('등록되지 않은 이메일입니다');
      else setResetMsg('발송 실패: ' + (e.message || ''));
    }
  };

  return (
    <div className="wu" style={{ height: '100vh', background: 'var(--wu-ink)', color: 'var(--wu-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
      <div style={{ width: 380, padding: '40px 32px', background: '#1A1A17' }}>
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'Archivo Black', fontSize: 28, letterSpacing: '-0.04em', lineHeight: 1 }}>
            <span style={{ color: 'var(--wu-paper)' }}>work</span>
            <span style={{ background: 'var(--wu-orange)', color: '#fff', padding: '1px 6px 0', fontStyle: 'italic', transform: 'skew(-8deg)' }}>up</span>
          </div>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginTop: 8, letterSpacing: '0.12em' }}>FRANCHISE PLATFORM · LOGIN</div>
        </div>

        {!showReset ? (
          <>
            <div style={{ marginBottom: 16 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 6, letterSpacing: '0.08em' }}>EMAIL</div>
              <input value={email} onChange={e => setEmail(e.target.value)} placeholder="your@email.com" className="kr"
                style={{ width: '100%', padding: '12px 14px', background: 'var(--wu-ink)', border: '1px solid #2A2A26', color: 'var(--wu-paper)', fontSize: 14, outline: 0 }}
                onKeyDown={e => e.key === 'Enter' && submit()} />
            </div>
            <div style={{ marginBottom: 16 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 6, letterSpacing: '0.08em' }}>PASSWORD</div>
              <input value={pw} onChange={e => setPw(e.target.value)} type="password" placeholder="••••••••" className="kr"
                style={{ width: '100%', padding: '12px 14px', background: 'var(--wu-ink)', border: '1px solid #2A2A26', color: 'var(--wu-paper)', fontSize: 14, outline: 0 }}
                onKeyDown={e => e.key === 'Enter' && submit()} />
            </div>

            {err && <div className="kr" style={{ fontSize: 12, color: 'var(--wu-orange)', marginBottom: 12, lineHeight: 1.4 }}>⚠ {err}</div>}

            <button onClick={submit} disabled={loading} className="wu-btn lime block" style={{ padding: '14px', fontSize: 14, width: '100%', opacity: loading ? 0.6 : 1 }}>
              {loading ? '로그인 중...' : '이메일 로그인'}
            </button>

            {/* 구분선 */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '18px 0' }}>
              <div style={{ flex: 1, height: 1, background: '#2A2A26' }} />
              <span className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>OR</span>
              <div style={{ flex: 1, height: 1, background: '#2A2A26' }} />
            </div>

            {/* Google 로그인 */}
            <button onClick={async () => {
              setErr(''); setLoading(true);
              try {
                const gUser = await firebaseGoogleLogin();
                const gEmail = gUser.email;
                // Firestore에 이미 있으면 바로 로그인
                const users = await getUsers();
                let user = users.find(u => u.email === gEmail);
                if (!user) {
                  // Google 첫 로그인 → 자동 회원가입 (승인 대기)
                  user = { email: gEmail, password: '', name: gUser.displayName || gEmail.split('@')[0], nickname: '', role: 'consumer', status: 'PENDING', createdAt: new Date().toISOString().split('T')[0], googleAuth: true };
                  await addUser(user);
                  setErr('Google 계정으로 가입되었습니다. 관리자 승인 후 이용 가능합니다.');
                  setLoading(false); return;
                }
                if (user.status === 'REJECTED') { setErr('가입이 반려되었습니다.'); setLoading(false); return; }
                if (user.status === 'PENDING' || user.status === 'PENDING_VERIFY') { setErr('관리자 승인 대기 중입니다.'); setLoading(false); return; }
                setAuth(user);
                onLogin(user);
              } catch(e) {
                if (e.code !== 'auth/popup-closed-by-user') setErr('Google 로그인 실패: ' + (e.message || ''));
              }
              setLoading(false);
            }} disabled={loading} style={{ width: '100%', padding: '12px 14px', background: '#fff', color: '#333', border: '1px solid #dadce0', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, cursor: loading ? 'not-allowed' : 'pointer', fontSize: 14, fontFamily: 'Pretendard', fontWeight: 600, opacity: loading ? 0.6 : 1 }}>
              <svg width="18" height="18" viewBox="0 0 48 48"><path fill="#EA4335" d="M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z"/><path fill="#4285F4" d="M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z"/><path fill="#FBBC05" d="M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z"/><path fill="#34A853" d="M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z"/></svg>
              Google 계정으로 로그인
            </button>

            {/* 카카오 로그인 */}
            <button onClick={async () => {
              setErr(''); setLoading(true);
              try {
                const kUser = await firebaseKakaoLogin();
                // 이메일이 있으면 이메일로, 없으면 카카오ID 기반 식별자 사용
                const kEmail = kUser.email || ('kakao_' + kUser.kakaoId + '@kakao.user');
                const users = await getUsers();
                // 이메일 또는 카카오ID로 기존 유저 찾기
                let user = users.find(u => u.email === kEmail || (u.kakaoId && u.kakaoId === String(kUser.kakaoId)));
                if (!user) {
                  user = { email: kEmail, password: '', name: kUser.name || '카카오회원', nickname: '', role: 'consumer', status: 'PENDING', createdAt: new Date().toISOString().split('T')[0], kakaoAuth: true, kakaoId: String(kUser.kakaoId), profileImage: kUser.profileImage || '' };
                  await addUser(user);
                  setErr('카카오 계정으로 가입되었습니다. 관리자 승인 후 이용 가능합니다.');
                  setLoading(false); return;
                }
                if (user.status === 'REJECTED') { setErr('가입이 반려되었습니다.'); setLoading(false); return; }
                if (user.status === 'PENDING' || user.status === 'PENDING_VERIFY') { setErr('관리자 승인 대기 중입니다.'); setLoading(false); return; }
                setAuth(user);
                onLogin(user);
              } catch(e) {
                if (e.code !== 'auth/popup-closed-by-user') setErr(e.message || '카카오 로그인 실패');
              }
              setLoading(false);
            }} disabled={loading} style={{ width: '100%', padding: '12px 14px', marginTop: 8, background: '#FEE500', color: '#191919', border: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10, cursor: loading ? 'not-allowed' : 'pointer', fontSize: 14, fontFamily: 'Pretendard', fontWeight: 600, opacity: loading ? 0.6 : 1, borderRadius: 0 }}>
              <svg width="18" height="18" viewBox="0 0 256 256"><path fill="#191919" d="M128 36C70.562 36 24 72.713 24 118c0 29.279 19.466 54.97 48.748 69.477l-12.5 45.723c-1.093 3.996 3.47 7.22 6.94 4.906L118.31 204.5c3.178.3 6.416.5 9.69.5 57.438 0 104-36.712 104-82S185.438 36 128 36"/></svg>
              카카오 계정으로 로그인
            </button>

            <div style={{ marginTop: 12, textAlign: 'center' }}>
              <button onClick={() => { setShowReset(true); setResetEmail(email); }} className="mono" style={{ fontSize: 11, color: 'var(--wu-mute)', background: 'none', border: 'none', cursor: 'pointer', textDecoration: 'underline' }}>비밀번호를 잊으셨나요?</button>
            </div>

            <div style={{ marginTop: 20, textAlign: 'center' }}>
              <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', lineHeight: 1.8 }}>
                계정이 없으신가요?
              </div>
              <div style={{ display: 'flex', gap: 8, marginTop: 8, justifyContent: 'center' }}>
                <button onClick={() => onGoSignup('consumer')} className="wu-btn ghost" style={{ fontSize: 11, padding: '8px 14px', color: 'var(--wu-paper)', borderColor: '#2A2A26' }}>일반회원 가입</button>
                <button onClick={() => onGoSignup('owner')} className="wu-btn ghost" style={{ fontSize: 11, padding: '8px 14px', color: 'var(--wu-paper)', borderColor: '#2A2A26' }}>점주회원 가입</button>
              </div>
            </div>
          </>
        ) : (
          <>
            <div className="display" style={{ fontSize: 20, marginBottom: 8 }}>비밀번호 재설정</div>
            <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', marginBottom: 16, lineHeight: 1.5 }}>가입한 이메일을 입력하면 비밀번호 재설정 링크를 보내드립니다.</div>
            <div style={{ marginBottom: 16 }}>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 6 }}>EMAIL</div>
              <input value={resetEmail} onChange={e => setResetEmail(e.target.value)} placeholder="your@email.com" className="kr"
                style={{ width: '100%', padding: '12px 14px', background: 'var(--wu-ink)', border: '1px solid #2A2A26', color: 'var(--wu-paper)', fontSize: 14, outline: 0 }}
                onKeyDown={e => e.key === 'Enter' && handleReset()} />
            </div>
            {resetMsg && <div className="kr" style={{ fontSize: 12, color: resetMsg.includes('발송') ? 'var(--wu-lime)' : 'var(--wu-orange)', marginBottom: 12, lineHeight: 1.4 }}>{resetMsg}</div>}
            <button onClick={handleReset} className="wu-btn block" style={{ padding: '14px', fontSize: 14, width: '100%', background: 'var(--wu-orange)', color: '#fff' }}>재설정 메일 발송</button>
            <button onClick={() => { setShowReset(false); setResetMsg(''); }} className="mono" style={{ display: 'block', width: '100%', marginTop: 12, textAlign: 'center', fontSize: 12, color: 'var(--wu-mute)', background: 'none', border: 'none', cursor: 'pointer' }}>← 로그인으로 돌아가기</button>
          </>
        )}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// SIGNUP — CONSUMER (email only, instant)
// ═══════════════════════════════════════════════════════════
function AuthSignupConsumer({ onBack, onSignup }) {
  const [form, setForm] = React.useState({ name: '', email: '', password: '', password2: '', nickname: '' });
  const [agreed, setAgreed] = React.useState(false);
  const [showPrivacy, setShowPrivacy] = React.useState(false);
  const [err, setErr] = React.useState('');

  const f = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const [loading, setLoading] = React.useState(false);
  const [done, setDone] = React.useState(false);

  const submit = async () => {
    setErr('');
    if (!form.name || !form.email || !form.password) { setErr('필수 항목을 모두 입력하세요'); return; }
    if (form.password.length < 6) { setErr('비밀번호는 6자 이상이어야 합니다'); return; }
    if (form.password !== form.password2) { setErr('비밀번호가 일치하지 않습니다'); return; }
    if (!agreed) { setErr('개인정보 수집·이용에 동의해주세요'); return; }
    setLoading(true);
    try {
      const users = await getUsers();
      if (users.find(u => u.email === form.email)) { setErr('이미 등록된 이메일입니다'); setLoading(false); return; }
      // Firebase Auth 회원가입 + 이메일 인증 발송
      await firebaseSignup(form.email, form.password);
      // Firestore에 사용자 정보 저장 (이메일 인증 전이라 PENDING 상태)
      const user = { email: form.email, password: form.password, name: form.name, nickname: form.nickname, role: 'consumer', status: 'PENDING_VERIFY', createdAt: new Date().toISOString().split('T')[0] };
      await addUser(user);
      setDone(true);
    } catch(e) {
      if (e.code === 'auth/email-already-in-use') setErr('이미 등록된 이메일입니다');
      else if (e.code === 'auth/weak-password') setErr('비밀번호가 너무 약합니다 (6자 이상)');
      else if (e.code === 'auth/invalid-email') setErr('유효하지 않은 이메일 형식입니다');
      else setErr('가입 실패: ' + (e.message || ''));
    }
    setLoading(false);
  };

  if (done) {
    return (
      <div className="wu" style={{ height: '100vh', background: 'var(--wu-ink)', color: 'var(--wu-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center', maxWidth: 400, padding: '0 20px' }}>
          <div style={{ width: 120, height: 120, borderRadius: 999, border: '1.5px dashed var(--wu-lime)', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 90, height: 90, borderRadius: 999, background: 'var(--wu-lime)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 36, color: 'var(--wu-ink)' }}>✉</div>
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--wu-lime)', marginTop: 24, letterSpacing: '0.12em' }}>EMAIL VERIFICATION SENT</div>
          <div className="display" style={{ fontSize: 32, marginTop: 8 }}>인증 메일 발송 완료</div>
          <div className="kr" style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 12, lineHeight: 1.6 }}>
            <strong>{form.email}</strong>으로 인증 메일을 발송했습니다.<br />
            메일의 인증 링크를 클릭한 후 관리자 승인을 받으면<br/>로그인하실 수 있습니다.
          </div>
          <button onClick={onBack} className="wu-btn" style={{ marginTop: 24, padding: '12px 24px', fontSize: 13, background: 'var(--wu-orange)', color: '#fff' }}>← 로그인 화면으로</button>
        </div>
      </div>
    );
  }

  return (
    <div className="wu wu-scroll" style={{ height: '100vh', background: 'var(--wu-bg)', overflow: 'auto', display: 'flex', justifyContent: 'center', padding: '40px 20px' }}>
      <div style={{ width: 400, padding: '36px 32px', background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', height: 'fit-content' }}>
        <button onClick={onBack} style={{ fontSize: 18, cursor: 'pointer', marginBottom: 16 }}>←</button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
          <span style={{ fontSize: 24 }}>🛍</span>
          <div className="display" style={{ fontSize: 24 }}>일반회원 가입</div>
        </div>
        <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', marginBottom: 24 }}>이메일 인증 후 관리자 승인 시 이용 가능</div>

        {[
          ['이름 *', 'name', 'text', '홍길동'],
          ['이메일 *', 'email', 'email', 'hello@gmail.com'],
          ['비밀번호 * (6자+)', 'password', 'password', '••••••••'],
          ['비밀번호 확인 *', 'password2', 'password', '••••••••'],
          ['닉네임 (선택)', 'nickname', 'text', 'workup.lover'],
        ].map(([label, key, type, ph]) => (
          <div key={key} style={{ marginBottom: 14 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4, letterSpacing: '0.06em' }}>{label.toUpperCase()}</div>
            <input value={form[key]} onChange={e => f(key, e.target.value)} type={type} placeholder={ph} className="kr"
              style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 14, fontWeight: 600, outline: 0 }} />
          </div>
        ))}

        {/* 개인정보 수집·이용 동의 */}
        <div style={{ marginBottom: 16, border: '1px solid var(--wu-line)', background: 'var(--wu-bg)' }}>
          <button onClick={() => setShowPrivacy(!showPrivacy)} style={{ width: '100%', padding: '10px 12px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', background: 'none', border: 'none', cursor: 'pointer' }}>
            <span className="kr" style={{ fontSize: 12, fontWeight: 700 }}>개인정보 수집·이용 동의 (필수)</span>
            <span style={{ fontSize: 12, color: 'var(--wu-mute)' }}>{showPrivacy ? '▲' : '▼'}</span>
          </button>
          {showPrivacy && (
            <div style={{ padding: '0 12px 12px', maxHeight: 200, overflow: 'auto' }}>
              <div className="kr" style={{ fontSize: 11, color: 'var(--wu-ink-2)', lineHeight: 1.8 }}>
                <strong>1. 수집 항목</strong><br/>
                이름, 이메일 주소, 비밀번호, 닉네임(선택)<br/><br/>
                <strong>2. 수집 목적</strong><br/>
                회원 식별 및 가입 의사 확인, 서비스 이용에 따른 본인 확인, 고지사항 전달, 불만 처리 등 원활한 의사소통 경로 확보, 서비스 개선을 위한 통계 활용<br/><br/>
                <strong>3. 보유 및 이용 기간</strong><br/>
                회원 탈퇴 시까지 (단, 관계법령에 따라 보존이 필요한 경우 해당 기간까지 보관)<br/><br/>
                <strong>4. 동의 거부권 및 불이익</strong><br/>
                귀하는 개인정보 수집·이용에 대한 동의를 거부할 권리가 있습니다. 다만, 필수 항목에 대한 동의를 거부하실 경우 회원가입이 제한됩니다.<br/><br/>
                <strong>5. 개인정보 처리 위탁</strong><br/>
                회사는 서비스 운영을 위해 필요한 경우 개인정보 처리업무를 외부에 위탁할 수 있으며, 위탁 시 관련 법령에 따라 안전하게 관리합니다.
              </div>
            </div>
          )}
        </div>

        <label style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginBottom: 16, cursor: 'pointer' }}>
          <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} style={{ marginTop: 3, width: 16, height: 16, accentColor: 'var(--wu-orange)' }} />
          <span className="kr" style={{ fontSize: 12, color: 'var(--wu-ink)', lineHeight: 1.5, fontWeight: 600 }}>개인정보 수집·이용에 동의합니다 (필수)</span>
        </label>

        {err && <div className="kr" style={{ fontSize: 12, color: 'var(--wu-orange)', marginBottom: 12 }}>⚠ {err}</div>}

        <button onClick={submit} disabled={loading} className="wu-btn block" style={{ padding: '14px', fontSize: 14, width: '100%', background: 'var(--wu-orange)', color: '#fff', opacity: loading ? 0.6 : 1 }}>
          {loading ? '가입 처리 중...' : '가입 완료 →'}
        </button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// SIGNUP — STORE OWNER (requires admin approval)
// ═══════════════════════════════════════════════════════════
function AuthSignupOwner({ onBack, onSignup }) {
  const [form, setForm] = React.useState({ name: '', email: '', password: '', password2: '', phone: '', storeName: '' });
  const [agreed, setAgreed] = React.useState(false);
  const [err, setErr] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [storeList, setStoreList] = React.useState([]);
  const [takenStores, setTakenStores] = React.useState([]);
  const [storeQuery, setStoreQuery] = React.useState('');
  const [showDropdown, setShowDropdown] = React.useState(false);
  const [storesLoaded, setStoresLoaded] = React.useState(false);
  const dropdownRef = React.useRef(null);

  // IndexedDB에서 매장 목록 로드 + 이미 등록된 점주의 매장명 파악
  React.useEffect(() => {
    (async () => {
      try {
        if (typeof getAllStores === 'function' || (window.getAllStores)) {
          const fn = window.getAllStores || getAllStores;
          const stores = await fn();
          setStoreList(stores.map(s => s.name).filter(Boolean));
        }
      } catch(e) { console.error('Store load error:', e); }
      // 이미 등록된 점주의 매장명
      const users = await getUsers();
      const taken = users.filter(u => u.role === 'owner' && u.storeName).map(u => u.storeName);
      setTakenStores(taken);
      setStoresLoaded(true);
    })();
  }, []);

  // 외부 클릭 시 드롭다운 닫기
  React.useEffect(() => {
    const handleClick = (e) => {
      if (dropdownRef.current && !dropdownRef.current.contains(e.target)) setShowDropdown(false);
    };
    document.addEventListener('mousedown', handleClick);
    return () => document.removeEventListener('mousedown', handleClick);
  }, []);

  const filteredStores = storeList.filter(name => {
    if (!storeQuery) return true;
    return name.toLowerCase().includes(storeQuery.toLowerCase());
  });

  const isTaken = (name) => takenStores.includes(name);

  const f = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const [loading, setLoading] = React.useState(false);

  const submit = async () => {
    setErr('');
    if (!form.name || !form.email || !form.password || !form.phone || !form.storeName) { setErr('필수 항목을 모두 입력하세요'); return; }
    if (form.password.length < 6) { setErr('비밀번호는 6자 이상'); return; }
    if (form.password !== form.password2) { setErr('비밀번호 불일치'); return; }
    if (!agreed) { setErr('약관 동의 필요'); return; }
    setLoading(true);
    try {
      const users = await getUsers();
      if (users.find(u => u.email === form.email)) { setErr('이미 등록된 이메일'); setLoading(false); return; }
      // Firebase Auth 회원가입 + 이메일 인증 발송
      await firebaseSignup(form.email, form.password);
      const user = {
        email: form.email, password: form.password, name: form.name, phone: form.phone,
        storeName: form.storeName,
        role: 'owner', status: 'PENDING', createdAt: new Date().toISOString().split('T')[0],
      };
      await addUser(user);
      setDone(true);
    } catch(e) {
      if (e.code === 'auth/email-already-in-use') setErr('이미 등록된 이메일입니다');
      else if (e.code === 'auth/weak-password') setErr('비밀번호가 너무 약합니다');
      else setErr('가입 실패: ' + (e.message || ''));
    }
    setLoading(false);
  };

  if (done) {
    return (
      <div className="wu" style={{ height: '100vh', background: 'var(--wu-ink)', color: 'var(--wu-paper)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div style={{ textAlign: 'center', maxWidth: 400, padding: '0 20px' }}>
          <div style={{ width: 120, height: 120, borderRadius: 999, border: '1.5px dashed var(--wu-orange)', margin: '0 auto', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <div style={{ width: 90, height: 90, borderRadius: 999, background: 'var(--wu-orange)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 36, color: '#fff' }}>⏱</div>
          </div>
          <div className="mono" style={{ fontSize: 11, color: 'var(--wu-orange)', marginTop: 24, letterSpacing: '0.12em' }}>REQUEST SUBMITTED</div>
          <div className="display" style={{ fontSize: 36, marginTop: 8 }}>승인 대기 중</div>
          <div className="kr" style={{ fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 12, lineHeight: 1.6 }}>
            점주 회원가입은 본사 관리자 승인 후 활성화됩니다.<br />승인이 완료되면 로그인하실 수 있습니다.
          </div>
          <div style={{ marginTop: 20, padding: 14, background: '#1A1A17', textAlign: 'left', borderLeft: '3px solid var(--wu-orange)' }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 6 }}>신청 정보</div>
            <div className="kr" style={{ fontSize: 12, lineHeight: 1.8 }}>
              담당자: {form.name}<br />매장명: {form.storeName}<br />이메일: {form.email}<br />연락처: {form.phone}
            </div>
          </div>
          <button onClick={onBack} className="wu-btn" style={{ marginTop: 24, padding: '12px 24px', fontSize: 13, background: 'var(--wu-orange)', color: '#fff' }}>← 로그인 화면으로</button>
        </div>
      </div>
    );
  }

  return (
    <div className="wu wu-scroll" style={{ height: '100vh', background: 'var(--wu-bg)', overflow: 'auto', display: 'flex', justifyContent: 'center', padding: '40px 20px' }}>
      <div style={{ width: 440, padding: '36px 32px', background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', height: 'fit-content' }}>
        <button onClick={onBack} style={{ fontSize: 18, cursor: 'pointer', marginBottom: 16 }}>←</button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
          <span style={{ fontSize: 24 }}>🏪</span>
          <div className="display" style={{ fontSize: 24 }}>점주회원 가입</div>
        </div>
        <div className="kr" style={{ fontSize: 12, color: 'var(--wu-mute)', marginBottom: 8 }}>관리자 승인 후 이용 가능</div>
        <div style={{ padding: '8px 12px', background: 'var(--wu-orange)', color: '#fff', marginBottom: 20 }}>
          <div className="kr" style={{ fontSize: 11, fontWeight: 700 }}>✓ 승인 후 공급가 열람 · 발주 · 매장 관리 등 점주 전용 기능 이용 가능</div>
        </div>

        {[
          ['담당자 이름 *', 'name', 'text', '홍길동'],
          ['이메일 *', 'email', 'email', 'store@workup.co'],
          ['비밀번호 * (6자+)', 'password', 'password', '••••••••'],
          ['비밀번호 확인 *', 'password2', 'password', '••••••••'],
          ['연락처 *', 'phone', 'tel', '010-0000-0000'],
        ].map(([label, key, type, ph]) => (
          <div key={key} style={{ marginBottom: 14 }}>
            <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4 }}>{label.toUpperCase()}</div>
            <input value={form[key]} onChange={e => f(key, e.target.value)} type={type} placeholder={ph} className="kr"
              style={{ width: '100%', padding: '10px 12px', border: '1px solid var(--wu-line)', background: 'var(--wu-bg)', fontSize: 14, fontWeight: 600, outline: 0 }} />
          </div>
        ))}

        {/* 매장 선택 (자동완성) */}
        <div style={{ marginBottom: 14, position: 'relative' }} ref={dropdownRef}>
          <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)', marginBottom: 4 }}>대리점명 * (매장 관리 목록에서 선택)</div>
          <input
            value={storeQuery}
            onChange={e => { setStoreQuery(e.target.value); setShowDropdown(true); f('storeName', ''); }}
            onFocus={() => setShowDropdown(true)}
            placeholder={storesLoaded && storeList.length === 0 ? '등록된 매장이 없습니다' : '매장명 검색 (예: 포천, 성남, 모다)'}
            className="kr"
            style={{ width: '100%', padding: '10px 12px', border: '1px solid ' + (form.storeName ? 'var(--wu-lime)' : 'var(--wu-line)'), background: form.storeName ? '#F0FFD0' : 'var(--wu-bg)', fontSize: 14, fontWeight: 600, outline: 0 }}
          />
          {form.storeName && (
            <div className="kr" style={{ fontSize: 11, color: 'var(--wu-ink)', marginTop: 4, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 6 }}>
              <span style={{ color: 'var(--wu-lime)', fontSize: 14 }}>✓</span> 선택됨: {form.storeName}
              <button onClick={() => { f('storeName', ''); setStoreQuery(''); }} style={{ fontSize: 10, color: 'var(--wu-orange)', cursor: 'pointer', background: 'none', border: 'none', fontWeight: 700 }}>변경</button>
            </div>
          )}
          {showDropdown && !form.storeName && storeList.length > 0 && (
            <div style={{ position: 'absolute', top: '100%', left: 0, right: 0, maxHeight: 200, overflow: 'auto', background: 'var(--wu-paper)', border: '1px solid var(--wu-line)', boxShadow: '0 8px 24px rgba(0,0,0,0.12)', zIndex: 10 }}>
              {filteredStores.length === 0 ? (
                <div className="kr" style={{ padding: '12px 14px', fontSize: 12, color: 'var(--wu-mute)' }}>일치하는 매장이 없습니다</div>
              ) : filteredStores.map(name => {
                const taken = isTaken(name);
                return (
                  <button key={name} disabled={taken} onClick={() => { f('storeName', name); setStoreQuery(name); setShowDropdown(false); }}
                    style={{ display: 'block', width: '100%', padding: '10px 14px', textAlign: 'left', border: 'none', borderBottom: '1px solid var(--wu-line)', background: taken ? '#f5f3ee' : 'var(--wu-paper)', cursor: taken ? 'not-allowed' : 'pointer', opacity: taken ? 0.5 : 1 }}>
                    <div className="kr" style={{ fontSize: 13, fontWeight: 600, color: taken ? 'var(--wu-mute)' : 'var(--wu-ink)' }}>
                      {name}
                      {taken && <span style={{ marginLeft: 8, fontSize: 10, color: '#C44', fontWeight: 700 }}>이미 등록됨</span>}
                    </div>
                  </button>
                );
              })}
            </div>
          )}
          {storesLoaded && storeList.length === 0 && (
            <div className="kr" style={{ fontSize: 11, color: 'var(--wu-orange)', marginTop: 4 }}>⚠ 관리자가 매장 목록을 등록하면 선택 가능합니다</div>
          )}
        </div>

        <label style={{ display: 'flex', alignItems: 'flex-start', gap: 8, marginTop: 12, marginBottom: 16, cursor: 'pointer' }}>
          <input type="checkbox" checked={agreed} onChange={e => setAgreed(e.target.checked)} style={{ marginTop: 3 }} />
          <span className="kr" style={{ fontSize: 11, color: 'var(--wu-mute)', lineHeight: 1.5 }}>이용약관 · 개인정보처리방침에 동의합니다</span>
        </label>

        {err && <div className="kr" style={{ fontSize: 12, color: 'var(--wu-orange)', marginBottom: 12 }}>⚠ {err}</div>}

        <button onClick={submit} disabled={loading} className="wu-btn block" style={{ padding: '14px', fontSize: 14, width: '100%', background: 'var(--wu-orange)', color: '#fff', opacity: loading ? 0.6 : 1 }}>
          {loading ? '가입 처리 중...' : '점주 가입 신청 →'}
        </button>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════
// ADMIN USER MANAGEMENT (inside admin dashboard or HQ)
// ═══════════════════════════════════════════════════════════
function AdminUserManager() {
  const [users, setUsers] = React.useState([]);
  const [filter, setFilter] = React.useState('ALL');

  React.useEffect(() => { getUsers().then(u => setUsers(u)); }, []);
  const refresh = () => getUsers().then(u => setUsers(u));

  const changeStatus = async (email, status) => {
    const all = await getUsers();
    const idx = all.findIndex(u => u.email === email);
    if (idx >= 0) { all[idx].status = status; await saveUsers(all); refresh(); }
  };

  const deleteUser = async (email) => {
    if (email === 'langpoon@gmail.com') return;
    if (!confirm('정말 이 회원을 삭제하시겠습니까?')) return;
    try {
      // Firestore에서 해당 유저 문서 직접 삭제
      if (typeof wu_db !== 'undefined') {
        const snap = await wu_db.collection('users').where('email', '==', email).get();
        const batch = wu_db.batch();
        snap.docs.forEach(doc => batch.delete(doc.ref));
        await batch.commit();
      }
      // localStorage 백업도 정리
      try {
        const raw = localStorage.getItem('wu-auth-users');
        if (raw) {
          const arr = JSON.parse(raw).filter(u => u.email !== email);
          localStorage.setItem('wu-auth-users', JSON.stringify(arr));
        }
      } catch(e) {}
      refresh();
    } catch (err) {
      console.error('deleteUser error:', err);
      // fallback: saveUsers 방식
      const all = (await getUsers()).filter(u => u.email !== email);
      await saveUsers(all);
      refresh();
    }
  };

  // 점주(owner)는 점주 승인 대시보드에서 관리 → 여기서는 제외
  const nonOwnerUsers = users.filter(u => u.role !== 'owner');

  const filtered = nonOwnerUsers.filter(u => {
    if (filter === 'ALL') return true;
    return u.role === filter;
  });
  const counts = { all: nonOwnerUsers.length, consumer: nonOwnerUsers.filter(u => u.role === 'consumer').length, admin: nonOwnerUsers.filter(u => u.role === 'admin').length };

  const Chrome = window.HQChrome || (({ children }) => <div>{children}</div>);
  return (
    <Chrome active="users" title="회원 관리" subtitle="ADMIN · USER MANAGEMENT">
      <div style={{ padding: 28 }}>
        {/* Stats */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10 }}>
          {[['전체', counts.all, 'ALL'], ['일반회원', counts.consumer, 'consumer'], ['관리자', counts.admin, 'admin']].map(([l, n, k]) => (
            <button key={k} onClick={() => setFilter(k)} style={{ background: filter === k ? 'var(--wu-ink)' : 'var(--wu-paper)', color: filter === k ? 'var(--wu-paper)' : 'var(--wu-ink)', border: '1px solid ' + (filter === k ? 'var(--wu-ink)' : 'var(--wu-line)'), padding: 12, textAlign: 'left', cursor: 'pointer' }}>
              <div className="kr" style={{ fontSize: 11 }}>{l}</div>
              <div className="display" style={{ fontSize: 22, marginTop: 2, color: filter === k ? 'var(--wu-lime)' : 'var(--wu-ink)' }}>{n}</div>
            </button>
          ))}
        </div>

        {/* Table */}
        <div style={{ marginTop: 16, background: 'var(--wu-paper)', border: '1px solid var(--wu-line)' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 100px 100px 120px 160px', padding: '10px 16px', fontFamily: 'JetBrains Mono', fontSize: 9, color: 'var(--wu-mute)', background: 'var(--wu-bg)', borderBottom: '1px solid var(--wu-line)' }}>
            <div>이메일</div><div>이름</div><div>역할</div><div>상태</div><div>가입일</div><div>액션</div>
          </div>
          {filtered.map(u => (
            <div key={u.email} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 100px 100px 120px 160px', padding: '12px 16px', borderBottom: '1px solid var(--wu-line)', alignItems: 'center', fontSize: 12 }}>
              <div className="mono" style={{ fontSize: 11 }}>{u.email}</div>
              <div className="kr" style={{ fontWeight: 600 }}>{u.name}{u.storeName ? ` (${u.storeName})` : ''}</div>
              <span className="mono" style={{ fontSize: 9, padding: '2px 6px', fontWeight: 700, width: 'fit-content', background: u.role === 'admin' ? 'var(--wu-ink)' : u.role === 'owner' ? 'var(--wu-orange)' : 'var(--wu-lime)', color: u.role === 'admin' ? 'var(--wu-lime)' : u.role === 'owner' ? '#fff' : 'var(--wu-ink)' }}>
                {u.role === 'admin' ? '관리자' : u.role === 'owner' ? '점주' : '일반'}
              </span>
              <span className="mono" style={{ fontSize: 9, padding: '2px 6px', fontWeight: 700, width: 'fit-content', background: u.status === 'APPROVED' ? 'var(--wu-lime)' : u.status === 'PENDING' ? 'var(--wu-orange)' : u.status === 'PENDING_VERIFY' ? '#FFD700' : '#C44', color: u.status === 'APPROVED' ? 'var(--wu-ink)' : u.status === 'PENDING_VERIFY' ? 'var(--wu-ink)' : '#fff' }}>
                {u.status === 'APPROVED' ? '승인' : u.status === 'PENDING' ? '승인대기' : u.status === 'PENDING_VERIFY' ? '메일인증대기' : '반려'}
              </span>
              <div className="mono" style={{ fontSize: 10, color: 'var(--wu-mute)' }}>{u.createdAt}</div>
              <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                {(u.status === 'PENDING' || u.status === 'PENDING_VERIFY') && (
                  <>
                    <button onClick={() => changeStatus(u.email, 'APPROVED')} style={{ padding: '4px 8px', fontSize: 10, fontWeight: 700, fontFamily: 'JetBrains Mono', background: 'var(--wu-lime)', color: 'var(--wu-ink)', border: 0, cursor: 'pointer' }}>승인</button>
                    <button onClick={() => changeStatus(u.email, 'REJECTED')} style={{ padding: '4px 8px', fontSize: 10, fontWeight: 700, fontFamily: 'JetBrains Mono', background: '#C44', color: '#fff', border: 0, cursor: 'pointer' }}>반려</button>
                  </>
                )}
                {u.email !== 'langpoon@gmail.com' && (
                  <button onClick={() => deleteUser(u.email)} style={{ padding: '4px 8px', fontSize: 10, fontWeight: 700, fontFamily: 'JetBrains Mono', background: 'var(--wu-bg)', color: '#C44', border: '1px solid #C44', cursor: 'pointer' }}>삭제</button>
                )}
              </div>
            </div>
          ))}
        </div>
      </div>
    </Chrome>
  );
}

Object.assign(window, { AuthLogin, AuthSignupConsumer, AuthSignupOwner, AdminUserManager });
