// Naviyell — A-21 パスワード変更 screen

// resetMode=true: skip current-password field and re-auth (used for email-link reset flow)
// resetMode=false (default): normal change-password flow from MyPage
function A21PasswordEdit({ resetMode = false }) {
  const nav = useNav();
  const { state } = useAppState();
  const user = state.currentUser;
  const userEmail = user?.email || '';

  // Google OAuth users have no existing password — skip re-auth and relabel as "set"
  const isOAuthUser = user?.app_metadata?.provider !== 'email';
  const needsCurrentPassword = !resetMode && !isOAuthUser;

  const [currentPassword, setCurrentPassword] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [confirmPassword, setConfirmPassword] = React.useState('');
  const [showPasswords, setShowPasswords] = React.useState(false);
  const [error, setError] = React.useState('');
  const [success, setSuccess] = React.useState(false);
  const [loading, setLoading] = React.useState(false);

  const handleSubmit = async () => {
    setError('');
    if (needsCurrentPassword && !currentPassword) {
      setError('現在のパスワードを入力してください'); return;
    }
    if (!newPassword) {
      setError('新しいパスワードを入力してください'); return;
    }
    if (newPassword.length < 8) {
      setError('パスワードは8文字以上で入力してください'); return;
    }
    if (newPassword !== confirmPassword) {
      setError('新しいパスワードが確認用と一致しません'); return;
    }
    if (needsCurrentPassword && newPassword === currentPassword) {
      setError('現在のパスワードと同じです'); return;
    }

    setLoading(true);
    try {
      if (typeof DB !== 'undefined' && DB.updatePassword) {
        if (needsCurrentPassword) await DB.signIn(userEmail, currentPassword);
        await DB.updatePassword(newPassword);
      } else {
        localStorage.setItem('naviyell_password_changed', 'true');
      }
      setSuccess(true);
      setTimeout(() => (resetMode ? nav.go('login') : nav.back('mypage')), 2000);
    } catch (err) {
      console.error('[PasswordEdit]', err.message);
      setError(err.message || 'エラーが発生しました。もう一度お試しください。');
    } finally {
      setLoading(false);
    }
  };

  const isSettingNew = isOAuthUser && !resetMode;
  const title = resetMode ? 'パスワードの再設定' : isSettingNew ? 'パスワードを設定する' : 'パスワード変更';
  const infoText = resetMode
    ? 'メールで確認済みです。新しいパスワードを設定してください。8文字以上で入力してください。'
    : isSettingNew
    ? 'Googleアカウントでログイン中です。パスワードを設定すると、メールアドレスでもログインできるようになります。8文字以上で設定してください。'
    : '新しいパスワードは8文字以上で設定してください。変更後は、次回ログイン時から新しいパスワードが有効になります。';
  const successText = resetMode
    ? 'パスワードを再設定しました。新しいパスワードでログインしてください。'
    : isSettingNew
    ? 'パスワードを設定しました。次回からメールアドレスでもログインできます。'
    : 'パスワードを変更しました。次回ログイン時から新しいパスワードが有効です。';

  return (
    <div className='ac-screen' style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
      <ACTopBar leading={!resetMode && <ACBack onClick={() => nav.back('mypage')} />} title={title} />
      <div style={{ flex: 1, overflow: 'auto', padding: '16px 20px 20px' }} className='ac-scroll'>
        {/* Info card */}
        <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,
          }}>
          {infoText}
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
          {/* Current password — only for email/password accounts in normal change mode */}
          {needsCurrentPassword && (
            <PasswordInput
              label='現在のパスワード'
              value={currentPassword}
              onChange={(v) => { setCurrentPassword(v); setError(''); }}
              placeholder='現在のパスワードを入力'
              showPassword={showPasswords}
              onTogglePassword={() => setShowPasswords(!showPasswords)}
            />
          )}

          {/* New password */}
          <PasswordInput
            label='新しいパスワード'
            value={newPassword}
            onChange={(v) => { setNewPassword(v); setError(''); }}
            placeholder='8文字以上で入力'
            showPassword={showPasswords}
            onTogglePassword={() => setShowPasswords(!showPasswords)}
          />

          {/* Confirm new password */}
          <PasswordInput
            label='新しいパスワード（確認）'
            value={confirmPassword}
            onChange={(v) => { setConfirmPassword(v); setError(''); }}
            placeholder='もう一度入力してください'
            type='password'
            showPassword={showPasswords}
            onTogglePassword={() => setShowPasswords(!showPasswords)}
            error={error && confirmPassword && newPassword !== confirmPassword ? 'パスワードが一致しません' : ''}
          />

          {/* 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>
              {successText}
            </div>
          )}
        </div>
      </div>

      <ACStickyCTA>
        <ACButton size='lg' onClick={handleSubmit} disabled={loading || success}>
          {loading ? '送信中...' : success ? '✓ 設定しました' : title}
        </ACButton>
      </ACStickyCTA>
    </div>
  );
}

// Password input with show/hide toggle
function PasswordInput({ label, value, onChange, placeholder, type = 'password', showPassword, onTogglePassword, error }) {
  return (
    <div>
      <div style={{ fontSize: 13, fontWeight: 500, color: A.ink500, marginBottom: 6 }}>{label}</div>
      <div style={{ position: 'relative' }}>
        <input
          type={showPassword ? 'text' : 'password'}
          value={value}
          onChange={(e) => onChange(e.target.value)}
          placeholder={placeholder}
          style={{
            width: '100%',
            height: 52,
            padding: '0 48px 0 16px',
            borderRadius: 12,
            background: A.white,
            border: `1.5px solid ${error ? A.danger : A.ink100}`,
            fontSize: 15,
            color: A.ink900,
            fontFamily: 'inherit',
            outline: 'none',
            boxSizing: 'border-box',
          }}
          onFocus={(e) => (e.target.style.borderColor = A.gold500)}
          onBlur={(e) => (e.target.style.borderColor = error ? A.danger : A.ink100)}
        />
        <button
          onClick={onTogglePassword}
          type='button'
          style={{
            position: 'absolute',
            right: 12,
            top: '50%',
            transform: 'translateY(-50%)',
            width: 32,
            height: 32,
            borderRadius: 8,
            border: 'none',
            background: 'transparent',
            cursor: 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: 0,
            color: A.ink500,
          }}>
          {showPassword ? (
            <svg width='20' height='20' viewBox='0 0 24 24' fill='none' stroke='currentColor' strokeWidth='2' strokeLinecap='round' strokeLinejoin='round'>
              <path d='M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24' />
              <line x1='1' y1='1' x2='23' y2='23' />
            </svg>
          ) : (
            <svg width='20' height='20' viewBox='0 0 24 24' fill='none' stroke='currentColor' strokeWidth='2' strokeLinecap='round' strokeLinejoin='round'>
              <path d='M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z' />
              <circle cx='12' cy='12' r='3' />
            </svg>
          )}
        </button>
      </div>
      {error && (
        <div style={{ fontSize: 12, color: A.danger, marginTop: 6 }}>{error}</div>
      )}
    </div>
  );
}

// Thin wrapper used by the 'password-reset' route — same screen in reset mode
function A21PasswordReset() {
  return React.createElement(A21PasswordEdit, { resetMode: true });
}

Object.assign(window, { A21PasswordEdit, A21PasswordReset });
