// Naviyell — A-20 メールアドレス変更 screen

function A20EmailEdit() {
  const nav = useNav();
  const { state, patch } = useAppState();
  const user = state.currentUser;
  const currentEmail = user?.email || '';

  // Google OAuth users have no password — detect so we can skip re-auth
  const isOAuthUser = user?.app_metadata?.provider !== 'email';

  // Supabase keeps new_email populated while the change is pending confirmation
  const pendingEmail = user?.new_email || state.pendingEmail || '';

  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const handleSubmit = async () => {
    setError('');
    if (!email.trim()) { setError('メールアドレスを入力してください'); return; }
    if (!/\S+@\S+\.\S+/.test(email)) { setError('正しいメールアドレス形式で入力してください'); return; }
    if (email === currentEmail) { setError('現在のメールアドレスと同じです'); return; }
    if (!isOAuthUser && !password) { setError('確認のためパスワードを入力してください'); return; }

    setLoading(true);
    try {
      if (typeof DB !== 'undefined' && DB.updateEmail) {
        // Re-authenticate first for email/password users only
        if (!isOAuthUser) await DB.signIn(currentEmail, password);
        await DB.updateEmail(email);
      } else {
        localStorage.setItem('naviyell_email', email);
      }
      patch({ pendingEmail: email });
      setSuccess(true);
      setTimeout(() => nav.back('mypage'), 1800);
    } catch (err) {
      console.error('[EmailEdit]', err.message);
      setError(err.message || 'エラーが発生しました。もう一度お試しください。');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={<ACBack onClick={() => nav.back('mypage')} />} title='メールアドレス変更' />
      <div style={{ flex: 1, overflow: 'auto', padding: '16px 20px 20px' }} className='ac-scroll'>
        {/* Pending change notice */}
        {pendingEmail && !success && (
          <div
            style={{
              display: 'flex',
              gap: 10,
              background: '#FFF8E6',
              borderRadius: 14,
              padding: 14,
              border: `1px solid ${A.gold300 || A.gold500}`,
              marginBottom: 16,
              fontSize: 12,
              color: A.ink700,
              lineHeight: 1.7,
            }}>
            <svg width='16' height='16' viewBox='0 0 24 24' fill='none' stroke={A.gold600} strokeWidth='2' style={{ flexShrink: 0, marginTop: 1 }}>
              <circle cx='12' cy='12' r='10' />
              <path d='M12 8v4M12 16h0' strokeLinecap='round' />
            </svg>
            <span>
              <strong>{pendingEmail}</strong> への確認メールを送信済みです。メール内のリンクをクリックすると変更が完了します。
            </span>
          </div>
        )}

        {/* Info card */}
        {!pendingEmail && (
          <div
            style={{
              background: `${A.gold100}55`,
              borderRadius: 14,
              padding: 14,
              border: `1px solid ${A.gold100}`,
              marginBottom: 24,
              fontSize: 12,
              color: A.ink700,
              lineHeight: 1.7,
            }}>
            新しいメールアドレスを入力してください。変更完了後、新しいアドレスに確認メールが送信されます。
            メール内のリンクをクリックすると、アドレスが確定します。
          </div>
        )}

        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Current email (read-only) */}
          <div>
            <div style={{ fontSize: 13, fontWeight: 500, color: A.ink500, marginBottom: 6 }}>現在のメールアドレス</div>
            <div
              style={{
                width: '100%',
                height: 52,
                padding: '0 16px',
                borderRadius: 12,
                background: A.paper2,
                border: `1.5px solid ${A.ink100}`,
                fontSize: 15,
                color: A.ink500,
                display: 'flex',
                alignItems: 'center',
              }}>
              {currentEmail}
            </div>
          </div>

          {/* New email */}
          <ACInput
            label='新しいメールアドレス'
            value={email}
            onChange={(v) => { setEmail(v); setError(''); }}
            placeholder='new@example.com'
            type='email'
          />

          {/* Password confirmation — only for email/password accounts */}
          {!isOAuthUser && (
            <ACInput
              label='現在のパスワード（確認）'
              value={password}
              onChange={(v) => { setPassword(v); setError(''); }}
              placeholder='パスワードを入力'
              type='password'
            />
          )}

          {/* Error message */}
          {error && (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                padding: '12px 16px',
                borderRadius: 12,
                background: '#F5DDD9',
                color: A.danger,
                fontSize: 13,
                fontWeight: 500,
                animation: 'ac-fade-in 200ms ease both',
              }}>
              <svg width='16' height='16' viewBox='0 0 24 24' fill='none' stroke={A.danger} strokeWidth='2'>
                <circle cx='12' cy='12' r='10' />
                <path d='M12 8v4M12 16h0' strokeLinecap='round' />
              </svg>
              {error}
            </div>
          )}

          {/* Success message */}
          {success && (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 8,
                padding: '12px 16px',
                borderRadius: 12,
                background: '#E8F0E5',
                color: A.success,
                fontSize: 13,
                fontWeight: 500,
                animation: 'ac-fade-in 200ms ease both',
              }}>
              <svg width='16' height='16' viewBox='0 0 24 24' fill='none' stroke={A.success} strokeWidth='2'>
                <path d='M22 11.1V12a10 10 0 1 1-5.9-9.1' strokeLinecap='round' />
                <path d='M22 4L12 14l-3-3' strokeLinecap='round' strokeLinejoin='round' />
              </svg>
              確認メールを送信しました。新しいアドレスをご確認ください。
            </div>
          )}
        </div>
      </div>

      <ACStickyCTA>
        <ACButton size='lg' onClick={handleSubmit} disabled={loading || success || !!pendingEmail}>
          {loading ? '送信中...' : success ? '✓ 送信しました' : pendingEmail ? '確認メール送信済み' : '変更メールを送信する'}
        </ACButton>
      </ACStickyCTA>
    </div>
  );
}

Object.assign(window, { A20EmailEdit });